diff --git a/incari-client/PROVENANCE.json b/incari-client/PROVENANCE.json new file mode 100644 index 0000000..ab4a5ba --- /dev/null +++ b/incari-client/PROVENANCE.json @@ -0,0 +1,46 @@ +{ + "slug": "incari-client", + "name": "Incari Client", + "category": "client", + "mc_version": "26.3", + "author": "incari-client", + "license": "unknown", + "upstream_ref": "unknown", + "sha256": "66e09605ba2fb5c5bbf3e3c20f60b5ac2f0d35d86e653afc24019109d32d1715", + "size": 12142449, + "storage": { + "git_path": "incari-client/", + "fs_url": "https://fs-archive.eaglercraft.tech/archives/incari-client.tar.gz" + }, + "play": { + "sandbox_url": "https://play-archive.eaglercraft.tech/incari-client/", + "sandbox_attr": "allow-scripts allow-same-origin allow-pointer-lock", + "network_notes": "May connect to user-chosen wss:// multiplayer servers." + }, + "sources": [ + { + "url": "https://github.com/incari-client/incari-client", + "retrieved_at": "2026-11-28T06:10:00Z", + "type": "upstream", + "notes": "Official GitHub repository for Incari Client." + }, + { + "url": "https://incariclient.org/", + "retrieved_at": "2026-11-28T06:10:00Z", + "type": "upstream", + "notes": "Official Incari Client website and web portal." + } + ], + "vetting": { + "verdict": "clean", + "tools": [ + "vet-static.mjs", + "virustotal-hash", + "static-code-review" + ], + "date": "2026-11-28", + "notes": "Standard Eaglercraft/Incari client and build tooling (WebSocket, IndexedDB/fetch storage-worker, smoke tests, ffmpeg/wasm-opt ProcessBuilder).", + "reviewer": "vet-gemini-2" + }, + "large_files_omitted_from_git": [] +} diff --git a/incari-client/README.md b/incari-client/README.md new file mode 100644 index 0000000..7952a28 --- /dev/null +++ b/incari-client/README.md @@ -0,0 +1,12 @@ +# Incari Client + +Open-source browser-based Minecraft client compiled with TeaVM to WebAssembly with a WebGL2 renderer, Web Worker singleplayer, and 25+ PvP and quality-of-life modules. + +- **Archive page:** https://archive.eaglercraft.tech/clients/incari-client.html +- **Play:** https://play-archive.eaglercraft.tech/incari-client/ +- **Large download (fs-archive):** https://fs-archive.eaglercraft.tech/archives/incari-client.tar.gz +- **MC Version:** 26.3 +- **Author:** incari-client +- **License:** unknown +- **SHA-256:** `66e09605ba2fb5c5bbf3e3c20f60b5ac2f0d35d86e653afc24019109d32d1715` +- **Vetting:** clean (2026-11-28) diff --git a/incari-client/files/.github/CODEOWNERS b/incari-client/files/.github/CODEOWNERS new file mode 100644 index 0000000..d31cb4b --- /dev/null +++ b/incari-client/files/.github/CODEOWNERS @@ -0,0 +1,19 @@ +# Changes here need a human reviewer. Agents may +# open pull requests that touch these paths, but a person approves them. + +# Patches into Mojang code and the manifest of replaced classes. +/patches/ @incari-client +# Graphics and networking. +/render-*/ @incari-client +/tools/shaders/ @incari-client +/net/ @incari-client +# Licensing, and the guards and workflow that keep the repo legal. +/LICENSE @incari-client +/LICENSE-EXCEPTION.txt @incari-client +/DCO.txt @incari-client +/docs/adr/0002-* @incari-client +/.github/ @incari-client +/tools/ci/ @incari-client +/tools/copycheck/ @incari-client +# The architecture's allowed dependencies. +/gradle/module-boundaries.txt @incari-client diff --git a/incari-client/files/.github/ISSUE_TEMPLATE/bug_report.yml b/incari-client/files/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..043b27c --- /dev/null +++ b/incari-client/files/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,51 @@ +name: Bug report +description: Something in Incari Client doesn't work as it should. +labels: [bug] +body: + - type: markdown + attributes: + value: | + Thanks for reporting! Please don't attach or link a playable build, and don't share passwords or recovery codes. + - type: textarea + id: what + attributes: + label: What happened + description: What you did, what you expected, and what happened instead. + validations: + required: true + - type: textarea + id: steps + attributes: + label: Steps to reproduce + placeholder: | + 1. Join a 1.8.9 server + 2. Open the module menu + 3. ... + - type: input + id: version + attributes: + label: Incari Client version + description: Shown at the bottom left of the title screen. + - type: dropdown + id: build + attributes: + label: Build + options: + - Fast + - Compatible + - Offline HTML file + - Not sure + - type: input + id: browser + attributes: + label: Browser and device + placeholder: Chrome 141 on a school Chromebook + - type: input + id: server + attributes: + label: Server and its version (if any) + - type: textarea + id: extra + attributes: + label: Anything else + description: Screenshots, the browser console's errors (F12), what you've tried. diff --git a/incari-client/files/.github/ISSUE_TEMPLATE/config.yml b/incari-client/files/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..e117341 --- /dev/null +++ b/incari-client/files/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,8 @@ +blank_issues_enabled: false +contact_links: + - name: Feedback and ideas + url: https://github.com/incari-client/incari-client/discussions/new?category=feedback + about: Suggestions, feature ideas and what you think of Incari Client go to Discussions. + - name: Security problem + url: https://github.com/incari-client/incari-client/security/advisories/new + about: Report vulnerabilities privately, never in a public issue (see SECURITY.md). diff --git a/incari-client/files/.github/pull_request_template.md b/incari-client/files/.github/pull_request_template.md new file mode 100644 index 0000000..6fa246e --- /dev/null +++ b/incari-client/files/.github/pull_request_template.md @@ -0,0 +1,25 @@ +## What + + + +## Why + + + +## Performance impact + + + +## Screenshots + + + +## Checklist + +- [ ] `./gradlew check` and `npm run check` pass locally +- [ ] `./incari rebuild --check` and `./incari copycheck` pass (if Java or patches changed) +- [ ] Patches are one- or two-line hooks into Incari modules, marked `// Incari start: ` / `// Incari end` +- [ ] No Mojang content, builds or links to playable builds; nothing copied from the decompiled game +- [ ] Tests cover the change, and the module README still describes it +- [ ] Every commit is signed off (`git commit -s`) diff --git a/incari-client/files/.github/workflows/ci.yml b/incari-client/files/.github/workflows/ci.yml new file mode 100644 index 0000000..3cc9065 --- /dev/null +++ b/incari-client/files/.github/workflows/ci.yml @@ -0,0 +1,140 @@ +# CI for the Incari repo. It builds and tests, and never publishes anything: every Incari build +# contains Mojang code (CONTRIBUTING.md). tools/ci/check-no-publishing.sh enforces that on this file. +name: CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + guards: + name: Repo guards + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + - name: No Mojang content or builds tracked + run: tools/ci/check-repo-content.sh + - name: No workflow publishes builds + run: tools/ci/check-no-publishing.sh + - name: Every commit is signed off (DCO) + if: github.event_name == 'pull_request' + run: tools/ci/check-dco.sh "${{ github.event.pull_request.base.sha }}" "${{ github.event.pull_request.head.sha }}" + - name: Patch budget + run: tools/ci/check-patch-budget.sh + - name: Every feature has a Rust status + run: tools/ci/check-rust-status.sh + - name: No hard-coded Minecraft version + run: tools/ci/check-version-literals.sh + - name: Install glslang + run: sudo apt-get install -y --no-install-recommends glslang-tools + - name: Shaders validate + run: tools/ci/check-glsl.sh + + typescript: + name: TypeScript + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: 26 + cache: npm + - run: npm ci + - name: Types, lint, format and tests + run: npm run check + + rust: + name: Rust build's mods + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + # The mods' own logic, without Horizon: the Rust build itself needs the game's files. + - name: Format, lints and tests + working-directory: rust + run: | + cargo fmt --check + cargo clippy --all-targets -- -D warnings + cargo test + + java: + name: Java, patches and vendor build + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-java@v6 + with: + distribution: temurin + java-version: 25 + - uses: gradle/actions/setup-gradle@v5 + # Downloads the pinned jar from Mojang and decompiles it inside the runner. The result stays + # in work/ on the runner and is never cached or uploaded. + - name: Fresh clone to patched tree + run: ./incari setup + - name: Patches round-trip (and replaced classes stamped) + run: ./incari rebuild --check + - name: Library pins match Minecraft's + run: tools/ci/check-mojang-pins.sh + # Formatting, Error Prone and NullAway, module boundaries, ArchUnit and unit tests, and the + # full client compiled from the patched tree. That includes the tests that parse + # app-web/download-budget.properties; the size check itself (:app-web:checkDownloadSize) runs + # where the browser build is compiled, which needs more memory (a 20 GB heap) than a hosted + # runner has. + - name: Build and check + run: ./gradlew check + # Translates every shader the game can compile to GLSL ES 3.00 for the WebGL2 backend, and has + # glslang compile and link each program (required in CI). Seconds, unlike the browser build. + # The output holds translated Mojang shaders: it stays on the runner and is never uploaded. + - name: Install glslang + run: sudo apt-get install -y --no-install-recommends glslang-tools + - name: Shaders translate for WebGL2 + run: ./gradlew :app-web:shaders + - name: No Incari code copied from the game + run: ./incari copycheck + + # The performance report (ADR 0021). The browser build needs more memory (a 20 GB heap) + # and a GPU than a hosted runner has, so this runs on a self-hosted runner labelled incari-perf + # (docs/benchmark.md sets one up), and only once the repository variable + # INCARI_PERF_RUNNER is 'true'. Never for pull requests from forks, whose code would run on that + # machine. The build, the world and every render stay on the runner; only the figures reach the + # job summary, which is the pull request's performance report. A figure that regressed past its + # rule against the runner's baseline (app-web/benchmark/baseline.properties) fails the job. + perf: + name: Performance report + if: >- + vars.INCARI_PERF_RUNNER == 'true' && + (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) + runs-on: [self-hosted, incari-perf] + timeout-minutes: 120 + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-java@v6 + with: + distribution: temurin + java-version: 25 + # The page's scripts are TypeScript, stripped by Node. + - uses: actions/setup-node@v7 + with: + node-version: 26 + # The game, decompiled and patched, and its asset index, in work/ on the runner only. + - name: Fresh clone to patched tree + run: ./incari setup + - name: Asset index + run: ./incari assets + # Compiles the browser build (build/teavm/, never uploaded) and measures the download. The + # release build: what players get, and what the budgets are about (ADR 0025). + - name: Download size + run: ./gradlew :app-web:checkDownloadSize -PdownloadSize.noBrotli -Pteavm.release + - name: Benchmark + run: >- + ./gradlew :app-web:benchmark -Pbenchmark.skipBuild -Pteavm.release + -Pbenchmark.machine=${{ vars.INCARI_PERF_MACHINE || 'desktop' }} diff --git a/incari-client/files/.gitignore b/incari-client/files/.gitignore new file mode 100644 index 0000000..42d9f7f --- /dev/null +++ b/incari-client/files/.gitignore @@ -0,0 +1,85 @@ +# --------------------------------------------------------------------------- +# Mojang content: NEVER commit. The repo must stay patch-only (see AGENTS.md). +# --------------------------------------------------------------------------- + +# Generated workspace: downloaded jars, decompiled game source, patched tree +/work/ + +# Any jar (Minecraft client/server jars, libraries). Gradle wrapper is the only exception. +*.jar +!/gradle/wrapper/gradle-wrapper.jar + +# Downloaded or extracted game assets, asset indexes, caches +/assets-cache/ +/mojang/ +.minecraft/ + +# Desktop dev runtime game directory (options.txt, saves, screenshots, logs) +/run/ +crash-reports/ +logs/ + +# --------------------------------------------------------------------------- +# Build outputs: compiled clients contain Mojang code. Never commit or publish. +# --------------------------------------------------------------------------- +**/build/ +# ...except tools/build, the build CLI's own module, and source packages named "build". +!/tools/build/ +!**/src/**/build/ +out/ +dist/ +target/ +*.wasm +*.wasm.map +*.teavmdbg +/offline/ + +# --------------------------------------------------------------------------- +# Tooling +# --------------------------------------------------------------------------- +.gradle/ +.kotlin/ +node_modules/ +.pnpm-store/ +.npm/ +playwright-report/ +test-results/ +blob-report/ +*.log + +# IDEs and editors +.idea/ +*.iml +.vscode/* +!.vscode/extensions.json +!.vscode/settings.json +.settings/ +.project +.classpath +*.swp +*~ + +# OS +.DS_Store +Thumbs.db + +# --------------------------------------------------------------------------- +# Secrets: keys and credentials live in environment variables, never git +# --------------------------------------------------------------------------- +.env +.env.* +*.pem +*.key +*.p12 +secrets/ + +# Claude Code: local settings and a checkout's private notes (shared settings in +# .claude/settings.json are fine) +.claude/settings.local.json +CLAUDE.local.md + +# Agent instructions ARE tracked, even where a global ignore rule excludes them. +!CLAUDE.md +!**/CLAUDE.md +!AGENTS.md +!**/AGENTS.md diff --git a/incari-client/files/.prettierignore b/incari-client/files/.prettierignore new file mode 100644 index 0000000..921499d --- /dev/null +++ b/incari-client/files/.prettierignore @@ -0,0 +1,13 @@ +# Prettier formats Incari's TypeScript and the files that configure it. Everything else has its +# own formatter (Java: Spotless) or isn't reformatted at all (the vendor tree, patches, docs). +* +!*/ +!app-web/src/**/*.ts +!platform-web/src/**/*.ts +!platform-web/src/**/*.js +!package.json +!tsconfig.json +!.prettierrc.json +work/ +node_modules/ +**/build/ diff --git a/incari-client/files/.prettierrc.json b/incari-client/files/.prettierrc.json new file mode 100644 index 0000000..963354f --- /dev/null +++ b/incari-client/files/.prettierrc.json @@ -0,0 +1,3 @@ +{ + "printWidth": 120 +} diff --git a/incari-client/files/AGENTS.md b/incari-client/files/AGENTS.md new file mode 100644 index 0000000..b68a229 --- /dev/null +++ b/incari-client/files/AGENTS.md @@ -0,0 +1,104 @@ +# Agent instructions for Incari + +Rules and commands for AI agents (and people) working here. Each module also has an `AGENTS.md` +with its own rules and a `README.md` saying what it does and how to test it. + +## The project + +Incari ports Minecraft: Java Edition's latest release to the browser and builds a PvP/QoL client on +it. Top priority: performance on typical crappy school Chromebooks. + +- **Patch-only:** the game is downloaded and decompiled into `work/` (git-ignored); the repo holds + Incari's code and `patches/` (ADR 0001). +- **Target:** Minecraft 26.3 (unobfuscated, Java 25). +- **Compiler:** TeaVM 0.16.0, WebAssembly GC, two builds: Fast (JSPI) and Compatible (coroutines) + (ADR 0036). Vineflower 1.12.0 decompiles. Both pinned exactly. +- **Graphics:** WebGL2 under Mojang's `GpuDevice` API, shaders translated at build time. +- **Networking:** WebSocket, Eagler's handshake, and ViaVersion in the client (any server 1.8+). + +| To learn | Read | +| --- | --- | +| Layers and modules | [`ARCHITECTURE.md`](ARCHITECTURE.md), `gradle/module-boundaries.txt` | +| Why it's built this way | [`docs/adr/README.md`](docs/adr/README.md) | +| Threads in the browser | [`docs/threading.md`](docs/threading.md) | +| Measuring performance | [`docs/benchmark.md`](docs/benchmark.md) | +| Moving to a new Minecraft release | [`docs/updating.md`](docs/updating.md) | + +## Hard rules + +- **Never commit Mojang files or anything from `work/`**: jars, decompiled source, textures, + sounds, models, language files, shaders (translated too), data dumps. +- **Never commit or publish a build**, or link to a hosted one. +- **Never copy decompiled code into an Incari module.** `./incari copycheck` checks. +- **Never hand-edit `patches/`.** Commit in `work/client`, then `./incari rebuild`. +- **Never reformat vendor code** or edit it to silence a warning. +- **Never commit secrets.** Use environment variables. +- **Run the module's tests before finishing**, and say what you ran. + +## Commands + +Needs JDK 25+, git and Node 24+. + +```sh +./incari setup # fresh clone -> patched tree in work/client +./gradlew check # all Java gates and tests, plus the client build +./gradlew ::check # one module +./gradlew spotlessApply # format Java +npm ci && npm run check # TypeScript +./incari rebuild [--check] # work/client commits -> patches/ (--check: fail if stale) +./incari classes [--stamp] # replaced classes whose Mojang original changed (--stamp: reviewed) +./incari copycheck # nothing copied from the game +tools/ci/check-patch-budget.sh # patch size against patches/budget.properties + +./incari assets # once: the game's sounds and languages +./gradlew :app-desktop:run # play on the desktop +./gradlew :app-desktop:smokeTest # unattended session (also smokeHost + smokeJoin) +./gradlew :app-web:teavm # browser build, ~10 minutes, ~20 GB memory +./gradlew :app-web:serve # serve it on localhost +./gradlew :app-web:browserCheck # run it headless until the game loop ticks +./incari build --only rust # the experimental Rust build on Horizon (ADR 0068, rust/README.md) +cargo test --manifest-path rust/Cargo.toml # the Rust build's mods +``` + +- Smoke tasks can say `BUILD SUCCESSFUL` with failures inside. Read the report they write. +- `./incari survey` must run on exactly JDK 25. + +## Where you can run what + +- **Rendering, audio and performance need a real GPU and display.** Without one, build and run + unit tests, but don't claim rendering or performance results. `browserCheck` uses SwiftShader by + default; `-Pbrowser.gpu=gl` uses the GPU. +- **Network:** allow Mojang (`piston-meta.mojang.com`, `piston-data.mojang.com`, + `resources.download.minecraft.net`), Maven Central and `repo.viaversion.com`. + +## Changing game code + +1. Edit `work/client/src/main/java`: a one- or two-line hook into an Incari module, marked + `// Incari start: ` and `// Incari end`. +2. Create an equivalent module/change in the experimental Rust port. +2. Commit in `work/client`, one concern each, subject `: `. +3. `./incari rebuild`, then commit `patches/` here. + +Whole-class deletes or replacements go in `patches/classes.txt`. + +## Where code goes + +- Logic goes in a strict module (`platform-*`, `render-*`, `net`, `mesher`, `framework`, `online`, + `features/*`). `client`'s own code is only the adapter the patches call. +- Platform modules never see game types. `features/*` depend only on `framework`. +- Use Mojang's official names. Comments explain why, especially browser limits ("must not block", + "worker-side, no game objects", "hot path, don't allocate"). +- Player-facing text is plain words, fitted to its box (`Ui.fit`, `Ui.wrap`). Screens fit 320x240 + GUI units; `./gradlew :app-desktop:smokeLayout` checks. + +## Docs + +Write short: the point first, plain words, tables and lists over paragraphs, each fact once. + +- New decision → an ADR in `docs/adr/` plus a line in its index. +- Module changed → its `README.md`, and `ARCHITECTURE.md` if the module table changes. + +## Commits + +Sign off every commit (`git commit -s`). Subjects are `: `. Renderer, networking, +patch and licensing changes need a human reviewer (`.github/CODEOWNERS`). diff --git a/incari-client/files/ARCHITECTURE.md b/incari-client/files/ARCHITECTURE.md new file mode 100644 index 0000000..a9a0506 --- /dev/null +++ b/incari-client/files/ARCHITECTURE.md @@ -0,0 +1,105 @@ +# Incari architecture + +Incari compiles Minecraft's Java client to WebAssembly with TeaVM. The game's code runs almost +unchanged. Everything underneath it is different. The reasons behind each decision are in +[`docs/adr/`](docs/adr/README.md), and terms are defined in [`docs/glossary.md`](docs/glossary.md). + +## Layers + +| Layer | What | Where | +| --- | --- | --- | +| 5. Incari features | Module framework, modules, UI kit and look | `framework`, `features/*`, `online`, `client`'s `modules` and `ui` | +| 4. Performance rewrites | Worker mesher, batched terrain, culling, memory diet, start-up | `mesher`, `render-webgl2`, `client`, patches | +| 3. Minecraft client | The decompiled 26.3 client, compiled nearly as-is | `work/client` (generated), built by `client` | +| 2. Java libraries | Mojang's pinned libraries (fastutil, Guava, Gson, JOML, Netty…), ViaVersion | Mojang's jars, Maven | +| 1. Platform | Window, input, audio, graphics surface, networking, storage, threads | `platform-api`, `platform-desktop`, `platform-web` | + +The game reaches the machine only through layer 1. On the desktop that's LWJGL, so the game can be +debugged on a normal JVM. In the browser it's canvas, DOM events, Web Audio, WebSocket and OPFS. + +## Modules + +`gradle/module-boundaries.txt` lists which module may depend on which, and `./gradlew check` fails +on anything else. ArchUnit tests add package rules (no LWJGL in shared code, no game types in the +platform layer). + +``` + app-desktop app-web + / \ / | \ + platform-desktop client ─── render-webgl2 | platform-web + \ / / | \ | / + \ mesher via | net | / + \ | / | / + └──── platform-api ─────────────────┴────┘ +``` + +| Module | Owns | May depend on | +| --- | --- | --- | +| `platform-api` | The `Platform*` interfaces: window, input, audio, files, threads, worker pools, WebRTC, profiling | nothing | +| `platform-desktop` | The LWJGL implementation, for development | `platform-api` | +| `platform-web` | The browser implementation (Java over TeaVM JSO, plus TypeScript): file system and storage worker, WebRTC, Web Workers | `platform-api` | +| `net` | WebSocket transport under the game's Netty pipeline; Eagler's handshake, messages, skins and relays; Wisp; Microsoft sign-in over its own TLS (Bouncy Castle) | `platform-api` | +| `via` | ViaVersion and ViaBackwards as a pipeline stage, to join servers of other versions | nothing | +| `mesher` | Terrain mesher: section snapshot in, vertices out, byte-identical to the game's. Also compiled alone for workers | nothing | +| `client` | The patched game plus the adapter code its patches call. Package map in [`client/README.md`](client/README.md) | `platform-api`, `net`, `via`, `mesher`, `framework`, `online`, `features/*` | +| `framework` | Module framework: `Module`, events, settings, keybinds, HUD elements, profiles, waypoints, the game as modules see it. No game types | nothing | +| `online` | Incari accounts, friends, chat, cosmetics, client side. No game types | `platform-api`, `framework` | +| `features/` | One module each, with its own README | `framework` only | +| `render-webgl2` | WebGL2 backend under the game's renderer | `client` | +| `web-classlib` | JDK classes TeaVM lacks, and LWJGL stand-ins, for the browser build | nothing | +| `app-desktop` | Desktop runtime: installs `platform-desktop`, starts the game | `client`, `platform-desktop` | +| `app-web` | Browser build: entry point, mesher worker, loader page | `client`, `platform-web`, `web-classlib`, `render-webgl2` | +| `tools/*` | Build CLI, TeaVM compile, shader and sprite translation, dev servers ([`tools/README.md`](tools/README.md)) | see `module-boundaries.txt` | +| `rust/` | Not a Gradle module: Incari on Horizon, the experimental Rust build: the client (`incari_core`, its look, screens and framework) and its feature mods ([`rust/README.md`](rust/README.md), ADR 0068, 0069) | Horizon's hook points only | + +**Why `client` is one compilation:** patches call Incari code that uses game types, so the two can't +be compiled separately. The vendor half is compiled without lint, and `strictCompile` rechecks +Incari's half with the same gates as every other module. Put logic in the strict modules and keep +`client`'s own code a thin adapter. + +## The vendor tree + +The repo never contains Mojang code ([ADR 0001](docs/adr/0001-patch-only-repo.md)). `./incari setup` +downloads the pinned jar, decompiles it with Vineflower, and builds `work/client`: a git repo of the +vendor commit, then `patches/classes.txt`, then one commit per patch. + +- **Decompile fixes** (`patches/decompile/`) make the tree compile and change no behaviour (ADR 0004). +- **Incari patches** are one- or two-line hooks, wrapped in `// Incari start: ` and `// Incari end`. +- **Whole-class replacements** go in `patches/classes.txt`, so no Mojang file is republished in a diff. + +## Platform layer + +`platform-api` describes what the game needs in Incari's own terms, with no game or library types. +The game reaches it through replacement classes (Mojang's window, event pump and audio, rewritten) +and small hooks (ADR 0005). + +Graphics plugs in lower: Mojang's renderer already has a backend API (`GpuDevice` in +`com.mojang.renderpearl`). The desktop keeps Mojang's OpenGL backend; the browser uses +`render-webgl2`, with shaders translated at build time (ADR 0007, 0012). + +## Browser constraints that shape the code + +- **Threads are cooperative.** Java threads take turns on one core (JSPI fibers in the Fast build, + coroutines in Compatible). Anything that blocks has to become async or move to a worker. The background + pool runs in the time a frame leaves over ([`docs/threading.md`](docs/threading.md), ADR 0015). +- **Workers share no objects.** Each worker is its own WebAssembly instance. Work crosses as flat + data in a `SharedArrayBuffer` or a transferred `ArrayBuffer` (ADR 0023). +- **Off-heap memory is linear memory.** The game's native buffers live in the module's linear + memory, with real addresses and no copy on upload (ADR 0008). +- **Closed world.** TeaVM sees the whole program at compile time, so reflection has to be declared or removed. +- **Files are in memory.** The game's file calls are synchronous and browser storage isn't, so files + live in memory and a storage worker writes changes behind (ADR 0011). +- **Memory is budgeted.** A 4 GB Chromebook kills the tab when it runs out of memory. The benchmark holds + heap, linear memory and GC pauses to budgets (ADR 0025). +- **Start-up only pays for the title screen.** Models load after it shows, and sprites are decoded at + build time (ADR 0026). + +## Where to start + +| To | Read | +| --- | --- | +| Set up and edit game code | [`CONTRIBUTING.md`](CONTRIBUTING.md), [`tools/build/README.md`](tools/build/README.md) | +| See why things are built as they are | [`docs/adr/README.md`](docs/adr/README.md) | +| Measure performance | [`docs/benchmark.md`](docs/benchmark.md) | +| Work as an agent | [`AGENTS.md`](AGENTS.md) and the module's own `AGENTS.md` | +| Change a module boundary | `gradle/module-boundaries.txt`, then an ADR | diff --git a/incari-client/files/CLAUDE.md b/incari-client/files/CLAUDE.md new file mode 100644 index 0000000..740edf5 --- /dev/null +++ b/incari-client/files/CLAUDE.md @@ -0,0 +1,3 @@ +# Incari Client + +@AGENTS.md diff --git a/incari-client/files/CODE_OF_CONDUCT.md b/incari-client/files/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..fa43761 --- /dev/null +++ b/incari-client/files/CODE_OF_CONDUCT.md @@ -0,0 +1,17 @@ +# Code of conduct + +Incari is made by volunteers. In the project's issues, +discussions, pull requests and other spaces, we ask everyone to: + +- be respectful and patient, even when you disagree; +- assume good intent, and criticize work, not people; +- never harass, threaten, demean or dox anyone, or share their private information; +- never post or link builds of the game, cheats, or other people's paid content. + +Maintainers may edit or remove anything that breaks these rules, and may warn or ban the person +who posted it, depending on how serious it was. + +To report a problem, use GitHub's "Report content" on the post, or contact a maintainer (listed in +[`.github/CODEOWNERS`](.github/CODEOWNERS)) privately. Reports are kept confidential. + +This code of conduct is loosely based on the [Contributor Covenant](https://www.contributor-covenant.org/). diff --git a/incari-client/files/CONTRIBUTING.md b/incari-client/files/CONTRIBUTING.md new file mode 100644 index 0000000..4373d7d --- /dev/null +++ b/incari-client/files/CONTRIBUTING.md @@ -0,0 +1,81 @@ +# Contributing to Incari + +This repo holds only Incari's code and small patch files. The build tool downloads Mojang's game +and decompiles it on your machine, so the game itself never goes into git. + +## Rules + +These keep the project safe from takedowns. CI enforces what it can. + +- **No Mojang content:** jars, decompiled source, textures, sounds, models, language files, shaders + (translated copies too), data dumps. +- **No builds:** no `.wasm`/`.js` builds, offline HTML, releases, Pages or CI artifacts, and no + links to hosted builds. +- **No copied game code** in Incari modules. Write it yourself. +- **No secrets.** Read them from environment variables. + +## Setup + +Needs JDK 25+, git and Node 24+. + +```sh +./incari setup # download 26.3, decompile, patch into work/client; installs the pre-commit hook +npm ci # TypeScript tooling +``` + +Every `./incari` command: [`tools/build/README.md`](tools/build/README.md). Where things are: +[`ARCHITECTURE.md`](ARCHITECTURE.md). Why things are as they are: [`docs/adr/`](docs/adr/README.md). +For larger changes, open a discussion or write an ADR first. + +## Changing game code + +```sh +cd work/client +# edit, then commit one change per commit; the subject prefix becomes the folder under patches/ +git commit -am "render: Route section compile to the mesher" +cd ../.. +./incari rebuild # writes patches/render/NNNN-route-section-compile-to-the-mesher.patch +``` + +Then commit the changed `patches/` files in this repo. Never edit patch files by hand. + +- **Keep patches thin.** A patch should be a one- or two-line hook into an Incari module, marked + `// Incari start: ` … `// Incari end`. Put the logic in the module. +- **Never reformat vendor code.** Every changed line makes the next Minecraft update harder to rebase. +- **Deleting or replacing a whole class** goes in `patches/classes.txt`, not in a patch. +- **Decompile fixes** (`patches/decompile/`) only make the tree compile, so they need no markers (ADR 0004). +- **Patch budget:** `tools/ci/check-patch-budget.sh` checks total patch size against + `patches/budget.properties`. If you have to raise it, do it in your PR and explain why. + +## Before you open a pull request + +```sh +./gradlew check # format, Error Prone, NullAway, boundaries, tests, client build +npm run check # TypeScript: types, lint, format, tests +./incari rebuild --check # patches/ matches your work/client commits +./incari copycheck # nothing copied from the game +``` + +`./gradlew spotlessApply` and `npm run format` fix formatting. A maintainer must review changes to +the renderer, networking, patches and licensing (`.github/CODEOWNERS`). + +## Sign off your commits (DCO) + +```sh +git commit -s -m "tools: Add the survey command" +``` + +Signing off says you agree to the [Developer Certificate of Origin](DCO.txt) and that your change is licensed +under GPL-3.0-or-later with the Minecraft exception ([`LICENSE-EXCEPTION.txt`](LICENSE-EXCEPTION.txt)). +CI rejects commits without a sign-off. + +## Optional environment variables + +| Variable | For | +| --- | --- | +| `INCARI_CHROME` | Which Chromium the browser checks and benchmark run | +| `INCARI_BROTLI` | The `brotli` command for `:app-web:checkDownloadSize` | +| `INCARI_RCON_PASSWORD` | Smoke tests that drive a local server over RCON | +| `INCARI_ONLINE_URL` | Which service `tools/onlinedev/peer.mjs` talks to | +| `INCARI_BENCH`, `INCARI_BENCH_OFF` | Turn on `TerrainStepBench` and pick what it compares | +| `INCARI_BUILD_OPTS`, `INCARI_SURVEY_OPTS`, `INCARI_COPYCHECK_OPTS` | JVM options for the `./incari` tools | diff --git a/incari-client/files/DCO.txt b/incari-client/files/DCO.txt new file mode 100644 index 0000000..49b8cb0 --- /dev/null +++ b/incari-client/files/DCO.txt @@ -0,0 +1,34 @@ +Developer Certificate of Origin +Version 1.1 + +Copyright (C) 2004, 2006 The Linux Foundation and its contributors. + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + + +Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +(a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +(b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +(c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +(d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. diff --git a/incari-client/files/LICENSE b/incari-client/files/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/incari-client/files/LICENSE @@ -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/incari-client/files/LICENSE-EXCEPTION.txt b/incari-client/files/LICENSE-EXCEPTION.txt new file mode 100644 index 0000000..60f3a7c --- /dev/null +++ b/incari-client/files/LICENSE-EXCEPTION.txt @@ -0,0 +1,28 @@ +Incari Client +Copyright (C) 2026 The Incari Client contributors + +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, with the +additional permission below. The full license text is in LICENSE. + +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. + + +Additional permission under GNU GPL version 3 section 7 + +If you modify this Program, or any covered work, by linking or combining it with +Minecraft: Java Edition (or a modified version of it, including one produced by +decompiling it and applying this Program's patches), containing parts covered by the +terms of the Minecraft End User License Agreement or other Mojang Studios or +Microsoft terms, the licensors of this Program grant you additional permission to +convey the resulting work. Corresponding Source for a non-source form of such a +combination shall include the source code for the parts of this Program used, but need +not include the source code for the parts of Minecraft: Java Edition used. + +This permission covers only the Minecraft: Java Edition parts of such a combination. +It gives no rights in Minecraft itself, which you must obtain from Mojang Studios +under their own terms, and it does not change the license of any other component, +including third-party libraries under their own licenses. diff --git a/incari-client/files/NOTICE.md b/incari-client/files/NOTICE.md new file mode 100644 index 0000000..b9c6eb2 --- /dev/null +++ b/incari-client/files/NOTICE.md @@ -0,0 +1,46 @@ +# Third-party notices + +Incari Client's own code is licensed under the GNU GPL version 3 or later, with the additional +permission in [`LICENSE-EXCEPTION.txt`](LICENSE-EXCEPTION.txt). That permission covers only +Incari's code. Everything below keeps its own licence. + +Minecraft is a trademark of Mojang Studios. Incari is not affiliated with or endorsed by Mojang or +Microsoft. This repository contains no Minecraft code or assets: the build tool downloads the game +from Mojang on your machine. + +## In this repository + +| What | Where | Licence | +| --- | --- | --- | +| [Red Hat Display](https://github.com/RedHatOfficial/RedHatFont), © The Red Hat Project Authors | `client/src/main/resources/incari-pack/assets/incari/font/` | OFL-1.1 (text beside the font) | +| [Michroma](https://github.com/googlefonts/Michroma-font), © The Michroma Project Authors | same | OFL-1.1 | +| [Inter](https://github.com/rsms/inter), © The Inter Project Authors | same, subset | OFL-1.1 | +| [Nunito](https://github.com/googlefonts/nunito), © The Nunito Project Authors | same, subset | OFL-1.1 | +| [Poppins](https://github.com/itfoundry/Poppins), © The Poppins Project Authors | same, subset | OFL-1.1 | +| [JetBrains Mono](https://github.com/JetBrains/JetBrainsMono), © The JetBrains Mono Project Authors | same, subset | OFL-1.1 | +| "Snowy landscape in Eigergletscher, Lauterbrunnen" by Pascale Amez ([Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Snowy_landscape_in_Eigergletscher,_Lauterbrunnen.jpg)), blurred and shrunk | `client/src/main/resources/incari-pack/assets/incari/textures/gui/title_backdrop.png` | CC0-1.0 | +| Fixes to [TeaVM](https://github.com/konsoletyper/teavm) 0.16.0, © Alexey Andreev and contributors: TeaVM's own source files with Incari's changes, original headers kept | `tools/teavm-patches/src/main/java/org/teavm/` | Apache-2.0 | +| The Gradle wrapper | `gradlew`, `gradlew.bat`, `gradle/wrapper/` | Apache-2.0 | + +## In a build + +A build (`./incari build`) also contains, fetched at build time: + +| What | Licence | +| --- | --- | +| [ViaVersion](https://github.com/ViaVersion/ViaVersion) and [ViaBackwards](https://github.com/ViaVersion/ViaBackwards), unmodified | GPL-3.0 | +| [TeaVM](https://github.com/konsoletyper/teavm)'s runtime and class library | Apache-2.0 | +| [ThreeTen Backport](https://github.com/ThreeTen/threetenbp) | BSD-3-Clause | +| [Bouncy Castle](https://www.bouncycastle.org/) (`bcprov`, `bcutil`, `bctls`), unmodified: sign-in's TLS and the browser build's crypto (ADR 0070) | MIT | +| [JZlib](https://github.com/ymnk/jzlib) | BSD-3-Clause | +| Minecraft: Java Edition and the libraries Mojang ships with it, from your own download | Mojang's terms and each library's own | + +ViaVersion and ViaBackwards carry no exception for combining them with Minecraft, so a build that +contains them has an open licensing question ([ADR 0002](docs/adr/0002-license-gpl3-with-minecraft-exception.md)). +That is one reason the project distributes no builds, and why +[`docs/self-hosting.md`](docs/self-hosting.md) asks you never to share one. + +The client lists these under Credits & Attribution (the copyright line on the title screen). + +Development tools (Vineflower, Error Prone, NullAway, ESLint, Prettier, TypeScript and the other +Gradle and npm dependencies) are used to build and check the code and aren't part of a build. diff --git a/incari-client/files/README.md b/incari-client/files/README.md new file mode 100644 index 0000000..d3cc8d9 --- /dev/null +++ b/incari-client/files/README.md @@ -0,0 +1,114 @@ +# Incari Client + +Incari is a browser client for Minecraft: Java Edition. It compiles the latest release of the game to +WebAssembly with TeaVM and runs it on a WebGL2 backend under Mojang's own renderer. On top of that +sits a PvP, QoL and visuals client. + +This repository contains **no Minecraft code or assets**. The build tool downloads the official game +from Mojang, decompiles it on your machine and applies Incari's patches. You need to own Minecraft: +Java Edition to play. + +## What it does + +- **Joins any server from 1.8 up.** Eaglercraft servers (EaglerXServer) work over WebSocket, and + vanilla servers work through a bridge. ViaVersion and ViaBackwards run inside the client to handle + version differences. On 1.8 servers, combat, movement and block shapes behave like 1.8. +- **Eaglercraft features:** skins and capes, password-protected servers, voice chat, and worlds + shared through relays. +- **Singleplayer in the browser.** The game's server runs in a Web Worker, and worlds are saved in + the browser's storage. +- **Fast on weak hardware.** Terrain is meshed in workers and drawn in a few batched calls, memory + use is trimmed, and the Potato preset is the default. There are two builds: Fast (JSPI) and + Compatible. +- **Over 25 QoL and PvP modules.** +- **Optional Incari accounts** for friends, messages and cosmetics, with a badge next to other + Incari players' names. + +## Don't share builds + +This repository publishes no builds, and nobody has permission to distribute one. Every build +contains Minecraft's code and files, so build it yourself and keep it for your own use. + +## Buy Minecraft + +Please buy the game. Running Mojang's game without a licence is piracy, and Incari doesn't change +that. Nothing in this project can check that you own it, but you should. + +## Getting started + +You need JDK 25 or newer, git, Node 24 or newer, and network access to Mojang's download servers and +Maven Central. Compiling the browser build needs about 20 GB of free memory. + +```sh +./incari setup # download 26.3, decompile it, apply the patches into work/client +npm ci # the TypeScript tooling + +./incari assets # once: the game's sounds and languages (~480 MB) +./gradlew :app-desktop:run # play on the desktop runtime, for debugging + +./gradlew :app-web:teavm # compile the browser build (about ten minutes) +./gradlew :app-web:serve # serve it on http://localhost:8080/ + +./incari build # both release builds as one folder for your own web server +``` + +Then read [`ARCHITECTURE.md`](ARCHITECTURE.md) for how the pieces fit, +[`CONTRIBUTING.md`](CONTRIBUTING.md) for the patch workflow and the checks, and +[`tools/build/README.md`](tools/build/README.md) for every `./incari` command. + +## Layout + +| Path | What it is | +| --- | --- | +| `incari`, `incari.cmd`, `incari.properties` | The build CLI's launcher, the pinned Minecraft version, and Incari's version and defaults | +| `patches/` | Incari's changes to the game, as patch files plus a class manifest | +| `client/` | Builds the game from `work/client`, plus the Incari code its patches call | +| `platform-api/`, `platform-desktop/`, `platform-web/` | The platform layer the game runs on: window, input, audio, files, threads, networking | +| `render-webgl2/` | The WebGL2 graphics backend | +| `net/`, `via/` | WebSocket transport and Eagler's protocol; ViaVersion inside the client | +| `mesher/` | The terrain mesher that runs in Web Workers | +| `framework/`, `features/` | The module framework, and one module per feature | +| `online/` | Incari accounts, chat and cosmetics, client side | +| `web-classlib/` | JDK classes TeaVM lacks, for the browser build | +| `app-desktop/`, `app-web/` | The desktop dev runtime and the browser build (loader page, benchmark, browser checks) | +| `tools/` | The build CLI, TeaVM compile and fixes, shader and sprite translation, copy check, dev servers, CI guards | +| `docs/` | Decision records (`docs/adr/`), protocol, benchmark and self-hosting guides | +| `work/` | Generated and git-ignored: downloads, decompiled source, the patched tree | + +Every module has a `README.md` (what it's for, how to test it) and an `AGENTS.md` (its rules). + +## Contributing + +Contributions are welcome. Start with [`CONTRIBUTING.md`](CONTRIBUTING.md). Commits must be signed +off (DCO), and a few rules exist to keep the project legally safe, so CI enforces them. File bugs with +the issue form and put ideas in Discussions. Report security problems privately, as described in +[`SECURITY.md`](SECURITY.md). Everyone follows the [code of conduct](CODE_OF_CONDUCT.md). + +AI coding agents: start with [`AGENTS.md`](AGENTS.md). + +## License + +Incari's own code is licensed under the GNU GPL version 3 or later, with an additional permission +for combining it with Minecraft (see [`LICENSE`](LICENSE) and +[`LICENSE-EXCEPTION.txt`](LICENSE-EXCEPTION.txt)). Third-party fonts, code and libraries keep their +own licences ([`NOTICE.md`](NOTICE.md)). Minecraft is a trademark of Mojang Studios. Incari is not +affiliated with or endorsed by Mojang or Microsoft. + +## Regarding AI usage in this project: + +Considering (as I write this) it's October 2026, it is absolutely ridiculous that I need to go over this. Some of you have a real problem with emerging technologies, +simply because: +1. Certain fear-mongering individuals on social media tell you that AI is bad, it will kill us all in the next 10 years, etc +2. Your dream GPU is too expensive because of the RAMpocolypse +3. AI can do tasks way faster and better than you can + +Given the fact that many of you are yet to emerge from even middle school while having this opinion, you're in a real dangerous spot mentally. This technology +is not going away, nor will it slow down. It will keep speeding up, and will continue to contribute immensely in many fields, including scientific ones as was seen with the recent OpenAI solutions to 300+ of the biggest problems in mathematics. +You seriously need to get with the program, and realize that this technology will change your life, for good or for bad. That choice is entirely in your hands. + +Either you learn how to use AI to be competitive, massively speed up your tasks, and do things you couldn't before, or reject it, fall behind, go to some shitty college, and struggle to get a job because you didn't pick up AI when everyone else was. +Your choice. + +Now that being said, AI was used extensively in the development of this project. + +And it should matter to you, as an end user, because it allowed for incredible performance optimizations and client features that would not have been possible for me to feasibly create on a realistic timescale otherwise. diff --git a/incari-client/files/SECURITY.md b/incari-client/files/SECURITY.md new file mode 100644 index 0000000..eccfc8a --- /dev/null +++ b/incari-client/files/SECURITY.md @@ -0,0 +1,27 @@ +# Security + +## Reporting a vulnerability + +Please report security problems privately, through GitHub's +[private vulnerability reporting](https://github.com/incari-client/incari-client/security/advisories/new), +not in a public issue or discussion. + +Tell us what's affected, how to reproduce it, and what an attacker could do with it. We'll reply +within a week. Please give us reasonable time to fix it before you talk about it publicly. + +## What's in scope + +- The client: anything a server, another player, a resource pack, a shared world or a crafted page + address can do to a player's machine, browser storage or account. +- Incari accounts and the online service's protocol ([`docs/online-protocol.md`](docs/online-protocol.md)): + sign-in, sessions, recovery codes, friends, messages and blocking. The service itself is closed + source; report problems with it the same way. +- The build tool and CI: anything that could put Mojang content, secrets or builds into the + repository, or run a fork's code on a maintainer's machine. + +Out of scope: problems in Minecraft itself, in ViaVersion or TeaVM (report those upstream), and in +builds other people host. The project publishes no builds. + +## Supported versions + +Only the latest commit on `main` gets fixes. diff --git a/incari-client/files/app-desktop/AGENTS.md b/incari-client/files/app-desktop/AGENTS.md new file mode 100644 index 0000000..8c1a224 --- /dev/null +++ b/incari-client/files/app-desktop/AGENTS.md @@ -0,0 +1,6 @@ +# app-desktop + +- Wiring only: install `platform-desktop`, start the game. Logic belongs in a strict module. +- Running the game needs a GPU and a display; without them it builds but can't run. +- After changing the platform layer or its hooks, run `./gradlew :app-desktop:smokeTest` and read + `run/smoke-host/incari-smoke/report.txt` (and look at the screenshots). diff --git a/incari-client/files/app-desktop/README.md b/incari-client/files/app-desktop/README.md new file mode 100644 index 0000000..f7897ec --- /dev/null +++ b/incari-client/files/app-desktop/README.md @@ -0,0 +1,46 @@ +# app-desktop: the desktop dev runtime + +Runs the game on a normal JVM through `platform-desktop`, so game logic can be debugged with a real +debugger and profiler before browser problems get in the way. `DesktopMain` installs the platform +and graphics backends, then starts the game's own `Main`. + +```sh +./incari assets # once (~480 MB) +./gradlew :app-desktop:run # play offline in run/; -Pincari.username= skips Edit Profile +``` + +## Smoke tests + +Unattended sessions with injected input. Each needs a display and GPU, writes a report and +screenshots under `run/smoke-*/incari-smoke/`, and halts the JVM if the game hangs. **A task can end +`BUILD SUCCESSFUL` with failed checks: read `report.txt`.** + +| Task | Checks | +| --- | --- | +| `smokeTest` | A world: movement, blocks, commands, inventory, chat, sound, LAN, a server ping, pause, quit | +| `smokeHost` + `smokeJoin` | A second client joins the first over LAN | +| `smokeServer -Pincari.server=` | Join a server, change dimension, reconnect | +| `smokeLegacy` | 1.8 sneaking, reach, cooldown, ladders and sword blocking on a 1.8 server | +| `smokeAuth` | Password login, then login by cookie, on an Eagler server | +| `smokeSkinA` + `smokeSkinB` | Eagler skins both ways | +| `smokeVoiceA` + `smokeVoiceB` | Voice signalling between two clients | +| `smokeOnlineA` + `smokeOnlineB` | Accounts, presence, friends, messages, blocking against an online service (`-Pincari.online`) | +| `smokeMesher` | Incari's mesher against the game's compiler, section by section | +| `smokeModules`, `smokeFeatures`, `smokeHudModules`, `smokeVisualModules`, `smokeScreenModules`, `smokeWaypoints`, `smokeCosmetics` | Modules turned on in a world, with screenshots | +| `smokeHudEditor` | Drag and resize in the HUD editor | +| `smokeScreens`, `smokeLook`, `smokeFit` | Screen edits and skins; the look in both GUI presets; text fitting at GUI scales 2–4 | +| `smokeLayout` | Every Incari screen at six GUI sizes from 320x240, in both fonts: no widget off the screen or over another, no text past its box. Problems in `layout.txt` | + +`worldgenServer -Pworldgen=on|off` runs the dedicated server for ADR 0041's world generation check. + +## Invariants + +- **Wires one game to one platform.** Smoke code runs only when `incari.smoke` is set. +- **An unattended run never leaves a game behind.** + +## How to test + +```sh +./gradlew :app-desktop:check # the layout rules' unit tests (LayoutRulesTest) +./gradlew :app-desktop:smokeLayout # after changing a screen's layout or Ui's widgets +``` diff --git a/incari-client/files/app-desktop/build.gradle.kts b/incari-client/files/app-desktop/build.gradle.kts new file mode 100644 index 0000000..eeed224 --- /dev/null +++ b/incari-client/files/app-desktop/build.gradle.kts @@ -0,0 +1,384 @@ +import java.time.Duration +import groovy.json.JsonSlurper +import java.util.Properties + +plugins { + application +} + +// The desktop dev runtime: the game on a normal JVM, through platform-desktop. +// `./gradlew :app-desktop:run` starts it offline, with its game directory in run/ (git-ignored). + +dependencies { + implementation(project(":client")) + implementation(project(":platform-desktop")) + + testImplementation(platform(libs.junit.bom)) + testImplementation(libs.junit.jupiter) + testImplementation(libs.assertj) + testRuntimeOnly(libs.junit.launcher) +} + +val repoRoot = rootProject.layout.projectDirectory +val minecraftVersion: String = Properties().run { + repoRoot.file("incari.properties").asFile.reader().use { load(it) } + getProperty("minecraft.version") +} +val versionDir = repoRoot.dir("work/cache/versions/$minecraftVersion") + +/** This machine's LWJGL natives, as `incari fetch` downloaded them. */ +val nativeJars = run { + val root = repoRoot.asFile + providers.fileContents(versionDir.file("natives.txt")).asText.map { text -> + text.lines().filter { it.isNotBlank() }.map { root.resolve(it.trim()) } + }.orElse(emptyList()) +} + +/** The asset index id from the version JSON; `./incari assets` downloads it. */ +val assetIndex = providers.fileContents(versionDir.file("$minecraftVersion.json")).asText.map { text -> + @Suppress("UNCHECKED_CAST") + ((JsonSlurper().parseText(text) as Map)["assetIndex"] as Map)["id"] as String +} + +application { + applicationName = "incari-desktop" + mainClass = "incari.app.desktop.DesktopMain" +} + +/** The launcher's JVM arguments for this version, with this machine's natives. */ +val gameJvmArgs = repoRoot.dir("work/natives").asFile.let { natives -> + listOf( + "-Xms2G", "-Xmx4G", "-XX:+UseCompactObjectHeaders", "-XX:+UseZGC", + "-XX:StackShadowPages=32", + "--enable-native-access=ALL-UNNAMED", + "--add-exports", "java.base/jdk.internal.misc=ALL-UNNAMED", + "-Dorg.lwjgl.system.SharedLibraryExtractPath=${natives.resolve("lwjgl")}", + "-Dio.netty.native.workdir=${natives.resolve("netty")}", + "-Dminecraft.launcher.brand=incari-dev", + ) + if (System.getProperty("os.name").lowercase().startsWith("mac")) { + listOf("-XstartOnFirstThread") + } else emptyList() +} + +/** + * Runs the game offline in `gameDir`, the way the launcher would: this machine's natives, the + * launcher's JVM arguments for this version (the version JSON's "jvm" and "default-user-jvm" + * lists, minus other operating systems'), and the downloaded assets. + */ +fun JavaExec.runsGame(gameDir: File, username: Provider, smoke: String?) { + val assetsDir = repoRoot.dir("work/cache/assets").asFile + val version = minecraftVersion + val index = assetIndex + classpath = sourceSets.main.get().runtimeClasspath + files(nativeJars) + mainClass = "incari.app.desktop.DesktopMain" + workingDir = gameDir + javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) } + jvmArgs(gameJvmArgs) + // `-Pincari.browserStartup`: the browser build's start-up on the desktop, to try it with a + // debugger: the data fixer built only when needed, and models loaded after the title. + if (providers.gradleProperty("incari.browserStartup").isPresent) { + systemProperty("incari.browserStartup", "true") + } + if (smoke != null) { + systemProperty("incari.smoke", smoke) + // A backstop behind the smoke test's own watchdog. + timeout = Duration.ofMinutes(15) + } + argumentProviders.add(CommandLineArgumentProvider { + listOf( + "--version", version, + "--versionType", "incari-dev", + "--gameDir", gameDir.path, + "--assetsDir", assetsDir.path, + "--assetIndex", index.get(), + "--accessToken", "0", + "--username", username.get(), + ) + }) + doFirst { + gameDir.mkdirs() + if (!assetsDir.resolve("indexes/${index.get()}.json").isFile) { + throw GradleException("The game's assets aren't downloaded yet. Run: ./incari assets") + } + } +} + +tasks.named("run") { + description = "Runs the game on the desktop platform, offline, in run/." + runsGame(repoRoot.dir("run").asFile, providers.gradleProperty("incari.username").orElse("Dev"), null) + // A name given here stands; without one, Edit Profile opens first and its saved name is used. + if (providers.gradleProperty("incari.username").isPresent) { + systemProperty("incari.fixedName", "true") + } + // `-Pincari.online=ws://127.0.0.1:8090/v1/ws`: Incari accounts against another service (ADR 0058, + // tools/onlinedev), as the page's ?online= does, without rebuilding the client for a new URL. + providers.gradleProperty("incari.online").orNull?.let { systemProperty("incari.online.url", it) } + // `-Pincari.updates=on`: the title screen's update notice, which only release builds show + // (with tools/onlinedev's `--release `). + providers.gradleProperty("incari.updates").orNull?.let { systemProperty("incari.updates", it) } + // `-Pincari.sceneAgent=`: remote control over a loopback port (SceneAgent), for scripted looks. + providers.gradleProperty("incari.sceneAgent").orNull?.let { systemProperty("incari.sceneAgent", it) } +} + +// The smoke test (incari.app.desktop.smoke.SmokeTest): a scripted session, results and +// screenshots in run/smoke-*/incari-smoke/. smokeTest plays alone; smokeHost waits for +// smokeJoin, run at the same time from another terminal, to join its LAN world. +tasks.register("smokeTest") { + group = "verification" + description = "Plays a scripted session on the desktop runtime and reports what worked." + runsGame(repoRoot.dir("run/smoke-host").asFile, providers.provider { "IncariHost" }, "host") +} + +tasks.register("smokeHost") { + group = "verification" + description = "Like smokeTest, then waits up to three minutes for smokeJoin to join over LAN." + runsGame(repoRoot.dir("run/smoke-host").asFile, providers.provider { "IncariHost" }, "host:180") +} + +// Joins a dedicated server, over a WebSocket for a ws:// address (for a vanilla server, +// through tools/wsbridge), changes dimension there and back, disconnects and reconnects. The +// player, IncariSmoke, must be an operator on that server. +tasks.register("smokeServer") { + group = "verification" + description = "Joins -Pincari.server=
(ws://... for WebSocket), changes dimension, reconnects." + val server = providers.gradleProperty("incari.server").orElse("ws://127.0.0.1:8816") + runsGame(repoRoot.dir("run/smoke-server").asFile, providers.provider { "IncariSmoke" }, null) + systemProperty("incari.smoke", "server:" + server.get()) + // `-Pincari.wisp=ws://127.0.0.1:6001/`: joins a host:port server through that Wisp proxy (Wispcraft). + providers.gradleProperty("incari.wisp").orNull?.let { systemProperty("incari.smoke.wisp", it) } + timeout = Duration.ofMinutes(15) +} + +// Skins both ways on an Eagler server. smokeSkinA and smokeSkinB, run at the same time, each +// set a generated skin (A: slim, with a cape; B: wide), join -Pincari.server=, and check +// the other's arrives from the server and draws as the texture it sent. +listOf("A" to "B", "B" to "A").forEach { (me, peer) -> + tasks.register("smokeSkin$me") { + group = "verification" + description = "Joins an Eagler server as IncariSkin$me and checks IncariSkin$peer's skin (run with smokeSkin$peer)." + val server = providers.gradleProperty("incari.server").orElse("ws://127.0.0.1:25577") + runsGame(repoRoot.dir("run/smoke-skin-$me").asFile, providers.provider { "IncariSkin$me" }, null) + systemProperty("incari.smoke", "skins:IncariSkin$peer:" + server.get()) + timeout = Duration.ofMinutes(15) + } +} + +// Incari accounts and chat (ADR 0058, ADR 0059) against a real online service: smokeOnlineA and +// smokeOnlineB, run at the same time, each make an account on -Pincari.online (default a local +// online service, ws://127.0.0.1:8080/v1/ws), join -Pincari.server (default the local 26.3 server, +// 127.0.0.1:25582), see each other as Incari players, become friends, message, block, and delete +// their accounts. +listOf("A" to "B", "B" to "A").forEach { (me, peer) -> + tasks.register("smokeOnline$me") { + group = "verification" + description = "Accounts and chat as IncariOnline$me with IncariOnline$peer (run with smokeOnline$peer)." + val server = providers.gradleProperty("incari.server").orElse("127.0.0.1:25582") + val online = providers.gradleProperty("incari.online").orElse("ws://127.0.0.1:8080/v1/ws") + runsGame(repoRoot.dir("run/smoke-online-$me").asFile, providers.provider { "IncariOnline$me" }, null) + systemProperty("incari.smoke", "online:IncariOnline$peer:" + server.get()) + systemProperty("incari.online.url", online.get()) + timeout = Duration.ofMinutes(15) + } +} + +// A password login and a cookie on an Eagler server whose auth plugin asks this player +// (AuthEIncari: the EAGLER_SHA256 method) for the password "incari" and then sets a cookie. +tasks.register("smokeAuth") { + group = "verification" + description = "Logs in to -Pincari.server= with a password, then again by the server's cookie." + val server = providers.gradleProperty("incari.server").orElse("ws://127.0.0.1:25577") + val name = providers.gradleProperty("incari.username").orElse("AuthEIncari") + runsGame(repoRoot.dir("run/smoke-auth").asFile, name, null) + systemProperty("incari.smoke", "auth:" + server.get()) + timeout = Duration.ofMinutes(15) +} + +// The legacy behaviour layer (ADR 0020) on a 1.8 server (-Pincari.server, default the 1.8.9 server's +// development bridge), checked where the server can tell; -Pincari.rcon is that server's console. +tasks.register("smokeLegacy") { + group = "verification" + description = "Checks 1.8's sneaking, pick margin, cooldown, ladders and sword blocking on a 1.8 server." + val server = providers.gradleProperty("incari.server").orElse("ws://127.0.0.1:8801") + val rcon = providers.gradleProperty("incari.rcon").orElse("127.0.0.1:25611") + runsGame(repoRoot.dir("run/smoke-legacy").asFile, providers.provider { "IncariLegacy" }, null) + systemProperty("incari.smoke", "legacy:" + server.get()) + systemProperty("incari.rcon", rcon.get()) + timeout = Duration.ofMinutes(15) +} + +// Voice chat's signalling on an Eagler server with voice on, with WebRTC scripted on the +// desktop (which has none): smokeVoiceA and smokeVoiceB, run together, turn global voice on and +// check the server pairs them. +listOf("A" to "B", "B" to "A").forEach { (me, peer) -> + tasks.register("smokeVoice$me") { + group = "verification" + description = "Joins an Eagler server as IncariVoice$me and checks voice pairs it with IncariVoice$peer." + val server = providers.gradleProperty("incari.server").orElse("ws://127.0.0.1:25577") + runsGame(repoRoot.dir("run/smoke-voice-$me").asFile, providers.provider { "IncariVoice$me" }, null) + systemProperty("incari.smoke", "voice:IncariVoice$peer:" + server.get()) + timeout = Duration.ofMinutes(15) + } +} + +// The module menu (ADR 0046), Toggle Sprint in a world, the profile saved. +tasks.register("smokeModules") { + group = "verification" + description = "Opens the module menu, latches sprint with Toggle Sprint, and screenshots the module screens." + runsGame(repoRoot.dir("run/smoke-modules").asFile, providers.provider { "IncariSmoke" }, "modules") +} + +// The client's look (ADR 0048), both GUI presets, on the screens players see most. +tasks.register("smokeLook") { + group = "verification" + description = "Screenshots the title, options, lists, module menu, pause menu and inventory in both GUI presets." + runsGame(repoRoot.dir("run/smoke-look").asFile, providers.provider { "IncariSmoke" }, "look") +} + +// Text that must fit its box, at GUI scale 2, 3 and 4 in a Chromebook-sized window, and the +// narrowest layouts at 3 in smaller windows. +tasks.register("smokeFit") { + group = "verification" + description = "Screenshots screens with long or player-chosen text at GUI scale 2, 3 and 4 in a 1366x768 window, and at 3 in 1280x720 and 1024x768." + runsGame(repoRoot.dir("run/smoke-fit").asFile, providers.provider { "IncariSmoke" }, "fit") + args("--width", "1366", "--height", "768") +} + +// Every screen's layout judged at the GUI sizes players get, from 320x240 up, in both fonts: a +// widget off the screen or over another, or text past its box, fails. Problems in layout.txt. +tasks.register("smokeLayout") { + group = "verification" + description = "Checks every Incari screen's layout at six GUI sizes from 320x240, in both fonts." + runsGame(repoRoot.dir("run/smoke-layout").asFile, providers.provider { "IncariSmoke" }, "layout") +} + +// The HUD editor (ADR 0049) from the module menu, dragged and resized in both GUI presets. +tasks.register("smokeHudEditor") { + group = "verification" + description = "Opens the HUD editor from the module menu, drags and resizes Toggle Sprint's line, checks Potato's backdrop rate." + runsGame(repoRoot.dir("run/smoke-hudeditor").asFile, providers.provider { "IncariSmoke" }, "hudeditor") +} + +// ADR 0050: the first modules in a world: armor and effects, a moved sidebar, chat, fire. +tasks.register("smokeFeatures") { + group = "verification" + description = "Turns on Armor & Potion View, Custom Scoreboard, Clear Chat, Low Fire and No Hurt Cam in a world and screenshots them." + runsGame(repoRoot.dir("run/smoke-features").asFile, providers.provider { "IncariSmoke" }, "features") +} + +// ADR 0051: the minimap and waypoints in a world, their screens, a death's waypoint. +tasks.register("smokeWaypoints") { + group = "verification" + description = "Turns on Minimap and Waypoints in a world with waypoints round the player and screenshots them and their screens." + runsGame(repoRoot.dir("run/smoke-waypoints").asFile, providers.provider { "IncariSmoke" }, "waypoints") +} + +// ADR 0052: the HUD modules (Keystrokes, CPS, FPS, Reach, Coordinates, Shield & Totem) in a world. +tasks.register("smokeHudModules") { + group = "verification" + description = "Turns on the HUD modules of ADR 0052 in a world, clicks a mob and holds keys, and screenshots them." + runsGame(repoRoot.dir("run/smoke-hudmodules").asFile, providers.provider { "IncariSmoke" }, "hudmodules") +} + +// ADR 0053: the visual modules (Crosshair, Cooldown, Weather, Freelook, Low Shield, 1.7 Animations), Hitboxes and Schematics. +tasks.register("smokeVisualModules") { + group = "verification" + description = "Runs the visual and combat modules of ADR 0053, Hitboxes and Schematics in a world and screenshots them." + runsGame(repoRoot.dir("run/smoke-visualmodules").asFile, providers.provider { "IncariSmoke" }, "visualmodules") +} + +// ADR 0054: Shulker Tooltips, Screenshot Manager and Theme Editor. +tasks.register("smokeScreenModules") { + group = "verification" + description = "Runs Shulker Tooltips, Screenshot Manager and Theme Editor and screenshots them." + runsGame(repoRoot.dir("run/smoke-screenmodules").asFile, providers.provider { "IncariSmoke" }, "screenmodules") +} + +// ADR 0061: cosmetics worn, the Wardrobe, emotes and the emote wheel. +tasks.register("smokeCosmetics") { + group = "verification" + description = "Wears cosmetics on the title screen and in a world, plays emotes and screenshots the Wardrobe." + runsGame(repoRoot.dir("run/smoke-cosmetics").asFile, providers.provider { "IncariSmoke" }, "cosmetics") +} + +tasks.register("smokeScreens") { + group = "verification" + description = "Screenshots the screens M2 adds (the edit-server screen's Version button, Edit Profile), edits, replaces and skins game screens (ADR 0047)." + runsGame(repoRoot.dir("run/smoke-screens").asFile, providers.provider { "IncariSmoke" }, "screens") +} + +// ADR 0023: every section meshed by the game's compiler and by Incari's mesher, compared, over +// terrain of every kind, every dimension and the debug world's every block state. +tasks.register("smokeMesher") { + group = "verification" + description = "Meshes varied worlds with both the game's compiler and Incari's mesher and compares them." + runsGame(repoRoot.dir("run/smoke-mesher").asFile, providers.provider { "IncariMesher" }, "mesher") + systemProperty("incari.mesher", "verify") + timeout = Duration.ofMinutes(45) +} + +tasks.register("smokeJoin") { + group = "verification" + description = "Joins smokeHost's LAN world through the platform transport." + runsGame(repoRoot.dir("run/smoke-join").asFile, providers.provider { "IncariGuest" }, "join:127.0.0.1:25577") +} + +// How the screenshot-diff harness (tools/webbuild's ScreenshotDiff, `:app-web:screenshotDiff`) +// starts this game to render its reference images with Mojang's OpenGL backend. One line per +// token: `java `, `jvm `, `classpath `, `main `, `arg `; +// the harness adds the game directory, the player, the server and its remote-control port. +tasks.register("sceneLaunch") { + group = "verification" + description = "Writes build/scene-launch.txt: how the screenshot-diff harness starts the desktop game." + val classpath = sourceSets.main.get().runtimeClasspath + files(nativeJars) + val launcher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) } + val output = layout.buildDirectory.file("scene-launch.txt") + val jvm = gameJvmArgs + val version = minecraftVersion + val index = assetIndex + val assetsDir = repoRoot.dir("work/cache/assets").asFile + inputs.files(classpath) + inputs.property("jvm", jvm) + outputs.file(output) + doLast { + val lines = mutableListOf("java " + launcher.get().executablePath.asFile.path) + jvm.forEach { lines.add("jvm $it") } + classpath.files.forEach { lines.add("classpath " + it.path) } + lines.add("main incari.app.desktop.DesktopMain") + listOf("--version", version, "--versionType", "incari-dev", "--assetsDir", assetsDir.path, + "--assetIndex", index.get(), "--accessToken", "0").forEach { lines.add("arg $it") } + output.get().asFile.writeText(lines.joinToString("\n", postfix = "\n")) + } +} + +// ADR 0041: the game's dedicated server with the browser build's world generation changes on or +// off (-Pworldgen=on|off), in run/worldgen-/ from server.properties' seed, typing +// tools/worldgen/script.txt into its console. tools/worldgen/compare.py compares the two worlds. +tasks.register("worldgenServer") { + group = "verification" + description = "Runs the dedicated server with ADR 0041's world generation changes on or off (-Pworldgen=on|off)." + val mode = providers.gradleProperty("worldgen").orElse("off") + val serverDir = mode.map { repoRoot.dir("run/worldgen-$it").asFile } + classpath = sourceSets.main.get().runtimeClasspath + files(nativeJars) + mainClass = "incari.app.desktop.smoke.WorldgenServer" + javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) } + jvmArgs(gameJvmArgs) + systemProperty("incari.worldgen", mode.get()) + systemProperty("incari.worldgen.script", repoRoot.file("tools/worldgen/script.txt").asFile.path) + // One background thread (-Pworldgen.threads=1): chunks generate in one order, so the features + // one chunk places in its neighbours land the same way each run. + providers.gradleProperty("worldgen.threads").orNull?.let { systemProperty("max.bg.threads", it) } + if (providers.gradleProperty("worldgen.verify").isPresent) { + systemProperty("incari.worldgen.verify", "true") + } + val dir = serverDir.get() + val properties = repoRoot.file("tools/worldgen/server.properties").asFile + workingDir = dir + args("--nogui", "--universe", dir.path) + timeout = Duration.ofMinutes(20) + doFirst { + dir.deleteRecursively() + dir.mkdirs() + dir.resolve("eula.txt").writeText("eula=true\n") + properties.copyTo(dir.resolve("server.properties")) + } +} diff --git a/incari-client/files/app-desktop/src/main/java/incari/app/desktop/DesktopMain.java b/incari-client/files/app-desktop/src/main/java/incari/app/desktop/DesktopMain.java new file mode 100644 index 0000000..276969e --- /dev/null +++ b/incari-client/files/app-desktop/src/main/java/incari/app/desktop/DesktopMain.java @@ -0,0 +1,91 @@ +package incari.app.desktop; + +import com.mojang.blaze3d.platform.NativeLibrariesBootstrap; +import com.mojang.renderpearl.api.device.GpuBackend; +import com.mojang.renderpearl.backend.opengl.GlBackend; +import com.mojang.renderpearl.backend.vulkan.VulkanBackend; +import incari.app.desktop.smoke.SceneAgent; +import incari.app.desktop.smoke.SmokeTest; +import incari.client.datafix.DataFixing; +import incari.client.platform.GraphicsBackends; +import incari.client.platform.PlatformLifecycle; +import incari.client.profile.PlayerName; +import incari.client.startup.DeferredModels; +import incari.platform.api.PlatformLog; +import incari.platform.api.Platforms; +import incari.platform.desktop.DesktopPlatform; +import incari.platform.desktop.DesktopStorage; +import java.util.List; +import net.minecraft.client.PreferredGraphicsApi; +import org.jspecify.annotations.Nullable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Starts the game on the desktop platform: installs {@link DesktopPlatform} and the desktop's + * graphics backends, then hands over to the game's own {@code Main} with the same arguments a + * launcher passes. + */ +public final class DesktopMain { + + private DesktopMain() {} + + public static void main(String[] args) { + List arguments = List.of(args); + DesktopStorage storage = new DesktopStorage( + optionValue(arguments, "--gameDir", "."), + optionValue(arguments, "--assetsDir", "assets"), + nullableOptionValue(arguments, "--assetIndex")); + Logger logger = LoggerFactory.getLogger("Platform"); + DesktopPlatform platform = new DesktopPlatform(storage, slf4j(logger), logger.isDebugEnabled()); + SmokeTest.configurePlatform(platform); + Platforms.install(platform); + GraphicsBackends.install(DesktopMain::desktopBackends); + GraphicsBackends.installVulkanCheck(VulkanBackend::checkBackendAvailable); + PlatformLifecycle.setNativeLibraryLoader(NativeLibrariesBootstrap::loadLibraries); + if (Boolean.getBoolean("incari.browserStartup")) { + // The browser build's start-up, to try it here: -Pincari.browserStartup. + DataFixing.buildLazily(); + DeferredModels.enable(); + } + if (System.getProperty("incari.smoke") != null + || System.getProperty("incari.sceneAgent") != null + || Boolean.getBoolean("incari.fixedName")) { + // Tests, and -Pincari.username, name the player: no Edit Profile at start-up. + PlayerName.fixAtLaunch(); + } + SmokeTest.startIfRequested(storage.gameDirectory()); + SceneAgent.startIfRequested(); + net.minecraft.client.main.Main.main(args); + } + + /** OpenGL first, as vanilla does, unless the player chose Vulkan; the other is the fallback. */ + private static GpuBackend[] desktopBackends(PreferredGraphicsApi preference) { + GpuBackend opengl = new GlBackend(); + GpuBackend vulkan = new VulkanBackend(); + return preference == PreferredGraphicsApi.VULKAN + ? new GpuBackend[] {vulkan, opengl} + : new GpuBackend[] {opengl, vulkan}; + } + + private static PlatformLog slf4j(Logger logger) { + return (level, message, error) -> { + switch (level) { + case DEBUG -> logger.debug(message, error); + case INFO -> logger.info(message, error); + case WARN -> logger.warn(message, error); + case ERROR -> logger.error(message, error); + } + }; + } + + private static String optionValue(List arguments, String option, String fallback) { + String value = nullableOptionValue(arguments, option); + return value == null ? fallback : value; + } + + private static @Nullable String nullableOptionValue(List arguments, String option) { + int at = arguments.indexOf(option); + return at >= 0 && at + 1 < arguments.size() ? arguments.get(at + 1) : null; + } +} diff --git a/incari-client/files/app-desktop/src/main/java/incari/app/desktop/package-info.java b/incari-client/files/app-desktop/src/main/java/incari/app/desktop/package-info.java new file mode 100644 index 0000000..d0d472c --- /dev/null +++ b/incari-client/files/app-desktop/src/main/java/incari/app/desktop/package-info.java @@ -0,0 +1,5 @@ +/** The desktop dev runtime's entry point. */ +@NullMarked +package incari.app.desktop; + +import org.jspecify.annotations.NullMarked; diff --git a/incari-client/files/app-desktop/src/main/java/incari/app/desktop/smoke/LayoutCheck.java b/incari-client/files/app-desktop/src/main/java/incari/app/desktop/smoke/LayoutCheck.java new file mode 100644 index 0000000..b8cdae3 --- /dev/null +++ b/incari-client/files/app-desktop/src/main/java/incari/app/desktop/smoke/LayoutCheck.java @@ -0,0 +1,210 @@ +package incari.app.desktop.smoke; + +import incari.app.desktop.smoke.LayoutRules.Box; +import incari.client.ui.GuiSkin; +import incari.client.ui.Skins; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphicsExtractor; +import net.minecraft.client.gui.components.AbstractWidget; +import net.minecraft.client.gui.components.events.ContainerEventHandler; +import net.minecraft.client.gui.navigation.ScreenRectangle; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.renderer.state.gui.GuiRenderState; +import net.minecraft.client.renderer.state.gui.GuiTextRenderState; +import net.minecraft.resources.Identifier; +import net.minecraft.util.FormattedCharSequence; +import org.jspecify.annotations.Nullable; + +/** + * A screen's layout as drawn: one frame of it extracted off the window, with the pointer away, + * recording where each widget and each run of text landed, for {@link LayoutRules} to judge. + * Widgets are seen through a {@link GuiSkin} that records and passes everything on to the skin in + * use; text through the frame's text states, measured as layouts measure it. Game thread. + */ +final class LayoutCheck { + + private LayoutCheck() {} + + /** What's wrong with the screen shown now, in words; empty if its layout is fine. */ + static List problems(Minecraft minecraft, Screen screen) { + GuiRenderState state = new GuiRenderState(); + GuiGraphicsExtractor graphics = new GuiGraphicsExtractor(minecraft, state, -1, -1); + Recorder recorder = new Recorder(Skins.current()); + Skins.use(recorder); + try { + screen.extractRenderStateWithTooltipAndSubtitles(graphics, -1, -1, 0); + } finally { + Skins.use(recorder.inner); + } + List texts = new ArrayList<>(); + state.forEachText(text -> { + Box box = laidOut(text); + if (box != null) { + texts.add(box); + } + }); + return LayoutRules.problems( + graphics.guiWidth(), graphics.guiHeight(), scrolls(screen), recorder.widgets, texts); + } + + /** The account screens' panel scrolls when it's taller than the screen ({@code FormScreen}). */ + private static boolean scrolls(Screen screen) { + for (Class type = screen.getClass(); type != null; type = type.getSuperclass()) { + if (type.getName().equals("incari.client.online.FormScreen")) { + return true; + } + } + return false; + } + + private static Box box(String what, ScreenRectangle rectangle) { + return new Box(what, rectangle.left(), rectangle.top(), rectangle.right(), rectangle.bottom()); + } + + private static String describe(AbstractWidget widget) { + Class type = widget.getClass(); + while (type.getSimpleName().isEmpty()) { + type = type.getSuperclass(); + } + return type.getSimpleName() + " \"" + shortened(widget.getMessage().getString()) + "\""; + } + + private static String shortened(String text) { + return text.length() <= 40 ? text : text.substring(0, 37) + "..."; + } + + /** + * Where a run of text was laid out: its font's width by its line height, as the screen measured + * it, cut to its clip; null if the clip hides it. Not the glyphs' own box, which takes in the + * shadow and, in the pixel font, some padding, so it reaches past where any layout put it. + */ + private static @Nullable Box laidOut(GuiTextRenderState state) { + Font font = field(state, "font", Font.class); + FormattedCharSequence text = field(state, "text", FormattedCharSequence.class); + int x = field(state, "x", Integer.class); + int y = field(state, "y", Integer.class); + ScreenRectangle laid = + new ScreenRectangle(x, y, font.width(text), font.lineHeight).transformMaxBounds(state.pose); + ScreenRectangle shown = state.scissor != null ? state.scissor.intersection(laid) : laid; + if (shown == null) { + return null; + } + StringBuilder words = new StringBuilder(); + text.accept((position, style, codepoint) -> { + words.appendCodePoint(codepoint); + return true; + }); + return box("text \"" + shortened(words.toString()) + "\"", shown); + } + + /** A text state keeps what it draws to itself. */ + private static T field(GuiTextRenderState state, String name, Class type) { + try { + Field field = GuiTextRenderState.class.getDeclaredField(name); + field.setAccessible(true); + return type.cast(field.get(state)); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException("GuiTextRenderState has no " + name, e); + } + } + + /** Records each widget drawn, cut to its clip, and hands every call on to {@code inner}. */ + private static final class Recorder implements GuiSkin { + + final @Nullable GuiSkin inner; + final List widgets = new ArrayList<>(); + + Recorder(@Nullable GuiSkin inner) { + this.inner = inner; + } + + @Override + public boolean widget(GuiGraphicsExtractor graphics, AbstractWidget widget, int mouseX, int mouseY, float a) { + // A list or a panel is judged by what's in it, not as one widget over its rows. + if (!(widget instanceof ContainerEventHandler)) { + ScreenRectangle drawn = widget.getRectangle(); + ScreenRectangle clip = graphics.incariScissor(); + ScreenRectangle shown = clip != null ? clip.intersection(drawn) : drawn; + if (shown != null) { + widgets.add(box(describe(widget), shown)); + } + } + return inner != null && inner.widget(graphics, widget, mouseX, mouseY, a); + } + + @Override + public boolean sprite( + GuiGraphicsExtractor graphics, Identifier sprite, int x, int y, int width, int height, int color) { + return inner != null && inner.sprite(graphics, sprite, x, y, width, height, color); + } + + @Override + public boolean spritePart( + GuiGraphicsExtractor graphics, + Identifier sprite, + int spriteWidth, + int spriteHeight, + int textureX, + int textureY, + int x, + int y, + int width, + int height, + int color) { + return inner != null + && inner.spritePart( + graphics, + sprite, + spriteWidth, + spriteHeight, + textureX, + textureY, + x, + y, + width, + height, + color); + } + + @Override + public boolean texture( + GuiGraphicsExtractor graphics, + Identifier texture, + int x, + int y, + int width, + int height, + float u, + float v, + int srcWidth, + int srcHeight, + int textureWidth, + int textureHeight, + int color) { + return inner != null + && inner.texture( + graphics, + texture, + x, + y, + width, + height, + u, + v, + srcWidth, + srcHeight, + textureWidth, + textureHeight, + color); + } + + @Override + public boolean background(GuiGraphicsExtractor graphics, Screen screen, float a) { + return inner != null && inner.background(graphics, screen, a); + } + } +} diff --git a/incari-client/files/app-desktop/src/main/java/incari/app/desktop/smoke/LayoutRules.java b/incari-client/files/app-desktop/src/main/java/incari/app/desktop/smoke/LayoutRules.java new file mode 100644 index 0000000..9b125cb --- /dev/null +++ b/incari-client/files/app-desktop/src/main/java/incari/app/desktop/smoke/LayoutRules.java @@ -0,0 +1,113 @@ +package incari.app.desktop.smoke; + +import java.util.ArrayList; +import java.util.List; +import org.jspecify.annotations.Nullable; + +/** + * What a screen drawn at one size must not do, from where its widgets and text landed (GUI + * units, already cut to any clip they were drawn in): a widget off the screen or over another, text + * past the widget it's in, over a widget it isn't in, over other text, or off the screen. The + * geometry only; {@link LayoutCheck} gathers the boxes from a frame. + */ +final class LayoutRules { + + /** + * Text's measured box takes in its shadow and anti-aliased edge, which may reach this far + * past where a layout put it without anyone seeing a problem. + */ + static final int SLACK = 1; + + private LayoutRules() {} + + /** A widget or a run of text, as drawn: {@code x1} and {@code y1} are exclusive. */ + record Box(String what, int x0, int y0, int x1, int y1) { + + boolean isEmpty() { + return x1 <= x0 || y1 <= y0; + } + + /** Whether {@code other} is inside this, give or take {@code slack}. */ + boolean holds(Box other, int slack) { + return other.x0 >= x0 - slack && other.y0 >= y0 - slack && other.x1 <= x1 + slack && other.y1 <= y1 + slack; + } + + /** Whether this and {@code other} share more than {@code slack} each way. */ + boolean overlaps(Box other, int slack) { + return Math.min(x1, other.x1) - Math.max(x0, other.x0) > slack + && Math.min(y1, other.y1) - Math.max(y0, other.y0) > slack; + } + + boolean containsPoint(int x, int y) { + return x >= x0 && x < x1 && y >= y0 && y < y1; + } + + @Override + public String toString() { + return what + " at " + x0 + "," + y0 + " " + (x1 - x0) + "x" + (y1 - y0); + } + } + + /** Everything wrong with one screen at {@code width} by {@code height}, in words; empty if fine. */ + static List problems(int width, int height, List widgets, List texts) { + return problems(width, height, false, widgets, texts); + } + + /** + * {@link #problems(int, int, List, List)} for a screen that may scroll its contents up + * ({@code scrolls}): what's below its bottom edge is reached by scrolling, not cut off. + */ + static List problems(int width, int height, boolean scrolls, List widgets, List texts) { + Box screen = new Box("the screen", 0, 0, width, scrolls ? Integer.MAX_VALUE / 2 : height); + List found = new ArrayList<>(); + List shown = widgets.stream().filter(box -> !box.isEmpty()).toList(); + List words = texts.stream().filter(box -> !box.isEmpty()).toList(); + for (int i = 0; i < shown.size(); i++) { + Box widget = shown.get(i); + if (!screen.holds(widget, 0)) { + found.add(widget + " runs off the screen"); + } + for (int j = i + 1; j < shown.size(); j++) { + if (widget.overlaps(shown.get(j), 0)) { + found.add(widget + " overlaps " + shown.get(j)); + } + } + } + for (int i = 0; i < words.size(); i++) { + Box text = words.get(i); + if (!screen.holds(text, SLACK)) { + found.add(text + " runs off the screen"); + } + Box owner = owner(text, shown); + if (owner != null) { + if (!owner.holds(text, SLACK)) { + found.add(text + " runs past " + owner); + } + } else { + for (Box widget : shown) { + if (text.overlaps(widget, SLACK)) { + found.add(text + " runs into " + widget); + } + } + } + for (int j = i + 1; j < words.size(); j++) { + if (text.overlaps(words.get(j), SLACK)) { + found.add(text + " overlaps " + words.get(j)); + } + } + } + return found; + } + + /** The widget text starts in: where its first letter's middle is. */ + private static @Nullable Box owner(Box text, List widgets) { + int x = text.x0 + SLACK; + int y = (text.y0 + text.y1) / 2; + for (Box widget : widgets) { + if (widget.containsPoint(x, y)) { + return widget; + } + } + return null; + } +} diff --git a/incari-client/files/app-desktop/src/main/java/incari/app/desktop/smoke/Rcon.java b/incari-client/files/app-desktop/src/main/java/incari/app/desktop/smoke/Rcon.java new file mode 100644 index 0000000..a15e5d9 --- /dev/null +++ b/incari-client/files/app-desktop/src/main/java/incari/app/desktop/smoke/Rcon.java @@ -0,0 +1,69 @@ +package incari.app.desktop.smoke; + +import java.io.DataInputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.net.Socket; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; + +/** + * A game server's remote console, for smoke scenarios that set up the world: one command per + * connection, which is plenty for a test. The protocol: little-endian length, id and type, the + * body, two zero bytes; type 3 logs in, type 2 runs a command. + */ +final class Rcon { + + private final String host; + private final int port; + private final String password; + + Rcon(String address, String password) { + int colon = address.lastIndexOf(':'); + this.host = address.substring(0, colon); + this.port = Integer.parseInt(address.substring(colon + 1)); + this.password = password; + } + + /** Runs {@code command} and returns the server's reply. */ + String run(String command) throws IOException { + try (Socket socket = new Socket(host, port)) { + socket.setSoTimeout(5000); + OutputStream out = socket.getOutputStream(); + DataInputStream in = new DataInputStream(socket.getInputStream()); + out.write(packet(1, 3, password)); + if (read(in).id == -1) { + throw new IOException("RCON refused the password"); + } + out.write(packet(2, 2, command)); + return read(in).body; + } + } + + private record Reply(int id, String body) {} + + private static byte[] packet(int id, int type, String body) { + byte[] text = body.getBytes(StandardCharsets.UTF_8); + ByteBuffer buffer = ByteBuffer.allocate(14 + text.length).order(ByteOrder.LITTLE_ENDIAN); + buffer.putInt(10 + text.length) + .putInt(id) + .putInt(type) + .put(text) + .put((byte) 0) + .put((byte) 0); + return buffer.array(); + } + + private static Reply read(DataInputStream in) throws IOException { + byte[] head = new byte[12]; + in.readFully(head); + ByteBuffer buffer = ByteBuffer.wrap(head).order(ByteOrder.LITTLE_ENDIAN); + int length = buffer.getInt(); + int id = buffer.getInt(); + buffer.getInt(); + byte[] body = new byte[length - 8]; + in.readFully(body); + return new Reply(id, new String(body, 0, Math.max(0, body.length - 2), StandardCharsets.UTF_8)); + } +} diff --git a/incari-client/files/app-desktop/src/main/java/incari/app/desktop/smoke/SceneAgent.java b/incari-client/files/app-desktop/src/main/java/incari/app/desktop/smoke/SceneAgent.java new file mode 100644 index 0000000..f65f44a --- /dev/null +++ b/incari-client/files/app-desktop/src/main/java/incari/app/desktop/smoke/SceneAgent.java @@ -0,0 +1,179 @@ +package incari.app.desktop.smoke; + +import com.mojang.blaze3d.platform.NativeImage; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import net.minecraft.client.Minecraft; +import net.minecraft.client.Screenshot; +import org.jspecify.annotations.Nullable; +import org.lwjgl.sdl.SDLVideo; + +/** + * Remote control for the screenshot-diff harness ({@code tools/webbuild}'s + * {@code ScreenshotDiff}): the harness renders the same scenes here, with Mojang's OpenGL backend, + * and in the browser, and compares the two. It drives this game over a line protocol on a loopback + * port, the way it drives the browser over the DevTools protocol: + * + *
    + *
  • {@code state}: {@code world} when a world is shown with no screen open, {@code screen} with + * a screen over it, {@code menu} otherwise + *
  • {@code key }: a key, as SDL reports it + *
  • {@code move } and {@code click }: the pointer, in fractions of the window + *
  • {@code type }: text typed into whatever has the focus, as SDL's text input reports it + *
  • {@code shot }: the main render target, as a PNG (what the window shows, before + * scaling); answers {@code ok } + *
+ * + * Every answer is one line, {@code ok ...} or {@code error }. Off unless + * {@code -Dincari.sceneAgent=}; development tooling, never in a build players get. + */ +public final class SceneAgent { + + private final Minecraft minecraft; + private @Nullable SdlInjector input; + + private SceneAgent(Minecraft minecraft) { + this.minecraft = minecraft; + } + + /** Listens on the port {@code incari.sceneAgent} names, if it's set, on a thread of its own. */ + public static void startIfRequested() { + String port = System.getProperty("incari.sceneAgent"); + if (port == null || port.isBlank()) { + return; + } + Thread.ofPlatform().name("Incari scene agent").daemon().start(() -> { + try (ServerSocket server = new ServerSocket(Integer.parseInt(port), 1, InetAddress.getLoopbackAddress())) { + Minecraft minecraft = waitForGame(); + SceneAgent agent = new SceneAgent(minecraft); + while (true) { + try (Socket socket = server.accept()) { + agent.serve(socket); + } + } + } catch (IOException e) { + org.slf4j.LoggerFactory.getLogger("Scene agent").error("The scene agent stopped", e); + } + }); + } + + private void serve(Socket socket) throws IOException { + BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8)); + PrintWriter out = new PrintWriter(socket.getOutputStream(), true, StandardCharsets.UTF_8); + String line; + while ((line = in.readLine()) != null) { + String answer; + try { + answer = "ok" + run(line.strip().split(" ", -1)); + } catch (RuntimeException | IOException e) { + answer = "error " + e.toString().replace('\n', ' '); + } + out.println(answer); + } + } + + private String run(String[] command) throws IOException { + return switch (command[0]) { + case "state" -> " " + onGameThread(this::state); + case "key" -> { + injector().key(Integer.parseInt(command[1]), Integer.parseInt(command[2]), command[3].equals("down")); + yield ""; + } + case "move", "click" -> { + float[] size = onGameThread(() -> new float[] { + minecraft.getWindow().getScreenWidth(), + minecraft.getWindow().getScreenHeight() + }); + SdlInjector injector = injector(); + injector.moveTo(Float.parseFloat(command[1]) * size[0], Float.parseFloat(command[2]) * size[1]); + if (command[0].equals("click")) { + injector.mouseButton(1, true); + injector.mouseButton(1, false); + } + yield ""; + } + case "type" -> { + injector().text(String.join(" ", java.util.Arrays.copyOfRange(command, 1, command.length))); + yield ""; + } + case "shot" -> " " + shot(Path.of(command[1])); + default -> throw new IllegalArgumentException("Unknown command " + command[0]); + }; + } + + private String state() { + if (minecraft.level == null || minecraft.player == null) { + return "menu"; + } + return minecraft.gui.screen() == null ? "world" : "screen"; + } + + private String shot(Path file) throws IOException { + Path parent = file.toAbsolutePath().getParent(); + if (parent != null) { + Files.createDirectories(parent); + } + CompletableFuture written = new CompletableFuture<>(); + onGameThread(() -> { + Screenshot.takeScreenshot(minecraft.gameRenderer.mainRenderTarget(), image -> { + try (NativeImage owned = image) { + owned.writeToFile(file); + written.complete(owned.getWidth() + " " + owned.getHeight()); + } catch (IOException | RuntimeException e) { + written.completeExceptionally(e); + } + }); + return ""; + }); + try { + return written.get(1, TimeUnit.MINUTES); + } catch (Exception e) { + throw new IOException("The screenshot wasn't written", e); + } + } + + private SdlInjector injector() { + SdlInjector current = input; + if (current == null) { + int windowId = onGameThread( + () -> SDLVideo.SDL_GetWindowID(minecraft.getWindow().handle())); + current = new SdlInjector(windowId); + current.focus(); + input = current; + } + return current; + } + + private T onGameThread(java.util.function.Supplier task) { + try { + return minecraft.submit(task).get(1, TimeUnit.MINUTES); + } catch (Exception e) { + throw new IllegalStateException("A scene agent command failed on the game thread", e); + } + } + + private static Minecraft waitForGame() { + while (true) { + Minecraft instance = Minecraft.getInstance(); + if (instance != null) { + return instance; + } + try { + Thread.sleep(200); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted", e); + } + } + } +} diff --git a/incari-client/files/app-desktop/src/main/java/incari/app/desktop/smoke/ScriptedRtc.java b/incari-client/files/app-desktop/src/main/java/incari/app/desktop/smoke/ScriptedRtc.java new file mode 100644 index 0000000..23ad604 --- /dev/null +++ b/incari-client/files/app-desktop/src/main/java/incari/app/desktop/smoke/ScriptedRtc.java @@ -0,0 +1,139 @@ +package incari.app.desktop.smoke; + +import incari.platform.api.net.NetConnection; +import incari.platform.api.rtc.IceServer; +import incari.platform.api.rtc.Microphone; +import incari.platform.api.rtc.PlatformRtc; +import incari.platform.api.rtc.RemoteVoice; +import incari.platform.api.rtc.RtcPeer; +import java.util.List; + +/** + * WebRTC's stand-in on the desktop, for the voice smoke test: peers exchange made-up + * descriptions and candidates, carried by the real server's signalling, and report the peer's + * audio once both descriptions and a candidate from the far side have come through. No audio flows; + * the browser checks cover that. Listener calls come on the game's thread, as in the browser. + */ +final class ScriptedRtc implements PlatformRtc { + + private boolean micOpen; + + @Override + public boolean supported() { + return true; + } + + /** As the browser's callbacks do: later, on the game's thread. */ + private static void later(Runnable action) { + net.minecraft.client.Minecraft.getInstance().execute(action); + } + + @Override + public Microphone microphone() { + return new Microphone() { + @Override + public State state() { + return micOpen ? State.OPEN : State.CLOSED; + } + + @Override + public void open() { + micOpen = true; + } + + @Override + public void close() { + micOpen = false; + } + + @Override + public void setTransmitting(boolean transmitting) {} + + @Override + public void setVolume(float volume) {} + + @Override + public float level() { + return 0; + } + }; + } + + @Override + public RtcPeer createPeer(List iceServers, RtcPeer.Listener listener) { + return new RtcPeer() { + private boolean local; + private boolean remote; + private boolean candidate; + private boolean audio; + private boolean closed; + + @Override + public void sendMicrophone() {} + + @Override + public NetConnection openDataChannel(String label, NetConnection.Listener channel) { + throw new UnsupportedOperationException("Voice only"); + } + + @Override + public void createOffer() { + local = true; + later(() -> { + listener.localDescription("{\"type\":\"offer\",\"sdp\":\"scripted\"}"); + listener.iceCandidate("candidate:1 1 udp 1 127.0.0.1 9 typ host", 0); + }); + } + + @Override + public void setRemoteDescription(String json) { + remote = true; + if (json.contains("offer")) { + local = true; + later(() -> { + listener.localDescription("{\"type\":\"answer\",\"sdp\":\"scripted\"}"); + listener.iceCandidate("candidate:2 1 udp 1 127.0.0.1 9 typ host", 0); + }); + } + check(); + } + + @Override + public void addIceCandidate(String line, int sdpMLineIndex) { + candidate = true; + check(); + } + + private void check() { + if (local && remote && candidate && !audio && !closed) { + audio = true; + later(() -> { + listener.stateChanged("connected"); + listener.remoteAudio(); + }); + } + } + + @Override + public RemoteVoice voice() { + return new RemoteVoice() { + @Override + public void setVolume(float volume) {} + + @Override + public void setPan(float pan) {} + + @Override + public float level() { + return 0; + } + }; + } + + @Override + public void close() { + closed = true; + } + }; + } +} diff --git a/incari-client/files/app-desktop/src/main/java/incari/app/desktop/smoke/SdlInjector.java b/incari-client/files/app-desktop/src/main/java/incari/app/desktop/smoke/SdlInjector.java new file mode 100644 index 0000000..49c0fca --- /dev/null +++ b/incari-client/files/app-desktop/src/main/java/incari/app/desktop/smoke/SdlInjector.java @@ -0,0 +1,91 @@ +package incari.app.desktop.smoke; + +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.List; +import org.lwjgl.sdl.SDLEvents; +import org.lwjgl.sdl.SDL_Event; +import org.lwjgl.system.MemoryUtil; + +/** + * Pushes synthetic events into SDL's queue, so the smoke test's input takes the same path a + * player's does: SDL's queue, the desktop platform's event pump, the game's event handler. + */ +final class SdlInjector implements AutoCloseable { + + private final int windowId; + /** Text events point at UTF-8 strings SDL reads later; they stay alive until close. */ + private final List texts = new ArrayList<>(); + + SdlInjector(int windowId) { + this.windowId = windowId; + } + + void focus() { + push(event -> event.window( + w -> w.type(SDLEvents.SDL_EVENT_WINDOW_FOCUS_GAINED).windowID(windowId))); + } + + /** + * @param scancode the physical key (a HID usage id) + * @param keyCode what it types in a US layout (SDL keycode) + */ + void key(int scancode, int keyCode, boolean down) { + push(event -> event.key(k -> k.type(down ? SDLEvents.SDL_EVENT_KEY_DOWN : SDLEvents.SDL_EVENT_KEY_UP) + .windowID(windowId) + .scancode(scancode) + .key(keyCode) + .down(down))); + } + + void tap(int scancode, int keyCode) { + key(scancode, keyCode, true); + key(scancode, keyCode, false); + } + + void text(String text) { + ByteBuffer utf8 = MemoryUtil.memUTF8(text); + texts.add(utf8); + push(event -> event.text( + t -> t.type(SDLEvents.SDL_EVENT_TEXT_INPUT).windowID(windowId).text(utf8))); + } + + /** Relative mouse motion, as while looking around. */ + void look(float dx, float dy) { + push(event -> event.motion(m -> m.type(SDLEvents.SDL_EVENT_MOUSE_MOTION) + .windowID(windowId) + .xrel(dx) + .yrel(dy))); + } + + /** Moves the pointer to a position in window coordinates, as over a menu. */ + void moveTo(float x, float y) { + push(event -> event.motion(m -> + m.type(SDLEvents.SDL_EVENT_MOUSE_MOTION).windowID(windowId).x(x).y(y))); + } + + /** @param button 1 left, 3 right */ + void mouseButton(int button, boolean down) { + push(event -> event.button( + b -> b.type(down ? SDLEvents.SDL_EVENT_MOUSE_BUTTON_DOWN : SDLEvents.SDL_EVENT_MOUSE_BUTTON_UP) + .windowID(windowId) + .button((byte) button) + .down(down) + .clicks((byte) 1))); + } + + private static void push(java.util.function.Consumer fill) { + try (SDL_Event event = SDL_Event.calloc()) { + fill.accept(event); + if (!SDLEvents.SDL_PushEvent(event)) { + throw new IllegalStateException("SDL refused an injected event"); + } + } + } + + @Override + public void close() { + texts.forEach(MemoryUtil::memFree); + texts.clear(); + } +} diff --git a/incari-client/files/app-desktop/src/main/java/incari/app/desktop/smoke/SmokeReport.java b/incari-client/files/app-desktop/src/main/java/incari/app/desktop/smoke/SmokeReport.java new file mode 100644 index 0000000..e0d4cf6 --- /dev/null +++ b/incari-client/files/app-desktop/src/main/java/incari/app/desktop/smoke/SmokeReport.java @@ -0,0 +1,67 @@ +package incari.app.desktop.smoke; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** The smoke test's results: one line per check, written to {@code /incari-smoke/report.txt}. */ +final class SmokeReport { + + private static final Logger LOGGER = LoggerFactory.getLogger("Smoke test"); + + private final Path file; + private final List lines = new ArrayList<>(); + private int failures; + + SmokeReport(Path directory) { + this.file = directory.resolve("report.txt"); + } + + void pass(String check, String detail) { + record("PASS", check, detail); + } + + void fail(String check, String detail) { + failures++; + record("FAIL", check, detail); + } + + void check(String check, boolean passed, String detail) { + if (passed) { + pass(check, detail); + } else { + fail(check, detail); + } + } + + boolean passed() { + return failures == 0 && !lines.isEmpty(); + } + + private synchronized void record(String result, String check, String detail) { + String line = result + " " + check + (detail.isEmpty() ? "" : " (" + detail + ")"); + lines.add(line); + LOGGER.info(line); + write(); + } + + synchronized void finish() { + lines.add(passed() ? "RESULT all checks passed" : "RESULT " + failures + " check(s) failed"); + LOGGER.info(lines.getLast()); + write(); + } + + private void write() { + try { + Files.createDirectories(file.getParent()); + Files.write(file, lines, StandardCharsets.UTF_8); + } catch (IOException e) { + LOGGER.warn("Couldn't write the smoke test report", e); + } + } +} diff --git a/incari-client/files/app-desktop/src/main/java/incari/app/desktop/smoke/SmokeTest.java b/incari-client/files/app-desktop/src/main/java/incari/app/desktop/smoke/SmokeTest.java new file mode 100644 index 0000000..813f67b --- /dev/null +++ b/incari-client/files/app-desktop/src/main/java/incari/app/desktop/smoke/SmokeTest.java @@ -0,0 +1,4378 @@ +package incari.app.desktop.smoke; + +import incari.client.net.ConnectionDetailsScreen; +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.concurrent.Callable; +import java.util.concurrent.TimeUnit; +import java.util.function.BooleanSupplier; +import net.minecraft.client.Minecraft; +import net.minecraft.client.Screenshot; +import net.minecraft.client.gui.components.AbstractWidget; +import net.minecraft.client.gui.screens.ChatScreen; +import net.minecraft.client.gui.screens.ConnectScreen; +import net.minecraft.client.gui.screens.DisconnectedScreen; +import net.minecraft.client.gui.screens.PauseScreen; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.gui.screens.TitleScreen; +import net.minecraft.client.gui.screens.inventory.InventoryScreen; +import net.minecraft.client.multiplayer.ServerData; +import net.minecraft.client.multiplayer.ServerStatusPinger; +import net.minecraft.client.multiplayer.resolver.ServerAddress; +import net.minecraft.client.server.IntegratedServer; +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.contents.TranslatableContents; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.network.EventLoopGroupHolder; +import net.minecraft.world.Difficulty; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.LevelSettings; +import net.minecraft.world.level.WorldDataConfiguration; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.levelgen.WorldOptions; +import net.minecraft.world.level.levelgen.presets.WorldPresets; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; +import org.jspecify.annotations.Nullable; +import org.lwjgl.sdl.SDLVideo; + +/** + * A scripted play session that checks the desktop runtime end to end ("fully playable"): + * boot, a new survival world, walking, looking, jumping, breaking and placing a block, the + * inventory, chat, sound, and the network path (a LAN server pinged and joined through the + * platform's transport). Input is injected as SDL events, so it takes the player's path. + * + *

Off unless {@code -Dincari.smoke=host} (plays and opens the world to LAN), + * {@code -Dincari.smoke=host:} (also waits that long for a second client to join), or + * {@code -Dincari.smoke=join:} (joins that world). Results + * and screenshots go to {@code /incari-smoke/}. Development tooling, never in a build + * players get. + */ +public final class SmokeTest { + + private static final long SEED = 20260926L; + /** Longer than any scenario takes; past it, the game is stuck and the watchdog ends it. */ + private static final Duration TIME_LIMIT = Duration.ofMinutes(12); + /** The mesher check meshes every section twice, over many places. */ + private static final Duration MESHER_TIME_LIMIT = Duration.ofMinutes(40); + /** How long one query to the game thread is waited on before it's asked again. */ + private static final Duration QUERY_PATIENCE = Duration.ofSeconds(10); + /** Fixed so a second client knows where to join. */ + static final int LAN_PORT = 25577; + + private final Minecraft minecraft; + private final String mode; + private final SmokeReport report; + private final Path directory; + private @Nullable SdlInjector input; + /** Every chat line the chat window has shown, recorded by a pass-through display filter. */ + private final java.util.Set seenChat = java.util.concurrent.ConcurrentHashMap.newKeySet(); + + private SmokeTest(Minecraft minecraft, String mode, Path directory) { + this.minecraft = minecraft; + this.mode = mode; + this.directory = directory; + this.report = new SmokeReport(directory); + } + + /** Before the game starts: a scripted WebRTC for the voice scenario (the desktop has none). */ + public static void configurePlatform(incari.platform.desktop.DesktopPlatform platform) { + if (System.getProperty("incari.smoke", "").startsWith("voice:")) { + platform.setRtc(new ScriptedRtc()); + } + } + + /** Starts the scenario named by {@code incari.smoke}, if any, on its own thread. */ + public static void startIfRequested(String gameDirectory) { + String mode = System.getProperty("incari.smoke"); + if (mode == null || mode.isBlank()) { + return; + } + Path directory = Path.of(gameDirectory, "incari-smoke"); + seedOptions(Path.of(gameDirectory)); + Thread.ofPlatform().name("Incari smoke test").daemon().start(() -> { + Minecraft minecraft = waitForGame(); + new SmokeTest(minecraft, mode, directory).run(); + }); + // An unattended run must never leave a game window behind: if the game hangs (a stuck + // server, a deadlock), end the process. + Thread.ofPlatform().name("Incari smoke watchdog").daemon().start(() -> { + Duration limit = mode.equals("mesher") ? MESHER_TIME_LIMIT : TIME_LIMIT; + sleep(limit); + org.slf4j.LoggerFactory.getLogger("Smoke test").error("Smoke test exceeded {}; halting", limit); + Runtime.getRuntime().halt(3); + }); + } + + /** + * A fresh game directory would start with the accessibility onboarding screen and pause + * whenever the window loses focus; neither suits an unattended run. + */ + private static void seedOptions(Path gameDirectory) { + Path options = gameDirectory.resolve("options.txt"); + if (java.nio.file.Files.exists(options)) { + return; + } + try { + java.nio.file.Files.createDirectories(gameDirectory); + java.nio.file.Files.writeString(options, """ + onboardAccessibility:false + pauseOnLostFocus:false + joinedFirstServer:true + skipMultiplayerWarning:true + tutorialStep:none + soundCategory_master:0.2 + """); + } catch (java.io.IOException e) { + throw new java.io.UncheckedIOException(e); + } + } + + private static Minecraft waitForGame() { + while (true) { + Minecraft instance = Minecraft.getInstance(); + if (instance != null) { + return instance; + } + sleep(Duration.ofMillis(200)); + } + } + + private void run() { + try { + if (mode.startsWith("join:")) { + joinScenario(mode.substring("join:".length())); + } else if (mode.startsWith("server:")) { + serverScenario(mode.substring("server:".length())); + } else if (mode.startsWith("voice:")) { + String rest = mode.substring("voice:".length()); + int colon = rest.indexOf(':'); + voiceScenario(rest.substring(0, colon), rest.substring(colon + 1)); + } else if (mode.startsWith("legacy:")) { + legacyScenario(mode.substring("legacy:".length())); + } else if (mode.startsWith("auth:")) { + authScenario(mode.substring("auth:".length())); + } else if (mode.equals("screens")) { + screensScenario(); + } else if (mode.equals("look")) { + lookScenario(); + } else if (mode.equals("modules")) { + modulesScenario(); + } else if (mode.equals("hudeditor")) { + hudEditorScenario(); + } else if (mode.equals("features")) { + featuresScenario(); + } else if (mode.equals("waypoints")) { + waypointsScenario(); + } else if (mode.equals("hudmodules")) { + hudModulesScenario(); + } else if (mode.equals("visualmodules")) { + visualModulesScenario(); + } else if (mode.equals("screenmodules")) { + screenModulesScenario(); + } else if (mode.equals("fit")) { + fitScenario(); + } else if (mode.equals("layout")) { + layoutScenario(); + } else if (mode.equals("cosmetics")) { + cosmeticsScenario(); + } else if (mode.equals("mesher")) { + mesherScenario(); + } else if (mode.startsWith("online:")) { + String rest = mode.substring("online:".length()); + int colon = rest.indexOf(':'); + onlineScenario(rest.substring(0, colon), rest.substring(colon + 1)); + } else if (mode.startsWith("skins:")) { + String rest = mode.substring("skins:".length()); + int colon = rest.indexOf(':'); + skinsScenario(rest.substring(0, colon), rest.substring(colon + 1)); + } else { + hostScenario(mode.startsWith("host:") ? Integer.parseInt(mode.substring("host:".length())) : 0); + } + } catch (Throwable t) { + report.fail("scenario", "stopped by " + t); + } finally { + report.finish(); + SdlInjector current = input; + if (current != null) { + current.close(); + } + // stop() only clears a volatile flag, so it's safe from here even if the game is stuck. + minecraft.stop(); + sleep(Duration.ofMinutes(1)); + // Still here: the game couldn't shut down. The report is written; end the process. + Runtime.getRuntime().halt(report.passed() ? 0 : 1); + } + } + + // ---------------------------------------------------------------------------------------- + // Scenarios + // ---------------------------------------------------------------------------------------- + + private void hostScenario(int waitForJoinSeconds) throws Exception { + waitForTitle(); + newSurvivalWorld(); + boolean loaded = waitUntil(Duration.ofMinutes(3), () -> inWorld() && player().tickCount > 60); + report.check( + "singleplayer world", loaded, loaded ? "created and loaded a new survival world" : stateDescription()); + if (!loaded) { + screenshot("fail-world"); + } + if (!inWorld()) { + return; + } + takeControl(); + screenshot("02-world"); + + walk(); + jump(); + look(); + breakAndPlace(); + inventory(); + chat("hello from the incari smoke test"); + sound(); + lan(waitForJoinSeconds); + + injector().tap(41, 0x1B); // Escape opens the pause menu + boolean paused = waitUntil(Duration.ofSeconds(3), () -> minecraft.gui.screen() instanceof PauseScreen); + report.check("pause menu (Escape)", paused, ""); + clickButton("menu.returnToMenu"); + boolean left = waitUntil( + Duration.ofMinutes(1), () -> minecraft.level == null && minecraft.gui.screen() instanceof TitleScreen); + report.check("save and quit", left, left ? "back on the title screen" : stateDescription()); + } + + /** Creates and enters a new peaceful survival world from the smoke test's seed. */ + private void newSurvivalWorld() { + onGameThread(() -> { + String name = "incari-smoke-" + System.currentTimeMillis(); + LevelSettings settings = new LevelSettings( + name, + GameType.SURVIVAL, + new LevelSettings.DifficultySettings(Difficulty.PEACEFUL, false, false), + true, + WorldDataConfiguration.DEFAULT); + minecraft + .createWorldOpenFlows() + .createFreshLevel( + name, + settings, + new WorldOptions(SEED, true, false), + WorldPresets::createNormalWorldDimensions, + new TitleScreen()); + return null; + }); + } + + /** + * The client's look on the screens players see most, in both GUI presets, with the + * pointer over a button (in Normal, mid-sweep): the title, options, video settings, the world + * and server lists, the module menu; then in a world, the pause menu and the inventory. + */ + private void lookScenario() throws Exception { + waitForTitle(); + takeControl(); + boolean skinned = onGameThread(() -> incari.client.ui.Skins.current() != null); + report.check("Incari's skin on", skinned, ""); + // The loading screen in the client's look (LoadingLook), mid-reload over the title: past + // its fade in, before the reload's done. + onGameThread(() -> { + minecraft.gui.setScreen(new TitleScreen()); + var _ = minecraft.reloadResourcePacks(); // waited on through the overlay below + return null; + }); + sleep(Duration.ofMillis(700)); + boolean loading = onGameThread(() -> minecraft.gui.overlay() != null); + screenshot("look-loading"); + report.check("Loading screen shown on a reload", loading, ""); + waitUntil(Duration.ofSeconds(30), () -> minecraft.gui.overlay() == null); + for (incari.client.ui.GuiPreset preset : incari.client.ui.GuiPreset.values()) { + String name = "look-" + preset.name().toLowerCase(java.util.Locale.ROOT); + onGameThread(() -> { + incari.client.ui.Look.set(preset); + return null; + }); + lookAt(new TitleScreen(), "menu.options", name + "-title"); + lookAt( + new net.minecraft.client.gui.screens.options.OptionsScreen(new TitleScreen(), minecraft.options), + "options.video", + name + "-options"); + lookAt( + new net.minecraft.client.gui.screens.options.VideoSettingsScreen( + new TitleScreen(), minecraft, minecraft.options), + "gui.done", + name + "-video"); + lookAt( + new net.minecraft.client.gui.screens.multiplayer.JoinMultiplayerScreen(new TitleScreen()), + "selectServer.add", + name + "-servers"); + lookAt( + new net.minecraft.client.gui.screens.worldselection.SelectWorldScreen(new TitleScreen()), + "selectWorld.create", + name + "-worlds"); + onGameThread(() -> { + incari.client.modules.IncariModules.openMenu(new TitleScreen()); + return null; + }); + sleep(Duration.ofSeconds(1)); + hoverButton("gui.done"); + sleep(Duration.ofMillis(250)); + screenshot(name + "-modules"); + } + + newSurvivalWorld(); + boolean loaded = waitUntil(Duration.ofMinutes(3), () -> inWorld() && player().tickCount > 60); + report.check("singleplayer world", loaded, loaded ? "" : stateDescription()); + if (!loaded) { + screenshot("fail-world"); + return; + } + for (incari.client.ui.GuiPreset preset : incari.client.ui.GuiPreset.values()) { + String name = "look-" + preset.name().toLowerCase(java.util.Locale.ROOT); + onGameThread(() -> { + incari.client.ui.Look.set(preset); + return null; + }); + lookAt(new PauseScreen(true), "menu.returnToGame", name + "-pause"); + lookAt(new InventoryScreen(player()), "", name + "-inventory"); + lookAt( + new net.minecraft.client.gui.screens.inventory.ContainerScreen( + net.minecraft.world.inventory.ChestMenu.threeRows(1, player().getInventory()), + player().getInventory(), + net.minecraft.network.chat.Component.literal("Chest")), + "", + name + "-chest"); + lookAt( + new net.minecraft.client.gui.screens.inventory.FurnaceScreen( + new net.minecraft.world.inventory.FurnaceMenu(1, player().getInventory()), + player().getInventory(), + net.minecraft.network.chat.Component.literal("Furnace")), + "", + name + "-furnace"); + } + + // The HUD: the hotbar, a scoreboard sidebar, chat with its field open, the tab list. + serverCommand("give @s minecraft:diamond_sword"); + serverCommand("give @s minecraft:oak_planks 32"); + serverCommand("scoreboard objectives add incari dummy \"Incari\""); + serverCommand("scoreboard objectives setdisplay sidebar incari"); + // Alone in singleplayer, the tab list shows only with an objective in it. + serverCommand("scoreboard objectives setdisplay list incari"); + serverCommand("scoreboard players set Snow incari 12"); + serverCommand("scoreboard players set Frost incari 7"); + onGameThread(() -> { + minecraft.gui.setScreen(null); + minecraft + .gui + .hud + .getChat() + .addClientSystemMessage(net.minecraft.network.chat.Component.literal("Welcome to Incari.")); + return null; + }); + sleep(Duration.ofSeconds(1)); + screenshot("look-hud"); + onGameThread(() -> { + minecraft.gui.setScreen(new ChatScreen("hello", false)); + return null; + }); + sleep(Duration.ofMillis(800)); + screenshot("look-chat"); + onGameThread(() -> { + minecraft.gui.setScreen(null); + return null; + }); + onGameThread(() -> { + minecraft.options.keyPlayerList.setDown(true); // Tab held: the player list + return null; + }); + sleep(Duration.ofMillis(600)); + screenshot("look-tab"); + onGameThread(() -> { + minecraft.options.keyPlayerList.setDown(false); + return null; + }); + boolean still = onGameThread(() -> incari.client.ui.Skins.current() != null); + report.check("Incari's skin still on", still, still ? "" : "dropped: see the log"); + onGameThread(() -> { + incari.client.ui.Look.set(incari.client.ui.GuiPreset.POTATO); + minecraft.gui.setScreen(new PauseScreen(true)); + return null; + }); + sleep(Duration.ofMillis(500)); + clickButton("menu.returnToMenu"); + waitUntil( + Duration.ofMinutes(1), () -> minecraft.level == null && minecraft.gui.screen() instanceof TitleScreen); + } + + /** Shows {@code screen}, puts the pointer over its button {@code hover}, and screenshots it. */ + private void lookAt(Screen screen, String hover, String name) { + onGameThread(() -> { + minecraft.gui.setScreen(screen); + return null; + }); + sleep(Duration.ofSeconds(1)); + injector().moveTo(2, 2); + sleep(Duration.ofMillis(200)); + if (!hover.isEmpty()) { + hoverButton(hover); + } + // Normal's light sweep is part way across by now. + sleep(Duration.ofMillis(250)); + screenshot(name); + } + + /** + * The module framework end to end. The module menu opens on its key; Toggle Sprint, turned + * on, latches sprinting on a tap of the sprint key and says so on the HUD, and a second tap stops + * it; the profile is saved to the game directory; the generated settings screen, the profiles + * screen and the pause menu's Modules button are drawn. + */ + private void modulesScenario() throws Exception { + waitForTitle(); + newSurvivalWorld(); + boolean loaded = waitUntil(Duration.ofMinutes(3), () -> inWorld() && player().tickCount > 60); + report.check("singleplayer world", loaded, loaded ? "" : stateDescription()); + if (!loaded) { + screenshot("fail-world"); + return; + } + takeControl(); + + injector().tap(229, 0x400000E5); // Right Shift: the module menu + boolean menu = waitUntil(Duration.ofSeconds(3), () -> screenName().equals("ModuleListScreen")); + report.check("module menu (Right Shift)", menu, menu ? "" : stateDescription()); + screenshot("modules-menu"); + + incari.framework.Module toggleSprint = onGameThread(() -> { + incari.framework.Module module = + incari.client.modules.IncariModules.system().module("togglesprint"); + if (module == null) { + throw new IllegalStateException("No togglesprint module"); + } + module.setEnabled(true); + incari.client.modules.IncariModules.openSettings(minecraft.gui.screen(), module); + return module; + }); + sleep(Duration.ofSeconds(1)); + screenshot("modules-settings"); + onGameThread(() -> { + incari.client.modules.IncariModules.openProfiles(minecraft.gui.screen()); + return null; + }); + sleep(Duration.ofSeconds(1)); + screenshot("modules-profiles"); + onGameThread(() -> { + minecraft.gui.setScreen(null); + minecraft.mouseHandler.grabMouse(); + return null; + }); + waitUntil(Duration.ofSeconds(3), () -> minecraft.gui.screen() == null); + sleep(Duration.ofMillis(500)); + + // A tap of Left Control latches sprinting: W alone then sprints. + injector().tap(224, 0x400000E0); + sleep(Duration.ofMillis(300)); + injector().key(44, ' ', true); + injector().key(26, 'w', true); + boolean sprinting = waitUntil(Duration.ofSeconds(3), () -> player().isSprinting()); + screenshot("modules-hud"); + injector().key(26, 'w', false); + injector().key(44, ' ', false); + report.check("toggle sprint latches", sprinting, sprinting ? "" : "W alone didn't sprint after a Control tap"); + + injector().tap(224, 0x400000E0); + sleep(Duration.ofMillis(300)); + injector().key(26, 'w', true); + sleep(Duration.ofSeconds(1)); + boolean stopped = !onGameThread(() -> player().isSprinting()); + injector().key(26, 'w', false); + report.check("a second tap unlatches", stopped, stopped ? "" : "still sprinting"); + + // Saved a second after the change, under the game directory. + sleep(Duration.ofMillis(1500)); + Path profile = directory.resolveSibling("incari/modules/profiles/Default.json"); + String saved = Files.isRegularFile(profile) ? Files.readString(profile) : ""; + boolean kept = saved.contains("\"togglesprint\"") && saved.contains("\"enabled\": true"); + report.check("profile saved", kept, kept ? profile.toString() : "not in " + profile); + report.check("module still on", onGameThread(toggleSprint::isEnabled), ""); + + injector().tap(41, 0x1B); // Escape opens the pause menu + boolean paused = waitUntil(Duration.ofSeconds(3), () -> minecraft.gui.screen() instanceof PauseScreen); + report.check("pause menu", paused, ""); + screenshot("modules-pause"); + clickButton("menu.returnToMenu"); + waitUntil( + Duration.ofMinutes(1), () -> minecraft.level == null && minecraft.gui.screen() instanceof TitleScreen); + } + + /** + * ADR 0050: the first modules, in a world. Armor & Potion View shows worn + * diamond armor and three effects; Custom Scoreboard moves a server's sidebar from the game's + * place to the top left, scaled; Clear Chat and No Hurt Cam hold their game options and give + * them back, and moving Clear Chat's slider turns it off; Low Fire lowers the flames on a + * burning player. Screenshots for each, and the HUD editor with them all. + */ + private void featuresScenario() throws Exception { + waitForTitle(); + newSurvivalWorld(); + boolean loaded = waitUntil(Duration.ofMinutes(3), () -> inWorld() && player().tickCount > 60); + report.check("singleplayer world", loaded, loaded ? "" : stateDescription()); + if (!loaded) { + screenshot("fail-world"); + return; + } + takeControl(); + serverCommands( + "time set noon", + "item replace entity @p armor.head with diamond_helmet[damage=40]", + "item replace entity @p armor.chest with diamond_chestplate[damage=300]", + "item replace entity @p armor.legs with iron_leggings[damage=200]", + "item replace entity @p armor.feet with diamond_boots[damage=410]", + "item replace entity @p weapon.mainhand with diamond_sword[damage=500]", + "effect give @p speed 83 1", + "effect give @p fire_resistance infinite 0", + "effect give @p strength 8 0", + "scoreboard objectives add kills dummy \"Incari Test\"", + "scoreboard objectives setdisplay sidebar kills", + "scoreboard players set Kills kills 12", + "scoreboard players set Deaths kills 3", + "scoreboard players set Coins kills 250", + "say Clear Chat: no box behind these lines", + "say A second line"); + sleep(Duration.ofSeconds(1)); + screenshot("features-off"); + + // The tab list's header, players and footer as one card, no dark band where they meet. + serverCommands("scoreboard objectives setdisplay list kills"); + onGameThread(() -> { + var tabList = minecraft.gui.hud.getTabList(); + tabList.setHeader(net.minecraft.network.chat.Component.literal("Incari Test\n\nA second header line")); + tabList.setFooter(net.minecraft.network.chat.Component.literal("A footer line\nAnother")); + minecraft.options.keyPlayerList.setDown(true); + return null; + }); + sleep(Duration.ofSeconds(1)); + screenshot("features-tab-list"); + onGameThread(() -> { + minecraft.options.keyPlayerList.setDown(false); + return null; + }); + serverCommands("scoreboard objectives setdisplay list"); + + incari.framework.ModuleSystem system = onGameThread(incari.client.modules.IncariModules::system); + String[] ids = {"armorpotionview", "customscoreboard", "clearchat", "lowfire", "nohurtcam"}; + double opacityBefore = + onGameThread(() -> minecraft.options.textBackgroundOpacity().get()); + double tiltBefore = + onGameThread(() -> minecraft.options.damageTiltStrength().get()); + onGameThread(() -> { + for (String id : ids) { + incari.framework.Module module = system.module(id); + if (module == null) { + throw new IllegalStateException("No module " + id); + } + module.setEnabled(true); + } + return null; + }); + serverCommands("say Clear Chat: no box behind these lines"); + sleep(Duration.ofSeconds(1)); + screenshot("features-on"); + report.check( + "clear chat holds the background opacity at 0", + onGameThread(() -> minecraft.options.textBackgroundOpacity().get() == 0.0), + "was " + opacityBefore); + report.check( + "no hurt cam holds damage tilt at 0", + onGameThread(() -> minecraft.options.damageTiltStrength().get() == 0.0), + "was " + tiltBefore); + report.check( + "the sidebar is the module's", + onGameThread(() -> system.holds(incari.framework.game.GamePart.SCOREBOARD)), + ""); + + incari.framework.Module scoreboard = system.module("customscoreboard"); + if (scoreboard != null) { + incari.framework.hud.HudElement sidebar = scoreboard.hudElements().get(0); + onGameThread(() -> { + sidebar.anchor().set(incari.framework.hud.Anchor.TOP_LEFT); + sidebar.offsetX().set(4); + sidebar.offsetY().set(4); + sidebar.scale().set(1.5F); + return null; + }); + sleep(Duration.ofSeconds(1)); + screenshot("features-scoreboard-moved"); + } + + // Burning, in first person: the flames drawn lower, then where the game draws them. + onGameThread(() -> { + IntegratedServer server = minecraft.getSingleplayerServer(); + if (server != null) { + server.execute(() -> server.getPlayerList().getPlayers().get(0).setRemainingFireTicks(1200)); + } + return null; + }); + boolean burning = waitUntil(Duration.ofSeconds(5), () -> player().isOnFire()); + report.check("player on fire", burning, ""); + incari.framework.Module lowFire = system.module("lowfire"); + if (lowFire != null) { + sleep(Duration.ofMillis(1500)); + onGameThread(() -> { + lowFire.setEnabled(false); + return null; + }); + sleep(Duration.ofMillis(500)); + for (int frame = 0; frame < 6; frame++) { + screenshot("features-fire-game-" + frame); + } + incari.framework.setting.IntSetting lower = + (incari.framework.setting.IntSetting) lowFire.settings().get("lower"); + for (int percent : new int[] {10, 20, 30}) { + onGameThread(() -> { + lowFire.setEnabled(true); + if (lower != null) { + lower.set(percent); + } + return null; + }); + sleep(Duration.ofMillis(300)); + for (int frame = 0; frame < 6; frame++) { + screenshot("features-fire-low-" + percent + "-" + frame); + } + } + } + + onGameThread(() -> { + incari.client.modules.IncariModules.openHudEditor(null); + return null; + }); + sleep(Duration.ofSeconds(1)); + screenshot("features-hudeditor"); + onGameThread(() -> { + minecraft.gui.setScreen(null); + return null; + }); + + // The slider is the player's: moving it turns Clear Chat off and keeps the new value. + onGameThread(() -> { + minecraft.options.textBackgroundOpacity().set(0.3); + return null; + }); + incari.framework.Module clearChat = system.module("clearchat"); + boolean letGo = clearChat != null && waitUntil(Duration.ofSeconds(3), () -> !clearChat.isEnabled()); + report.check( + "moving the slider turns clear chat off", + letGo + && onGameThread( + () -> minecraft.options.textBackgroundOpacity().get() == 0.3), + ""); + onGameThread(() -> { + incari.framework.Module noHurtCam = system.module("nohurtcam"); + if (noHurtCam != null) { + noHurtCam.setEnabled(false); + } + return null; + }); + double tiltAfter = + onGameThread(() -> minecraft.options.damageTiltStrength().get()); + report.check("no hurt cam gives damage tilt back", Math.abs(tiltAfter - tiltBefore) < 0.01, "now " + tiltAfter); + oldTexturesChecks(system); + sleep(Duration.ofMillis(1500)); + system.flush(); + } + + /** ADR 0055: Old Textures is Programmer Art's switch, and the Resource Packs screen is its too. */ + private void oldTexturesChecks(incari.framework.ModuleSystem system) { + incari.framework.Module oldTextures = system.module("oldtextures"); + if (oldTextures == null) { + report.check("old textures module", false, "no module oldtextures"); + return; + } + onGameThread(() -> { + oldTextures.setEnabled(true); + return null; + }); + boolean packOn = + waitUntil(Duration.ofSeconds(2), () -> minecraft.options.resourcePacks.contains("programmer_art")); + boolean reloaded = waitUntil(Duration.ofSeconds(60), () -> minecraft.gui.overlay() == null); + // Under Incari's pack, which is fixed on top, as the Resource Packs screen puts it. + java.util.List order = onGameThread(() -> + java.util.List.copyOf(minecraft.getResourcePackRepository().getSelectedIds())); + boolean under = + order.indexOf("programmer_art") >= 0 && order.indexOf("programmer_art") < order.indexOf("incari"); + report.check( + "old textures turns programmer art on", + packOn && reloaded && oldTextures.isEnabled() && under, + "packs " + order); + screenshot("features-old-textures"); + + // As the Resource Packs screen leaves it: the repository's selection, then the options. + onGameThread(() -> { + var packs = minecraft.getResourcePackRepository(); + packs.removePack("programmer_art"); + minecraft.options.updateResourcePacks(packs); + return null; + }); + boolean followedOff = waitUntil(Duration.ofSeconds(3), () -> !oldTextures.isEnabled()); + waitUntil(Duration.ofSeconds(60), () -> minecraft.gui.overlay() == null); + onGameThread(() -> { + var packs = minecraft.getResourcePackRepository(); + packs.addPack("programmer_art"); + minecraft.options.updateResourcePacks(packs); + return null; + }); + boolean followedOn = waitUntil(Duration.ofSeconds(3), oldTextures::isEnabled); + waitUntil(Duration.ofSeconds(60), () -> minecraft.gui.overlay() == null); + report.check( + "the resource packs screen turns old textures", + followedOff && followedOn, + "off " + followedOff + ", on " + followedOn); + + onGameThread(() -> { + oldTextures.setEnabled(false); + return null; + }); + boolean packOff = + waitUntil(Duration.ofSeconds(2), () -> !minecraft.options.resourcePacks.contains("programmer_art")); + waitUntil(Duration.ofSeconds(60), () -> minecraft.gui.overlay() == null); + report.check("old textures turns programmer art off", packOff, ""); + screenshot("features-new-textures"); + } + + /** + * ADR 0052: Keystrokes, CPS, FPS Display, Reach Display, Coordinates and Shield & Totem HUD in + * a world: keys held and clicks on a mob in reach, a shield and totems carried. + */ + private void hudModulesScenario() throws Exception { + waitForTitle(); + newSurvivalWorld(); + boolean loaded = waitUntil(Duration.ofMinutes(3), () -> inWorld() && player().tickCount > 60); + report.check("singleplayer world", loaded, loaded ? "" : stateDescription()); + if (!loaded) { + screenshot("fail-world"); + return; + } + takeControl(); + serverCommands( + "time set noon", + "gamerule doMobSpawning false", + "execute as @p at @s run tp @s ~ ~ ~ 180 0", + "item replace entity @p weapon.offhand with shield[damage=200]", + "give @p totem_of_undying 2", + "execute at @p run summon villager ~ ~ ~-2.6 {NoAI:1b,Invulnerable:1b,Rotation:[0f,0f]}"); + sleep(Duration.ofSeconds(1)); + + incari.framework.ModuleSystem system = onGameThread(incari.client.modules.IncariModules::system); + String[] ids = {"keystrokes", "cps", "fpsdisplay", "reachdisplay", "coordinates", "shieldtotem"}; + java.util.List reaches = new java.util.concurrent.CopyOnWriteArrayList<>(); + java.util.List clicks = new java.util.concurrent.CopyOnWriteArrayList<>(); + incari.framework.event.AttackListener attackProbe = reaches::add; + incari.framework.event.ClickListener clickProbe = clicks::add; + onGameThread(() -> { + for (String id : ids) { + incari.framework.Module module = system.module(id); + if (module == null) { + throw new IllegalStateException("No module " + id); + } + module.setEnabled(true); + } + system.events().add(incari.framework.event.Events.ATTACK, this, attackProbe); + system.events().add(incari.framework.event.Events.CLICK, this, clickProbe); + return null; + }); + for (int i = 0; i < 6; i++) { + injector().mouseButton(1, true); + sleep(Duration.ofMillis(40)); + injector().mouseButton(1, false); + sleep(Duration.ofMillis(110)); + } + injector().mouseButton(3, true); + sleep(Duration.ofMillis(40)); + injector().mouseButton(3, false); + // W and space held while the HUD is shot: their keys lit. + injector().key(26, 'w', true); + injector().key(44, ' ', true); + sleep(Duration.ofMillis(200)); + screenshot("hudmodules-on"); + injector().key(26, 'w', false); + injector().key(44, ' ', false); + report.check("clicks reach modules", clicks.size() >= 7, clicks.size() + " clicks"); + report.check( + "hits report their reach", + !reaches.isEmpty() && reaches.get(0) > 1.5 && reaches.get(0) < 3.5, + reaches.toString()); + incari.framework.game.Game game = system.game(); + report.check("fps read", onGameThread(game::fps) > 0, ""); + report.check( + "W bound as W", + onGameThread(() -> game.keyName(incari.framework.game.GameKey.FORWARD)) + .equals("W"), + onGameThread(() -> game.keyName(incari.framework.game.GameKey.FORWARD))); + report.check( + "attack bound as LMB", + onGameThread(() -> game.keyName(incari.framework.game.GameKey.ATTACK)) + .equals("LMB"), + onGameThread(() -> game.keyName(incari.framework.game.GameKey.ATTACK))); + report.check( + "totems counted", + onGameThread(() -> { + incari.framework.game.PlayerView view = game.player(); + return view == null ? -1 : view.count("minecraft:totem_of_undying"); + }) + == 2, + ""); + report.check( + "shield seen in the off hand", + onGameThread(() -> { + incari.framework.game.PlayerView view = game.player(); + return view != null + && view.item(incari.framework.game.EquipmentSlot.OFFHAND) + .id() + .equals("minecraft:shield"); + }), + ""); + String biome = onGameThread(() -> { + incari.framework.game.PlayerView view = game.player(); + return view == null ? "" : view.biome(); + }); + report.check("biome named", !biome.isEmpty() && !biome.startsWith("biome."), biome); + + onGameThread(() -> { + system.events().remove(incari.framework.event.Events.ATTACK, attackProbe); + system.events().remove(incari.framework.event.Events.CLICK, clickProbe); + incari.client.modules.IncariModules.openHudEditor(null); + return null; + }); + sleep(Duration.ofSeconds(1)); + screenshot("hudmodules-hudeditor"); + onGameThread(() -> { + minecraft.gui.setScreen(null); + return null; + }); + sleep(Duration.ofMillis(500)); + system.flush(); + } + + /** + * ADR 0053: Crosshair Editor's presets and grid, Cooldown Indicator after a swing, Weather + * Changer over a server's rain (clear, snow, midnight), Freelook with Left Alt held, Low Shield, + * and 1.7 Animations' poses and block-hit. + */ + private void visualModulesScenario() throws Exception { + waitForTitle(); + newSurvivalWorld(); + boolean loaded = waitUntil(Duration.ofMinutes(3), () -> inWorld() && player().tickCount > 60); + report.check("singleplayer world", loaded, loaded ? "" : stateDescription()); + if (!loaded) { + screenshot("fail-world"); + return; + } + takeControl(); + serverCommands( + "time set noon", + "gamerule doDaylightCycle false", + "execute as @p at @s run tp @s ~ ~ ~ 180 10", + "item replace entity @p weapon.mainhand with diamond_sword", + "item replace entity @p weapon.offhand with shield"); + sleep(Duration.ofSeconds(1)); + incari.framework.ModuleSystem system = onGameThread(incari.client.modules.IncariModules::system); + + // Crosshair Editor: each preset, then the grid. + incari.framework.Module crosshair = module(system, "crosshair"); + screenshot("visual-crosshair-game"); + onGameThread(() -> { + crosshair.setEnabled(true); + return null; + }); + for (String each : new String[] {"classic", "competitive", "small", "dot", "circle", "t_shape"}) { + choose(crosshair, "preset", each); + sleep(Duration.ofMillis(300)); + screenshot("visual-crosshair-" + each); + } + choose(crosshair, "style", "grid"); + sleep(Duration.ofMillis(300)); + screenshot("visual-crosshair-grid"); + choose(crosshair, "preset", "competitive"); + + // Cooldown Indicator: the game's own off, the bar charging after a swing. + incari.framework.Module cooldown = module(system, "cooldownindicator"); + onGameThread(() -> { + cooldown.setEnabled(true); + return null; + }); + report.check( + "cooldown indicator holds the game's indicator off", + onGameThread(() -> + minecraft.options.attackIndicator().get() == net.minecraft.client.AttackIndicatorStatus.OFF), + ""); + injector().mouseButton(1, true); + sleep(Duration.ofMillis(30)); + injector().mouseButton(1, false); + sleep(Duration.ofMillis(150)); + screenshot("visual-cooldown-bar"); + choose(cooldown, "style", "ring"); + sleep(Duration.ofMillis(800)); + injector().mouseButton(1, true); + sleep(Duration.ofMillis(30)); + injector().mouseButton(1, false); + sleep(Duration.ofMillis(200)); + screenshot("visual-cooldown-ring"); + onGameThread(() -> { + cooldown.setEnabled(false); + return null; + }); + report.check( + "cooldown indicator gives the game's indicator back", + onGameThread(() -> + minecraft.options.attackIndicator().get() != net.minecraft.client.AttackIndicatorStatus.OFF), + ""); + + // Weather Changer over the server's rain. + serverCommands("weather rain"); + waitUntil(Duration.ofSeconds(15), () -> onGameThread(() -> level().getRainLevel(1.0F) > 0.9F)); + screenshot("visual-weather-rain"); + incari.framework.Module weather = module(system, "weatherchanger"); + choose(weather, "weather", "clear"); + onGameThread(() -> { + ((incari.framework.setting.BooleanSetting) + java.util.Objects.requireNonNull(weather.settings().get("hold-time"))) + .set(false); + weather.setEnabled(true); + return null; + }); + sleep(Duration.ofMillis(500)); + report.check( + "weather changer clears the rain", + onGameThread(() -> incari.client.modules.ModuleSky.shownRain(level(), 1.0F) == 0.0F), + ""); + // Only where it's drawn: the game's own rain checks (a trident's Riptide) see the real. + report.check("the client level keeps the real rain", onGameThread(() -> level().isRaining()), ""); + boolean serverStillRains = onGameThread(() -> { + IntegratedServer server = minecraft.getSingleplayerServer(); + return server != null && server.overworld().isRaining(); + }); + report.check("the server's rain goes on", serverStillRains, ""); + screenshot("visual-weather-clear"); + choose(weather, "weather", "snow"); + onGameThread(() -> { + ((incari.framework.setting.BooleanSetting) + java.util.Objects.requireNonNull(weather.settings().get("hold-time"))) + .set(true); + ((incari.framework.setting.IntSetting) + java.util.Objects.requireNonNull(weather.settings().get("hour"))) + .set(0); + return null; + }); + sleep(Duration.ofSeconds(2)); + screenshot("visual-weather-snow-midnight"); + onGameThread(() -> { + weather.setEnabled(false); + return null; + }); + sleep(Duration.ofMillis(300)); + report.check("weather changer gives the rain back", onGameThread(() -> level().getRainLevel(1.0F) > 0.9F), ""); + serverCommands("weather clear"); + + // Freelook: Left Alt held, the mouse turns the camera and not the player. + incari.framework.Module freelook = module(system, "freelook"); + onGameThread(() -> { + freelook.setEnabled(true); + return null; + }); + float yawBefore = onGameThread(() -> player().getYRot()); + // The game turns only while its window is active (as look() finds). + injector().focus(); + sleep(Duration.ofMillis(100)); + injector().key(226, 0x400000E2, true); + sleep(Duration.ofMillis(300)); + for (int i = 0; i < 10; i++) { + injector().look(40, 0); + sleep(Duration.ofMillis(30)); + } + sleep(Duration.ofMillis(300)); + float yawDuring = onGameThread(() -> player().getYRot()); + float cameraYaw = onGameThread(() -> minecraft.gameRenderer.mainCamera().yRot()); + boolean third = onGameThread( + () -> minecraft.options.getCameraType() == net.minecraft.client.CameraType.THIRD_PERSON_BACK); + screenshot("visual-freelook"); + injector().key(226, 0x400000E2, false); + sleep(Duration.ofMillis(400)); + boolean first = onGameThread(() -> minecraft.options.getCameraType().isFirstPerson()); + report.check( + "freelook turns the camera, not the player", + Math.abs(yawDuring - yawBefore) < 0.01F && Math.abs(cameraYaw - yawBefore) > 5, + "player " + yawBefore + " -> " + yawDuring + ", camera " + cameraYaw); + report.check("freelook looks from behind, then back", third && first, "third " + third + ", first " + first); + onGameThread(() -> { + freelook.setEnabled(false); + return null; + }); + + // Hitboxes: a villager (the world may be peaceful) under the crosshair and a cow beside it. + // On flat ground cleared in front (north), so neither stands in the hillside. + serverCommands( + "execute as @p at @s run fill ~-5 ~-1 ~-8 ~5 ~-1 ~2 stone", + "execute as @p at @s run fill ~-5 ~ ~-8 ~5 ~4 ~2 air", + "execute as @p at @s run tp @s ~ ~ ~ 180 10", + "execute as @p at @s run summon villager ^ ^ ^3 {NoAI:1b,Silent:1b,Rotation:[0f,0f]}", + "execute as @p at @s run summon cow ^2 ^ ^4 {NoAI:1b,Silent:1b}"); + sleep(Duration.ofSeconds(1)); + screenshot("visual-hitboxes-game"); + incari.framework.Module hitboxes = module(system, "hitboxes"); + onGameThread(() -> { + hitboxes.settings().resetAll(); + hitboxes.setEnabled(true); + return null; + }); + sleep(Duration.ofMillis(300)); + incari.framework.game.Hitboxes held = onGameThread(incari.client.modules.ModuleHitboxes::held); + report.check("hitboxes reach the renderer", held != null, String.valueOf(held)); + boolean aimed = onGameThread( + () -> minecraft.crosshairPickEntity instanceof net.minecraft.world.entity.npc.villager.Villager); + report.check( + "the crosshair is on the villager", + aimed, + String.valueOf(onGameThread(() -> minecraft.crosshairPickEntity))); + screenshot("visual-hitboxes-on"); + choose(hitboxes, "show", "players"); + onGameThread(() -> { + ((incari.framework.setting.BooleanSetting) + java.util.Objects.requireNonNull(hitboxes.settings().get("own"))) + .set(true); + minecraft.options.setCameraType(net.minecraft.client.CameraType.THIRD_PERSON_BACK); + return null; + }); + sleep(Duration.ofMillis(500)); + held = onGameThread(incari.client.modules.ModuleHitboxes::held); + report.check( + "a hitboxes setting reaches the renderer at once", + held != null && held.show() == incari.framework.game.Hitboxes.Show.PLAYERS && held.own(), + String.valueOf(held)); + screenshot("visual-hitboxes-own"); + onGameThread(() -> { + minecraft.options.setCameraType(net.minecraft.client.CameraType.FIRST_PERSON); + hitboxes.setEnabled(false); + return null; + }); + report.check("hitboxes off draws none", onGameThread(incari.client.modules.ModuleHitboxes::held) == null, ""); + serverCommands("kill @e[type=villager]", "kill @e[type=cow]"); + + schematicsSteps(system); + + // Low Shield and 1.7 Animations: the hands without, then with. + serverCommands("execute as @p at @s run tp @s ~ ~ ~ 180 10"); + sleep(Duration.ofMillis(500)); + screenshot("visual-hands-game"); + incari.framework.Module lowShield = module(system, "lowshield"); + incari.framework.Module old = module(system, "oldanimations"); + onGameThread(() -> { + lowShield.setEnabled(true); + old.setEnabled(true); + return null; + }); + sleep(Duration.ofMillis(500)); + screenshot("visual-hands-modules"); + serverCommands("item replace entity @p weapon.mainhand with fishing_rod"); + sleep(Duration.ofMillis(800)); + screenshot("visual-hands-rod"); + onGameThread(() -> { + old.setEnabled(false); + return null; + }); + sleep(Duration.ofMillis(300)); + screenshot("visual-hands-rod-game"); + // A sword that blocks (as on a 1.8 server): 1.7's pose, then the block-hit on a block. + serverCommands( + "item replace entity @p weapon.offhand with air", + "item replace entity @p weapon.mainhand with diamond_sword[blocks_attacks={}]", + "execute as @p at @s run tp @s ~ ~ ~ 180 70"); + sleep(Duration.ofMillis(800)); + injector().mouseButton(3, true); + sleep(Duration.ofMillis(500)); + screenshot("visual-block-game"); + onGameThread(() -> { + old.setEnabled(true); + return null; + }); + sleep(Duration.ofMillis(300)); + screenshot("visual-block-old"); + boolean using = onGameThread(() -> player().isUsingItem()); + injector().mouseButton(1, true); + boolean swung = waitUntil(Duration.ofSeconds(2), () -> onGameThread(() -> player().getCurrentSwing() != null)); + sleep(Duration.ofMillis(100)); + screenshot("visual-block-hit"); + boolean stillUsing = onGameThread(() -> player().isUsingItem()); + injector().mouseButton(1, false); + injector().mouseButton(3, false); + report.check("blocking with the sword", using, ""); + report.check( + "block-hit swings while blocking", + swung && stillUsing, + "swung " + swung + ", still using " + stillUsing); + onGameThread(() -> { + lowShield.setEnabled(false); + old.setEnabled(false); + crosshair.setEnabled(false); + return null; + }); + sleep(Duration.ofMillis(500)); + system.flush(); + } + + /** + * Text that must fit its box: the screens whose long or player-chosen text used to run past + * its panel, at GUI scale 2, 3 and 4 in a 1366x768 window (a Chromebook windowed and + * fullscreen). The game caps the scale at what leaves 320x240 units, so 4 there is 3 (455x256); + * narrower layouts are seen in smaller framebuffers at 3: 1280x720 (426x240) and 1024x768 + * (341x256), where the module menu, the screenshot gallery, the pause card and the menus' + * captions must still fit. Screenshots only; a person looks at them. + */ + private void fitScenario() throws Exception { + waitForTitle(); + takeControl(); + incari.framework.ModuleSystem system = onGameThread(incari.client.modules.IncariModules::system); + onGameThread( + () -> incari.client.online.IncariOnline.service().wardrobe().saveOutfit("My Practice Server Setup")); + for (int scale : new int[] {2, 3, 4}) { + String name = "fit-" + scale; + guiScale(scale); + onGameThread(() -> system.applyPreset("Modern PvP", java.util.Set.of("shieldtotem", "lowshield"))); + lookAt(menu(), "", name + "-modules-preset"); + onGameThread(() -> system.applyPreset("My Practice Server Setup", java.util.Set.of("minimap"))); + lookAt(menu(), "", name + "-modules-long-profile"); + onGameThread(() -> { + incari.client.modules.IncariModules.openProfiles(new TitleScreen()); + return null; + }); + sleep(Duration.ofSeconds(1)); + screenshot(name + "-profiles"); + lookAt(new incari.client.settings.IncariSettingsScreen(new TitleScreen()), "", name + "-settings"); + hoverLabel("Show others I use Incari"); + sleep(Duration.ofMillis(400)); + screenshot(name + "-settings-tooltip"); + lookAt( + new incari.client.eagler.PasswordScreen( + new TitleScreen(), + new ServerData("Smoke", "localhost", ServerData.Type.OTHER), + ServerAddress.parseString("localhost"), + new incari.client.eagler.EaglerAuth.Request( + "localhost", + incari.net.eagler.EaglerPassword.PLAINTEXT, + "Welcome back to the server. Log in with the password you registered with" + + " last time. If you forgot it, ask a staff member on Discord to reset" + + " it for you.")), + "", + name + "-password"); + lookAt(incari.client.cosmetics.WardrobeScreen.showing(null, null), "", name + "-wardrobe-outfits"); + lookAt( + incari.client.cosmetics.WardrobeScreen.showing(null, incari.online.Cosmetic.Slot.EMOTE), + "", + name + "-wardrobe-emotes"); + lookAt( + incari.client.cosmetics.WardrobeScreen.showing(null, incari.online.Cosmetic.Slot.NAMETAG), + "", + name + "-wardrobe-nametags"); + var constructor = Class.forName("incari.client.online.ForgotPasswordScreen") + .asSubclass(Screen.class) + .getDeclaredConstructor(Screen.class); + constructor.setAccessible(true); + Screen forgot = constructor.newInstance(new TitleScreen()); + onGameThread(() -> { + minecraft.gui.setScreen(forgot); + var status = Class.forName("incari.client.online.FormScreen") + .getDeclaredMethod("status", String.class, int.class); + status.setAccessible(true); + status.invoke( + forgot, + "Wrong username or recovery code. Check both and try again in a few minutes.", + incari.client.ui.Theme.NEGATIVE); + return null; + }); + sleep(Duration.ofSeconds(1)); + screenshot(name + "-forgot-password"); + } + + newSurvivalWorld(); + boolean loaded = waitUntil(Duration.ofMinutes(3), () -> inWorld() && player().tickCount > 60); + report.check("singleplayer world", loaded, loaded ? "" : stateDescription()); + if (!loaded) { + screenshot("fail-world"); + return; + } + onGameThread(() -> { + incari.framework.Module minimap = system.module("minimap"); + if (minimap != null) { + minimap.setEnabled(true); + } + return null; + }); + for (int scale : new int[] {2, 3, 4}) { + String name = "fit-" + scale; + guiScale(scale); + lookAt(incari.client.profile.ProfileScreen.from(new PauseScreen(true)), "", name + "-edit-profile"); + onGameThread(() -> { + minecraft.gui.setScreen(null); + return null; + }); + sleep(Duration.ofMillis(500)); + injector().key(16, 'm', true); + sleep(Duration.ofMillis(150)); + injector().key(16, 'm', false); + sleep(Duration.ofSeconds(2)); + screenshot(name + "-worldmap"); + onGameThread(() -> { + minecraft.gui.setScreen(null); + return null; + }); + } + + // A picture for the gallery, then the narrow windows. + injector().tap(59, 0x4000003B); + sleep(Duration.ofMillis(1500)); + for (int[] size : new int[][] {{1280, 720}, {1024, 768}}) { + if (!windowSize(size[0], size[1])) { + continue; + } + guiScale(3); + String name = + "fit-narrow-" + onGameThread(() -> minecraft.getWindow().getGuiScaledWidth()) + "x" + + onGameThread(() -> minecraft.getWindow().getGuiScaledHeight()); + lookAt(menu(), "", name + "-modules"); + lookAt(new incari.client.settings.IncariSettingsScreen(new TitleScreen()), "", name + "-settings"); + lookAt(new incari.client.recorder.RecorderScreen(null), "", name + "-recorder"); + onGameThread(() -> { + incari.client.modules.IncariModules.openSettings( + new TitleScreen(), java.util.Objects.requireNonNull(system.module("theme"))); + return null; + }); + sleep(Duration.ofSeconds(1)); + screenshot(name + "-theme"); + onGameThread(() -> { + system.game().askText("Import theme", "Paste a theme code (Ctrl+V), then press Done.", "", text -> {}); + return null; + }); + sleep(Duration.ofSeconds(1)); + screenshot(name + "-import"); + lookAt(new PauseScreen(true), "", name + "-pause"); + onGameThread(() -> { + minecraft.gui.setScreen(null); + system.game().openScreenshots(); + return null; + }); + sleep(Duration.ofSeconds(2)); + screenshot(name + "-gallery"); + // The first cell opens the viewer. + int scale = onGameThread(() -> minecraft.getWindow().getGuiScale()); + int guiWidth = onGameThread(() -> minecraft.getWindow().getGuiScaledWidth()); + int columns = Math.max(1, (guiWidth - 16) / (96 + 8)); + int left = (guiWidth - (columns * (96 + 8) - 8)) / 2; + float windowRatio = onGameThread(() -> minecraft.getWindow().getScreenWidth() + / (float) minecraft.getWindow().getWidth()); + injector().moveTo((left + 40) * scale * windowRatio, (40 + 25) * scale * windowRatio); + sleep(Duration.ofMillis(200)); + injector().mouseButton(1, true); + sleep(Duration.ofMillis(50)); + injector().mouseButton(1, false); + sleep(Duration.ofSeconds(1)); + screenshot(name + "-viewer"); + onGameThread(() -> { + minecraft.gui.setScreen(null); + return null; + }); + } + // Back to the window the run started with. + onGameThread(() -> minecraft.getWindow().platformWindow().setWindowed(64, 64, 1366, 768)); + sleep(Duration.ofMillis(500)); + } + + /** + * The GUI sizes players' windows give, each a framebuffer and a GUI scale: the smallest the + * game allows (320x240), a Chromebook's browser tab at the largest scale (683x325), and narrow, + * short and wide ones between. + */ + private static final int[][] LAYOUT_SIZES = { + {640, 480, 2}, {1280, 720, 3}, {1024, 768, 3}, {1366, 650, 2}, {1920, 600, 2}, {1920, 1080, 3}, + }; + + /** + * Every screen's layout judged, not looked at ({@link LayoutCheck}): Incari's screens and the + * game's that Incari changes, at each of {@link #LAYOUT_SIZES}, in Incari's font and in the + * game's pixel font (a theme's choice, and what's drawn if the page can't load Incari's). A + * widget off the screen or over another, or text past its box, fails, and the screen's picture + * is kept. Every problem is listed in {@code layout.txt}. + */ + private void layoutScenario() throws Exception { + waitForTitle(); + incari.framework.ModuleSystem system = onGameThread(incari.client.modules.IncariModules::system); + onGameThread( + () -> incari.client.online.IncariOnline.service().wardrobe().saveOutfit("My Practice Server Setup")); + java.util.Map> screens = new java.util.LinkedHashMap<>(); + screens.put("title", TitleScreen::new); + screens.put( + "multiplayer", + () -> new net.minecraft.client.gui.screens.multiplayer.JoinMultiplayerScreen(new TitleScreen())); + screens.put( + "edit-server", + () -> new net.minecraft.client.gui.screens.ManageServerScreen( + new TitleScreen(), + net.minecraft.network.chat.Component.literal("Edit Server Info"), + ok -> {}, + new ServerData("Test", "ws://127.0.0.1:8801", ServerData.Type.OTHER))); + screens.put( + "direct-connect", + () -> new net.minecraft.client.gui.screens.DirectJoinServerScreen( + new TitleScreen(), ok -> {}, new ServerData("", "", ServerData.Type.OTHER))); + screens.put( + "wispcraft", + () -> incari.client.net.WispServers.screen( + new TitleScreen(), new ServerData("Test", "127.0.0.1", ServerData.Type.OTHER), () -> {})); + screens.put("modules", () -> { + incari.client.modules.IncariModules.openMenu(new TitleScreen()); + return minecraft.gui.screen(); + }); + screens.put("profiles", () -> { + incari.client.modules.IncariModules.openProfiles(new TitleScreen()); + return minecraft.gui.screen(); + }); + screens.put("theme", () -> { + incari.client.modules.IncariModules.openSettings( + new TitleScreen(), java.util.Objects.requireNonNull(system.module("theme"))); + return minecraft.gui.screen(); + }); + screens.put("text-entry", () -> { + system.game().askText("Import theme", "Paste a theme code (Ctrl+V), then press Done.", "", text -> {}); + return minecraft.gui.screen(); + }); + screens.put("settings", () -> new incari.client.settings.IncariSettingsScreen(new TitleScreen())); + screens.put("recorder", () -> new incari.client.recorder.RecorderScreen(new TitleScreen())); + screens.put("edit-profile", () -> incari.client.profile.ProfileScreen.from(new TitleScreen())); + screens.put("microsoft-sign-in", () -> new incari.client.account.MicrosoftScreen(new TitleScreen())); + screens.put("wardrobe-outfits", () -> incari.client.cosmetics.WardrobeScreen.showing(new TitleScreen(), null)); + screens.put( + "wardrobe-emotes", + () -> incari.client.cosmetics.WardrobeScreen.showing( + new TitleScreen(), incari.online.Cosmetic.Slot.EMOTE)); + screens.put( + "wardrobe-nametags", + () -> incari.client.cosmetics.WardrobeScreen.showing( + new TitleScreen(), incari.online.Cosmetic.Slot.NAMETAG)); + screens.put("credits", () -> new incari.client.credits.CreditsScreen(new TitleScreen())); + screens.put("chat-menu", () -> new incari.client.online.ChatMenuScreen(new TitleScreen())); + screens.put("account", () -> new incari.client.online.AccountScreen(new TitleScreen())); + for (String form : new String[] { + "SignInScreen", + "CreateAccountScreen", + "ForgotPasswordScreen", + "ChangePasswordScreen", + "BlockedPlayersScreen" + }) { + screens.put(form, () -> { + var constructor = Class.forName("incari.client.online." + form) + .asSubclass(Screen.class) + .getDeclaredConstructor(Screen.class); + constructor.setAccessible(true); + return constructor.newInstance(new TitleScreen()); + }); + } + screens.put("release-notes", () -> { + var constructor = Class.forName("incari.client.online.ReleaseNotesScreen") + .asSubclass(Screen.class) + .getDeclaredConstructor(Screen.class, String.class, java.util.List.class); + constructor.setAccessible(true); + return constructor.newInstance( + new TitleScreen(), + "0.1.7", + java.util.List.of( + "Buttons and text fit their boxes on small screens and at browser zoom.", + "The default GUI scale is one step smaller, so menus leave room for the game.")); + }); + screens.put("relay", () -> new incari.client.relay.RelayScreen(new TitleScreen())); + screens.put( + "relay-connect", + () -> new incari.client.relay.RelayConnectScreen(new TitleScreen(), "ws://127.0.0.1:9", "ABCD")); + screens.put( + "password", + () -> new incari.client.eagler.PasswordScreen( + new TitleScreen(), + new ServerData("Smoke", "localhost", ServerData.Type.OTHER), + ServerAddress.parseString("localhost"), + new incari.client.eagler.EaglerAuth.Request( + "localhost", + incari.net.eagler.EaglerPassword.PLAINTEXT, + "Welcome back to the server. Log in with the password you registered with" + + " last time. If you forgot it, ask a staff member on Discord to reset" + + " it for you."))); + + StringBuilder all = new StringBuilder(); + String[][] fonts = {{"smooth", "red_hat_display.ttf"}, {"pixel", null}}; + for (String[] font : fonts) { + onGameThread(() -> { + incari.client.ui.SmoothFont.useFont(font[1], 1.0F); + return null; + }); + sleep(Duration.ofSeconds(2)); + for (int[] size : LAYOUT_SIZES) { + if (!windowSize(size[0], size[1])) { + continue; + } + guiScale(size[2]); + String at = onGameThread(() -> minecraft.getWindow().getGuiScaledWidth() + "x" + + minecraft.getWindow().getGuiScaledHeight()); + for (var entry : screens.entrySet()) { + String name = entry.getKey(); + java.util.List problems; + try { + onGameThread(() -> { + Screen screen = entry.getValue().call(); + if (!java.util.Objects.equals(minecraft.gui.screen(), screen)) { + minecraft.gui.setScreen(screen); + } + return null; + }); + // A frame or two for what a screen lays out after it opens (a caption, a fetch). + sleep(Duration.ofMillis(300)); + problems = onGameThread(() -> { + Screen shown = minecraft.gui.screen(); + return shown == null + ? java.util.List.of("no screen open") + : LayoutCheck.problems(minecraft, shown); + }); + } catch (RuntimeException e) { + problems = java.util.List.of("couldn't open: " + e); + } + String label = name + " at " + at + " (" + font[0] + ")"; + report.check( + "layout " + label, + problems.isEmpty(), + problems.isEmpty() + ? "" + : problems.get(0) + + (problems.size() > 1 ? " (+" + (problems.size() - 1) + " more)" : "")); + if (!problems.isEmpty()) { + screenshot("layout-" + name + "-" + at + "-" + font[0]); + all.append(label).append('\n'); + problems.forEach( + problem -> all.append(" ").append(problem).append('\n')); + } + } + } + } + onGameThread(() -> { + incari.client.ui.SmoothFont.useFont("red_hat_display.ttf", 1.0F); + minecraft.gui.setScreen(new TitleScreen()); + return null; + }); + Files.createDirectories(directory); + Files.writeString(directory.resolve("layout.txt"), all.isEmpty() ? "No problems.\n" : all.toString()); + } + + /** + * Sizes the window so its framebuffer is {@code width} by {@code height} pixels (what the GUI + * scale divides: on a display scaled up, the window's own size is smaller), and says whether it + * took that size. + */ + private boolean windowSize(int width, int height) { + float ratio = onGameThread(() -> + minecraft.getWindow().getWidth() / (float) minecraft.getWindow().getScreenWidth()); + onGameThread(() -> minecraft + .getWindow() + .platformWindow() + .setWindowed(64, 64, Math.round(width / ratio), Math.round(height / ratio))); + boolean sized = waitUntil( + Duration.ofSeconds(5), + () -> onGameThread(() -> Math.abs(minecraft.getWindow().getWidth() - width) <= 2 + && Math.abs(minecraft.getWindow().getHeight() - height) <= 2)); + report.check( + "framebuffer " + width + "x" + height, + sized, + onGameThread(() -> minecraft.getWindow().getWidth() + "x" + + minecraft.getWindow().getHeight())); + sleep(Duration.ofMillis(500)); + return sized; + } + + private Screen menu() { + return onGameThread(() -> { + incari.client.modules.IncariModules.openMenu(new TitleScreen()); + return minecraft.gui.screen(); + }); + } + + private void guiScale(int scale) { + onGameThread(() -> { + minecraft.options.guiScale().set(scale); + minecraft.resizeGui(); + return null; + }); + sleep(Duration.ofMillis(300)); + } + + /** The pointer over the settings row labelled {@code label}, at the label's start. */ + private void hoverLabel(String label) { + float[] at = onGameThread(() -> { + Screen screen = minecraft.gui.screen(); + if (screen == null) { + return null; + } + for (var child : screen.children()) { + if (child instanceof incari.client.ui.ControlList list) { + for (var row : list.children()) { + // The label is the row's own text, not a widget: read it from the row. + java.lang.reflect.Field field; + try { + field = row.getClass().getDeclaredField("label"); + } catch (NoSuchFieldException e) { + continue; + } + field.setAccessible(true); + if (field.get(row) instanceof net.minecraft.network.chat.Component text + && text.getString().equals(label)) { + var window = minecraft.getWindow(); + float toWindow = (float) window.getScreenWidth() / window.getGuiScaledWidth(); + return new float[] {(row.getContentX() + 6) * toWindow, row.getContentYMiddle() * toWindow}; + } + } + } + } + return null; + }); + report.check("settings row " + label, at != null, ""); + if (at != null) { + injector().moveTo(at[0], at[1]); + } + } + + /** + * Cosmetics (ADR 0061): worn on the title screen's player, the Wardrobe's tabs, then in a world + * from in front and behind, an emote turning the camera and turning it back, the emote wheel, + * and the pause menu's and module menu's ways in. Others' cosmetics come from the online service + * and are checked by {@code :online}'s tests and smokeOnline. + */ + private void cosmeticsScenario() throws Exception { + waitForTitle(); + incari.online.Wardrobe wardrobe = + onGameThread(() -> incari.client.online.IncariOnline.service().wardrobe()); + onGameThread(() -> { + wardrobe.wear(incari.online.Loadout.EMPTY); + wardrobe.wear(cosmetic("cape.aurora")); + wardrobe.wear(cosmetic("hat.crown")); + wardrobe.wear(cosmetic("nametag.aurora")); + minecraft.gui.setScreen(new TitleScreen()); + return null; + }); + sleep(Duration.ofSeconds(3)); + screenshot("cosmetics-title"); + boolean titleButton = onGameThread(() -> hasButton("Cosmetics")); + report.check("the title card has Cosmetics", titleButton, screenName()); + + for (incari.online.Cosmetic.Slot slot : incari.online.Cosmetic.Slot.values()) { + onGameThread(() -> { + minecraft.gui.setScreen(incari.client.cosmetics.WardrobeScreen.showing(new TitleScreen(), slot)); + return null; + }); + sleep(Duration.ofSeconds(2)); + screenshot("cosmetics-wardrobe-" + slot.prefix()); + } + onGameThread(() -> { + wardrobe.saveOutfit("Smoke"); + minecraft.gui.setScreen(incari.client.cosmetics.WardrobeScreen.showing(new TitleScreen(), null)); + return null; + }); + sleep(Duration.ofSeconds(2)); + screenshot("cosmetics-wardrobe-outfits"); + report.check( + "an outfit is saved", + onGameThread( + () -> wardrobe.outfits().stream().anyMatch(o -> o.name().equals("Smoke"))), + ""); + + newSurvivalWorld(); + boolean loaded = waitUntil(Duration.ofMinutes(3), () -> inWorld() && player().tickCount > 60); + report.check("singleplayer world", loaded, loaded ? "" : stateDescription()); + if (!loaded) { + screenshot("fail-world"); + return; + } + takeControl(); + serverCommands("time set noon", "weather clear", "execute as @p at @s run tp @s ~ ~ ~ 0 10"); + sleep(Duration.ofSeconds(2)); + onGameThread(() -> { + minecraft.options.setCameraType(net.minecraft.client.CameraType.THIRD_PERSON_FRONT); + return null; + }); + sleep(Duration.ofSeconds(2)); + screenshot("cosmetics-world-front"); + onGameThread(() -> { + wardrobe.wear(cosmetic("back.angel_wings")); + minecraft.options.setCameraType(net.minecraft.client.CameraType.THIRD_PERSON_BACK); + return null; + }); + sleep(Duration.ofSeconds(2)); + screenshot("cosmetics-world-back"); + for (String id : new String[] {"back.frost_wings", "back.bat_wings", "back.backpack"}) { + onGameThread(() -> { + wardrobe.wear(cosmetic(id)); + return null; + }); + sleep(Duration.ofSeconds(1)); + screenshot("cosmetics-world-" + id.replace('.', '-')); + } + onGameThread(() -> { + wardrobe.wear(cosmetic("back.angel_wings")); + minecraft.options.setCameraType(net.minecraft.client.CameraType.THIRD_PERSON_FRONT); + return null; + }); + for (String id : new String[] {"hat.halo", "hat.top_hat", "hat.beanie", "hat.horns", "hat.cat_ears"}) { + onGameThread(() -> { + wardrobe.wear(cosmetic(id)); + return null; + }); + sleep(Duration.ofSeconds(1)); + screenshot("cosmetics-world-" + id.replace('.', '-')); + } + boolean worn = onGameThread(() -> { + var state = new net.minecraft.client.renderer.entity.state.AvatarRenderState(); + incari.client.cosmetics.Cosmetics.extract(player(), state); + return state.incariWorn != incari.client.cosmetics.Worn.NONE; + }); + report.check("the player's render state carries what's worn", worn, ""); + + // An emote: the camera turns to face the player, and back once it's over. + onGameThread(() -> { + minecraft.options.setCameraType(net.minecraft.client.CameraType.FIRST_PERSON); + return null; + }); + boolean played = onGameThread(() -> incari.client.cosmetics.Cosmetics.playEmote(cosmetic("emote.wave"))); + sleep(Duration.ofMillis(1200)); + screenshot("cosmetics-emote-wave"); + boolean turned = onGameThread( + () -> minecraft.options.getCameraType() == net.minecraft.client.CameraType.THIRD_PERSON_FRONT); + boolean back = waitUntil( + Duration.ofSeconds(6), + () -> minecraft.options.getCameraType() == net.minecraft.client.CameraType.FIRST_PERSON); + report.check( + "an emote plays and the camera comes back", + played && turned && back, + "played " + played + ", turned " + turned + ", back " + back); + onGameThread(() -> incari.client.cosmetics.Cosmetics.playEmote(cosmetic("emote.cheer"))); + sleep(Duration.ofMillis(300)); + holdKey(26, 'w', Duration.ofMillis(600)); + boolean cut = waitUntil( + Duration.ofSeconds(2), + () -> minecraft.options.getCameraType() == net.minecraft.client.CameraType.FIRST_PERSON); + report.check("moving ends an emote", cut, ""); + + // The emote wheel, held open by G. + injector().key(10, 'g', true); + boolean wheel = waitUntil( + Duration.ofSeconds(3), + () -> minecraft.gui.screen() instanceof incari.client.cosmetics.EmoteWheelScreen); + sleep(Duration.ofMillis(500)); + screenshot("cosmetics-emote-wheel"); + injector().key(10, 'g', false); + boolean closed = waitUntil(Duration.ofSeconds(3), () -> minecraft.gui.screen() == null); + report.check("the emote wheel opens on G and closes on letting go", wheel && closed, screenName()); + // A quick tap, let go before the wheel opens: it waits for a click, and G again closes it. + injector().key(10, 'g', true); + injector().key(10, 'g', false); + boolean tapped = waitUntil( + Duration.ofSeconds(3), + () -> minecraft.gui.screen() instanceof incari.client.cosmetics.EmoteWheelScreen); + sleep(Duration.ofMillis(500)); + boolean stays = minecraft.gui.screen() instanceof incari.client.cosmetics.EmoteWheelScreen; + injector().key(10, 'g', true); + injector().key(10, 'g', false); + boolean tapClosed = waitUntil(Duration.ofSeconds(3), () -> minecraft.gui.screen() == null); + report.check( + "a tap of G leaves the emote wheel open for a click, and G again closes it", + tapped && stays && tapClosed, + "opened " + tapped + ", stayed " + stays + ", closed " + tapClosed); + + // A trail, walking. + onGameThread(() -> { + wardrobe.wear(cosmetic("trail.hearts")); + minecraft.options.setCameraType(net.minecraft.client.CameraType.THIRD_PERSON_BACK); + return null; + }); + injector().key(26, 'w', true); + sleep(Duration.ofMillis(1500)); + screenshot("cosmetics-trail"); + injector().key(26, 'w', false); + + // The personal effects: the outline, the glint, the hurt tint and a kill's burst. + incari.framework.ModuleSystem system = onGameThread(incari.client.modules.IncariModules::system); + incari.framework.Module outline = module(system, "blockoutline"); + incari.framework.Module hitColor = module(system, "hitcolor"); + incari.framework.Module glint = module(system, "glintcolor"); + incari.framework.Module effects = module(system, "hiteffects"); + onGameThread(() -> { + wardrobe.takeOff(incari.online.Cosmetic.Slot.TRAIL); + ((incari.framework.setting.BooleanSetting) + java.util.Objects.requireNonNull(outline.settings().get("fill"))) + .set(true); + outline.setEnabled(true); + hitColor.setEnabled(true); + glint.setEnabled(true); + effects.setEnabled(true); + minecraft.options.setCameraType(net.minecraft.client.CameraType.FIRST_PERSON); + return null; + }); + // A clear, flat patch to stand on: the trail walked somewhere. + serverCommands( + "execute as @p at @s run fill ~-4 ~-1 ~-4 ~4 ~-1 ~4 stone", + "execute as @p at @s run fill ~-4 ~ ~-4 ~4 ~4 ~4 air", + "item replace entity @p weapon.mainhand with diamond_sword[enchantments={sharpness:5}]", + "execute as @p at @s run tp @s ~ ~ ~ 0 60"); + sleep(Duration.ofSeconds(2)); + screenshot("cosmetics-outline-glint"); + // Painted, it's Incari's own reloadable texture in the game's slot, not the game's SimpleTexture. + boolean tinted = onGameThread(() -> minecraft + .getTextureManager() + .getTexture(net.minecraft.client.renderer.feature.ItemFeatureRenderer.ENCHANTED_GLINT_ITEM) + .getClass() + .getSimpleName() + .equals("TintedGlint")); + report.check("Enchant Glint paints the glint", tinted, ""); + java.util.concurrent.atomic.AtomicInteger kills = new java.util.concurrent.atomic.AtomicInteger(); + incari.framework.event.KillListener killProbe = kills::incrementAndGet; + onGameThread(() -> { + system.events().add(incari.framework.event.Events.KILL, this, killProbe); + return null; + }); + serverCommands( + "execute as @p at @s run tp @s ~ ~ ~ 0 30", + "execute as @p at @s run summon pig ~ ~ ~2.2 {NoAI:1b,Silent:1b}"); + sleep(Duration.ofSeconds(1)); + injector().mouseButton(1, true); + sleep(Duration.ofMillis(50)); + injector().mouseButton(1, false); + sleep(Duration.ofMillis(150)); + screenshot("cosmetics-hit-color"); + serverCommands("effect give @p strength 30 10 true"); + sleep(Duration.ofMillis(800)); + injector().mouseButton(1, true); + sleep(Duration.ofMillis(50)); + injector().mouseButton(1, false); + boolean killed = waitUntil(Duration.ofSeconds(3), () -> kills.get() > 0); + screenshot("cosmetics-kill-effect"); + report.check("a kill fires the kill event", killed, "kills " + kills.get()); + onGameThread(() -> { + system.events().remove(incari.framework.event.Events.KILL, killProbe); + outline.setEnabled(false); + hitColor.setEnabled(false); + glint.setEnabled(false); + effects.setEnabled(false); + return null; + }); + boolean restored = onGameThread(() -> minecraft + .getTextureManager() + .getTexture(net.minecraft.client.renderer.feature.ItemFeatureRenderer.ENCHANTED_GLINT_ITEM) + .getClass() + == net.minecraft.client.renderer.texture.SimpleTexture.class); + report.check("the game's glint comes back", restored, ""); + + // The ways in from a world: the pause menu and the module menu. + onGameThread(() -> { + minecraft.gui.setScreen(new net.minecraft.client.gui.screens.PauseScreen(true)); + return null; + }); + sleep(Duration.ofSeconds(1)); + screenshot("cosmetics-pause"); + // ADR 0062: the pause menu's one Incari button opens Incari Settings, where the Wardrobe is a tile. + report.check( + "the pause menu has Incari Settings", onGameThread(() -> hasButton("Incari Settings")), screenName()); + onGameThread(() -> { + minecraft.gui.setScreen(new incari.client.settings.IncariSettingsScreen(minecraft.gui.screen())); + return null; + }); + sleep(Duration.ofSeconds(1)); + screenshot("cosmetics-incari-settings"); + report.check("Incari Settings has Cosmetics", onGameThread(() -> hasButton("Cosmetics")), screenName()); + onGameThread(() -> { + incari.client.modules.IncariModules.openMenu(null); + return null; + }); + sleep(Duration.ofSeconds(1)); + screenshot("cosmetics-module-menu"); + report.check("the module menu has Cosmetics", onGameThread(() -> hasButton("Cosmetics")), screenName()); + + // Others' cosmetics off is kept. + onGameThread(() -> { + wardrobe.setShowOthers(false); + minecraft.gui.setScreen( + incari.client.cosmetics.WardrobeScreen.showing(null, incari.online.Cosmetic.Slot.CAPE)); + return null; + }); + sleep(Duration.ofSeconds(1)); + screenshot("cosmetics-others-off"); + onGameThread(() -> { + wardrobe.setShowOthers(true); + minecraft.gui.setScreen(null); + return null; + }); + } + + private static incari.online.Cosmetic cosmetic(String id) { + return java.util.Objects.requireNonNull(incari.online.Catalog.byId(id), id); + } + + /** Whether the shown screen has a widget saying {@code label}. */ + private boolean hasButton(String label) { + return minecraft.gui.screen() != null && hasButton(minecraft.gui.screen(), label); + } + + /** Searches lists' rows too: Incari Settings' tiles sit in its list, not on the screen. */ + private static boolean hasButton( + net.minecraft.client.gui.components.events.ContainerEventHandler parent, String label) { + for (var child : parent.children()) { + if (child instanceof net.minecraft.client.gui.components.AbstractWidget widget + && widget.getMessage().getString().equals(label)) { + return true; + } + if (child instanceof net.minecraft.client.gui.components.events.ContainerEventHandler container + && hasButton(container, label)) { + return true; + } + } + return false; + } + + /** + * ADR 0054 and 0062: Shulker Tooltips over a filled box in the inventory, the screenshot gallery + * (F2 twice, the event, the gallery and the viewer), Incari Settings from the pause menu, and + * the Theme Editor's presets and fonts applied and Frost given back. + */ + private void screenModulesScenario() throws Exception { + waitForTitle(); + incari.framework.ModuleSystem system = onGameThread(incari.client.modules.IncariModules::system); + incari.framework.Module theme = module(system, "theme"); + incari.framework.Module shulker = module(system, "shulkertooltips"); + onGameThread(() -> { + minecraft.gui.setScreen(new net.minecraft.client.gui.screens.TitleScreen()); + return null; + }); + sleep(Duration.ofSeconds(2)); + screenshot("screens-title"); + + newSurvivalWorld(); + boolean loaded = waitUntil(Duration.ofMinutes(3), () -> inWorld() && player().tickCount > 60); + report.check("singleplayer world", loaded, loaded ? "" : stateDescription()); + if (!loaded) { + screenshot("fail-world"); + return; + } + takeControl(); + serverCommands( + "time set noon", + "item replace entity @p hotbar.0 with purple_shulker_box[container=[" + + "{slot:0,item:{id:\"diamond\",count:12}},{slot:1,item:{id:\"golden_apple\",count:3}}," + + "{slot:4,item:{id:\"diamond_sword\",count:1}},{slot:13,item:{id:\"ender_pearl\",count:16}}," + + "{slot:26,item:{id:\"totem_of_undying\",count:1}}]]"); + sleep(Duration.ofSeconds(1)); + + // Shulker Tooltips: the box's tooltip carries the grid while on, and not while off. + boolean gameTooltip = onGameThread( + () -> player().getInventory().getItem(0).getTooltipImage().isEmpty()); + onGameThread(() -> { + shulker.setEnabled(true); + return null; + }); + boolean preview = onGameThread( + () -> player().getInventory().getItem(0).getTooltipImage().orElse(null) + instanceof incari.client.modules.ModuleTooltips.Preview); + report.check( + "shulker tooltips show the grid", + gameTooltip && preview, + "game none " + gameTooltip + ", preview " + preview); + injector().tap(8, 'e'); + boolean open = waitUntil(Duration.ofSeconds(3), () -> minecraft.gui.screen() instanceof InventoryScreen); + if (open) { + int scale = onGameThread(() -> minecraft.getWindow().getGuiScale()); + int guiWidth = onGameThread(() -> minecraft.getWindow().getGuiScaledWidth()); + int guiHeight = onGameThread(() -> minecraft.getWindow().getGuiScaledHeight()); + // Window units, which a HiDPI window's framebuffer is larger than. + float ratio = onGameThread(() -> minecraft.getWindow().getScreenWidth() + / (float) minecraft.getWindow().getWidth()); + float x = ((guiWidth - 176) / 2 + 8 + 8) * scale * ratio; + float y = ((guiHeight - 166) / 2 + 142 + 8) * scale * ratio; + injector().moveTo(x, y); + sleep(Duration.ofMillis(300)); + injector().moveTo(x + 1, y); + sleep(Duration.ofMillis(500)); + String mouse = onGameThread(() -> minecraft.mouseHandler.xpos() + "," + minecraft.mouseHandler.ypos() + + " grabbed " + minecraft.mouseHandler.isMouseGrabbed() + " window " + + minecraft.getWindow().getScreenWidth() + "x" + + minecraft.getWindow().getScreenHeight()); + report.check("pointer over the box", true, "at " + x + "," + y + ", game sees " + mouse); + screenshot("screens-shulker-tooltip"); + injector().tap(41, 0x1B); + waitUntil(Duration.ofSeconds(3), () -> minecraft.gui.screen() == null); + } + + // Screenshot Manager: F2 twice, heard by modules, then the gallery. + java.util.List taken = new java.util.concurrent.CopyOnWriteArrayList<>(); + incari.framework.event.ScreenshotListener probe = taken::add; + onGameThread(() -> { + system.events().add(incari.framework.event.Events.SCREENSHOT, this, probe); + return null; + }); + injector().tap(59, 0x4000003B); + sleep(Duration.ofMillis(1200)); + serverCommands("execute as @p at @s run tp @s ~ ~ ~ 90 0"); + sleep(Duration.ofMillis(800)); + injector().tap(59, 0x4000003B); + boolean heard = waitUntil(Duration.ofSeconds(5), () -> taken.size() >= 2); + report.check("screenshots heard by modules", heard, taken.toString()); + onGameThread(() -> { + system.events().remove(incari.framework.event.Events.SCREENSHOT, probe); + system.game().openScreenshots(); + return null; + }); + sleep(Duration.ofSeconds(2)); + screenshot("screens-gallery"); + report.check( + "the gallery opens", + onGameThread(() -> minecraft.gui.screen() != null + && minecraft.gui.screen().getTitle().getString().equals("Screenshots")), + screenName()); + // The newest first: the first cell opens the viewer. + int scale = onGameThread(() -> minecraft.getWindow().getGuiScale()); + int guiWidth = onGameThread(() -> minecraft.getWindow().getGuiScaledWidth()); + int columns = Math.max(1, (guiWidth - 16) / (96 + 8)); + int left = (guiWidth - (columns * (96 + 8) - 8)) / 2; + float windowRatio = onGameThread(() -> minecraft.getWindow().getScreenWidth() + / (float) minecraft.getWindow().getWidth()); + injector().moveTo((left + 40) * scale * windowRatio, (40 + 25) * scale * windowRatio); + sleep(Duration.ofMillis(200)); + injector().mouseButton(1, true); + sleep(Duration.ofMillis(50)); + injector().mouseButton(1, false); + sleep(Duration.ofSeconds(1)); + screenshot("screens-viewer"); + onGameThread(() -> { + minecraft.gui.setScreen(new net.minecraft.client.gui.screens.PauseScreen(true)); + return null; + }); + sleep(Duration.ofSeconds(1)); + screenshot("screens-pause"); + boolean pauseButton = onGameThread(() -> minecraft.gui.screen() != null + && minecraft.gui.screen().children().stream() + .anyMatch(child -> child instanceof net.minecraft.client.gui.components.AbstractWidget widget + && widget.getMessage().getString().equals("Incari Settings"))); + report.check("pause menu has Incari Settings", pauseButton, ""); + onGameThread(() -> { + minecraft.gui.setScreen(new incari.client.settings.IncariSettingsScreen(minecraft.gui.screen())); + return null; + }); + sleep(Duration.ofSeconds(1)); + screenshot("screens-incari-settings"); + + // Theme Editor: always on; presets and fonts live, then Frost back. + // Frost's accent: an earlier run's profile may start the theme elsewhere. + int frostAccent = 0xFFA9DCFF; + report.check("the theme editor is always on", onGameThread(theme::isEnabled), ""); + choose(theme, "preset", "ember"); + sleep(Duration.ofMillis(500)); + screenshot("screens-theme-ember-pause"); + int emberAccent = onGameThread(() -> incari.client.ui.Theme.ACCENT); + choose(theme, "preset", "mint"); + onGameThread(() -> { + incari.client.modules.IncariModules.openMenu(null); + return null; + }); + sleep(Duration.ofSeconds(1)); + screenshot("screens-theme-mint-menu"); + onGameThread(() -> { + minecraft.gui.setScreen(null); + return null; + }); + sleep(Duration.ofMillis(500)); + screenshot("screens-theme-mint-hud"); + int mintAccent = onGameThread(() -> incari.client.ui.Theme.ACCENT); + for (String font : new String[] {"inter", "minecraft", "jetbrains_mono"}) { + choose(theme, "font", font); + onGameThread(() -> { + minecraft.gui.setScreen(new incari.client.settings.IncariSettingsScreen(null)); + return null; + }); + sleep(Duration.ofSeconds(2)); + screenshot("screens-font-" + font); + } + choose(theme, "font", "red_hat_display"); + choose(theme, "preset", "frost"); + sleep(Duration.ofMillis(500)); + int after = onGameThread(() -> incari.client.ui.Theme.ACCENT); + report.check( + "themes apply and Frost comes back", + emberAccent == 0xFFFFB067 && mintAccent == 0xFF7FE8C3 && after == frostAccent, + Integer.toHexString(emberAccent) + " " + Integer.toHexString(mintAccent) + " " + + Integer.toHexString(after)); + onGameThread(() -> { + shulker.setEnabled(false); + return null; + }); + sleep(Duration.ofMillis(500)); + system.flush(); + } + + /** Sets {@code module}'s choice {@code id} to the choice saved as {@code key}. */ + private void choose(incari.framework.Module module, String id, String key) { + incari.framework.setting.Setting setting = module.settings().get(id); + if (!(setting instanceof incari.framework.setting.ChoiceSetting choice)) { + throw new IllegalStateException(module.id() + " has no choice " + id); + } + onGameThread(() -> { + chooseKey(choice, key); + return null; + }); + } + + private static > void chooseKey(incari.framework.setting.ChoiceSetting setting, String key) { + E value = setting.fromKey(key); + if (value == null) { + throw new IllegalStateException(setting.id() + " has no choice " + key); + } + setting.set(value); + } + + private incari.framework.Module module(incari.framework.ModuleSystem system, String id) { + incari.framework.Module module = system.module(id); + if (module == null) { + throw new IllegalStateException("No module " + id); + } + return module; + } + + /** + * ADR 0051: the minimap and waypoints in a world. Four waypoints round the player (one ahead, + * one ahead and to the left, one far beyond the render distance, one behind) and one in the + * Nether; screenshots of the map round and turning, square and north up, zoomed, the list, the + * editor and the HUD editor; a death leaves a waypoint; the world's waypoints are saved. + */ + private void waypointsScenario() throws Exception { + waitForTitle(); + newSurvivalWorld(); + boolean loaded = waitUntil(Duration.ofMinutes(3), () -> inWorld() && player().tickCount > 60); + report.check("singleplayer world", loaded, loaded ? "" : stateDescription()); + if (!loaded) { + screenshot("fail-world"); + return; + } + takeControl(); + serverCommands("time set noon", "weather clear"); + incari.framework.ModuleSystem system = onGameThread(incari.client.modules.IncariModules::system); + incari.framework.Module minimap = system.module("minimap"); + incari.framework.Module waypointsModule = system.module("waypoints"); + report.check("both modules", minimap != null && waypointsModule != null, ""); + if (minimap == null || waypointsModule == null) { + return; + } + incari.framework.waypoint.Waypoints waypoints = system.waypoints(); + report.check( + "the world's waypoints are open", + onGameThread( + () -> waypoints.world() != null && waypoints.world().startsWith("world/")), + String.valueOf(onGameThread(waypoints::world))); + BlockPos at = onGameThread(() -> player().blockPosition()); + String overworld = incari.framework.game.PlayerView.OVERWORLD; + onGameThread(() -> { + waypoints.add(new incari.framework.waypoint.Waypoint( + "Base", + at.getX() + 4, + at.getY(), + at.getZ() - 28, + overworld, + 0x5B8CFF, + incari.framework.hud.Shape.STAR)); + waypoints.add(new incari.framework.waypoint.Waypoint( + "Mine", + at.getX() - 40, + at.getY() - 6, + at.getZ() - 55, + overworld, + 0xFF9F43, + incari.framework.hud.Shape.DIAMOND)); + waypoints.add(new incari.framework.waypoint.Waypoint( + "Far tower", + at.getX() + 60, + at.getY() + 20, + at.getZ() - 600, + overworld, + 0x8BE04E, + incari.framework.hud.Shape.TRIANGLE)); + waypoints.add(new incari.framework.waypoint.Waypoint( + "Home", + at.getX() - 6, + at.getY(), + at.getZ() + 30, + overworld, + 0xF06FD8, + incari.framework.hud.Shape.HEART)); + waypoints.add(new incari.framework.waypoint.Waypoint( + "Portal", + 10, + 70, + 10, + incari.framework.game.PlayerView.NETHER, + 0x9D7BFF, + incari.framework.hud.Shape.HEXAGON)); + minimap.setEnabled(true); + waypointsModule.setEnabled(true); + player().setYRot(180.0F); // north + player().setXRot(-8.0F); + return null; + }); + sleep(Duration.ofSeconds(4)); + screenshot("waypoints-north"); + + onGameThread(() -> { + player().setYRot(270.0F); // east + return null; + }); + sleep(Duration.ofSeconds(1)); + screenshot("waypoints-east"); + + // Square, north up, zoomed in, and zoomed all the way out. + incari.framework.setting.Setting shape = minimap.settings().get("shape"); + incari.framework.setting.Setting turn = minimap.settings().get("turn"); + incari.framework.setting.Setting zoom = minimap.settings().get("zoom"); + onGameThread(() -> { + ((incari.framework.setting.ChoiceSetting) java.util.Objects.requireNonNull(shape)).reset(); + next((incari.framework.setting.ChoiceSetting) shape); + ((incari.framework.setting.BooleanSetting) java.util.Objects.requireNonNull(turn)).set(false); + ((incari.framework.setting.IntSetting) java.util.Objects.requireNonNull(zoom)).set(6); + return null; + }); + sleep(Duration.ofSeconds(1)); + screenshot("waypoints-square-north-up-zoomed-in"); + onGameThread(() -> { + ((incari.framework.setting.IntSetting) java.util.Objects.requireNonNull(zoom)).set(1); + return null; + }); + sleep(Duration.ofSeconds(3)); + screenshot("waypoints-square-zoomed-out"); + onGameThread(() -> { + minimap.settings().resetAll(); + minimap.hudElements().get(0).scale().set(1.5F); + return null; + }); + sleep(Duration.ofSeconds(1)); + screenshot("waypoints-round-1.5x"); + + onGameThread(() -> { + system.game().openWaypoints(); + return null; + }); + sleep(Duration.ofSeconds(1)); + screenshot("waypoints-list"); + onGameThread(() -> { + incari.framework.waypoint.Waypoint base = waypoints.all().get(0); + system.game().editWaypoint(base, false); + return null; + }); + sleep(Duration.ofSeconds(1)); + screenshot("waypoints-edit"); + onGameThread(() -> { + minecraft.gui.setScreen(null); + return null; + }); + // The New waypoint key: the editor, on a new waypoint where the player stands. + injector().key(17, 'n', true); + sleep(Duration.ofMillis(150)); + injector().key(17, 'n', false); + boolean editor = waitUntil( + Duration.ofSeconds(3), + () -> minecraft.gui.screen() != null + && minecraft.gui.screen().getClass().getSimpleName().equals("WaypointEditScreen")); + report.check( + "the new waypoint key opens the editor", + editor, + String.valueOf(onGameThread(() -> minecraft.gui.screen() == null + ? "no screen" + : minecraft.gui.screen().getClass().getSimpleName()))); + sleep(Duration.ofMillis(500)); + screenshot("waypoints-new"); + onGameThread(() -> { + minecraft.gui.setScreen(null); + return null; + }); + + onGameThread(() -> { + incari.client.modules.IncariModules.openHudEditor(null); + return null; + }); + sleep(Duration.ofSeconds(1)); + screenshot("waypoints-hudeditor"); + onGameThread(() -> { + minecraft.gui.setScreen(null); + minimap.hudElements().get(0).resetPlacement(); + return null; + }); + + // A death leaves a waypoint where it happened. + int before = onGameThread(() -> waypoints.all().size()); + serverCommands("kill @p"); + boolean marked = waitUntil(Duration.ofSeconds(5), () -> waypoints.death() != null); + report.check( + "a death is marked", + marked && onGameThread(() -> waypoints.all().size()) == before + 1, + ""); + onGameThread(() -> { + player().respawn(); + return null; + }); + waitUntil( + Duration.ofSeconds(10), () -> inWorld() && !player().isDeadOrDying() && minecraft.gui.screen() == null); + sleep(Duration.ofSeconds(2)); + onGameThread(() -> { + player().setYRot(180.0F); + player().setXRot(-8.0F); + return null; + }); + sleep(Duration.ofSeconds(1)); + screenshot("waypoints-after-death"); + + onGameThread(() -> { + system.flush(); + return null; + }); + java.nio.file.Path folder = minecraft.gameDirectory.toPath().resolve("incari/modules/waypoints"); + String world = String.valueOf(onGameThread(waypoints::world)).replace('/', '_'); + long files; + try (var list = java.nio.file.Files.list(folder)) { + files = list.filter(file -> file.getFileName().toString().startsWith(world)) + .count(); + } catch (java.io.IOException e) { + files = 0; + } + report.check("the world's waypoints are saved", files == 1, folder + ": " + files + " files for " + world); + + // On green land, for the map's colors: the nearest plains, found as the locate command does. + BlockPos plains = onGameThread(() -> { + IntegratedServer server = minecraft.getSingleplayerServer(); + if (server == null) { + return null; + } + return server.submit(() -> { + var found = server.overworld() + .findClosestBiome3d( + biome -> biome.is(net.minecraft.world.level.biome.Biomes.PLAINS), + at, + 6400, + 32, + 64); + return found == null ? null : found.getFirst(); + }) + .get(30, TimeUnit.SECONDS); + }); + if (plains != null) { + serverCommands("gamemode creative @p", "tp @p " + plains.getX() + " 140 " + plains.getZ() + " 0 50"); + onGameThread(() -> { + player().getAbilities().flying = true; + minimap.hudElements().get(0).scale().set(1.5F); + return null; + }); + sleep(Duration.ofSeconds(8)); + screenshot("waypoints-plains"); + } + + // The world map: M opens it on the player; zoomed out it shows the spawn too, remembered. + injector().key(16, 'm', true); + sleep(Duration.ofMillis(150)); + injector().key(16, 'm', false); + boolean opened = waitUntil( + Duration.ofSeconds(3), + () -> minecraft.gui.screen() != null + && minecraft.gui.screen().getClass().getSimpleName().equals("WorldMapScreen")); + report.check("the world map key opens it", opened, ""); + sleep(Duration.ofSeconds(2)); + screenshot("worldmap"); + onGameThread(() -> { + var screen = java.util.Objects.requireNonNull(minecraft.gui.screen()); + screen.mouseScrolled(screen.width / 2.0, screen.height / 2.0, 0, -10); + return null; + }); + sleep(Duration.ofSeconds(2)); + screenshot("worldmap-zoomed-out"); + injector().key(16, 'm', true); + sleep(Duration.ofMillis(150)); + injector().key(16, 'm', false); + report.check( + "the world map key closes it", + waitUntil(Duration.ofSeconds(3), () -> minecraft.gui.screen() == null), + ""); + onGameThread(() -> { + incari.client.modules.MapMemory.save(); + return null; + }); + java.nio.file.Path maps = minecraft.gameDirectory.toPath().resolve("incari/map"); + long regionFiles; + try (var walk = java.nio.file.Files.walk(maps)) { + regionFiles = walk.filter(file -> file.toString().contains(world) + && file.getFileName().toString().endsWith(".map")) + .count(); + } catch (java.io.IOException e) { + regionFiles = 0; + } + report.check("the explored map is remembered", regionFiles >= 2, regionFiles + " region files"); + } + + private static > void next(incari.framework.setting.ChoiceSetting setting) { + setting.next(); + } + + /** Runs commands as the integrated server's console, in order, and waits for them. */ + private void serverCommands(String... commands) { + onGameThread(() -> { + IntegratedServer server = minecraft.getSingleplayerServer(); + if (server == null) { + throw new IllegalStateException("No integrated server"); + } + server.submit(() -> { + for (String command : commands) { + server.getCommands().performPrefixedCommand(server.createCommandSourceStack(), command); + } + }) + .get(30, TimeUnit.SECONDS); + return null; + }); + } + + /** + * The HUD editor. Opened from the module menu's Edit HUD button with Toggle Sprint on, in + * both GUI presets: its line is shown (a sample, nothing being latched) over the blurred world, + * dragged to the right where it snaps and takes the right side's anchor, resized by its corner, + * and saved. In Potato the blurred backdrop is drawn about ten times a second while the editor + * runs at the full frame rate. + */ + private void hudEditorScenario() throws Exception { + waitForTitle(); + newSurvivalWorld(); + boolean loaded = waitUntil(Duration.ofMinutes(3), () -> inWorld() && player().tickCount > 60); + report.check("singleplayer world", loaded, loaded ? "" : stateDescription()); + if (!loaded) { + screenshot("fail-world"); + return; + } + takeControl(); + incari.framework.Module toggleSprint = onGameThread(() -> { + incari.framework.Module module = + incari.client.modules.IncariModules.system().module("togglesprint"); + if (module == null) { + throw new IllegalStateException("No togglesprint module"); + } + module.setEnabled(true); + return module; + }); + incari.framework.hud.HudElement status = toggleSprint.hudElements().get(0); + for (incari.client.ui.GuiPreset preset : incari.client.ui.GuiPreset.values()) { + String name = "hudeditor-" + preset.name().toLowerCase(java.util.Locale.ROOT); + onGameThread(() -> { + incari.client.ui.Look.set(preset); + status.resetPlacement(); + minecraft.gui.setScreen(null); + minecraft.mouseHandler.grabMouse(); + return null; + }); + sleep(Duration.ofMillis(500)); + injector().tap(229, 0x400000E5); // Right Shift: the module menu + waitUntil(Duration.ofSeconds(3), () -> screenName().equals("ModuleListScreen")); + sleep(Duration.ofMillis(500)); + clickButton("Edit HUD"); + boolean open = waitUntil(Duration.ofSeconds(3), () -> screenName().equals("HudEditorScreen")); + report.check(name + ": Edit HUD opens the editor", open, open ? "" : stateDescription()); + if (!open) { + screenshot("fail-" + name); + continue; + } + sleep(Duration.ofSeconds(1)); + injector().moveTo(400, 400); + sleep(Duration.ofMillis(300)); + screenshot(name); + + // Frame rate and backdrop refreshes over two seconds. + int refreshesBefore = incari.client.gui.BackdropCache.refreshes(); + long framesBefore = onGameThread(() -> (long) minecraft.getFps()); + sleep(Duration.ofSeconds(2)); + int refreshes = incari.client.gui.BackdropCache.refreshes() - refreshesBefore; + long fps = onGameThread(() -> (long) minecraft.getFps()); + if (preset == incari.client.ui.GuiPreset.POTATO) { + boolean throttled = refreshes >= 10 && refreshes <= 26; + report.check( + name + ": backdrop ~10 a second", + throttled, + refreshes + " refreshes in 2 s at " + fps + " fps (" + framesBefore + " before)"); + } else { + report.check(name + ": backdrop live in Normal", refreshes == 0, refreshes + " refreshes"); + } + + // Drag the line from the top left to the right edge, halfway down. + var window = onGameThread(minecraft::getWindow); + float toWindow = (float) window.getScreenWidth() / window.getGuiScaledWidth(); + int[] bounds = new int[4]; + int guiWidth = window.getGuiScaledWidth(); + int guiHeight = window.getGuiScaledHeight(); + float startX = (2 + 10) * toWindow; + float startY = (2 + 4) * toWindow; + injector().moveTo(startX, startY); + sleep(Duration.ofMillis(200)); + injector().mouseButton(1, true); + sleep(Duration.ofMillis(100)); + float endX = (guiWidth - 30) * toWindow; + float endY = (guiHeight / 2.0F) * toWindow; + for (int step = 1; step <= 10; step++) { + injector().moveTo(startX + (endX - startX) * step / 10, startY + (endY - startY) * step / 10); + sleep(Duration.ofMillis(40)); + } + sleep(Duration.ofMillis(300)); + screenshot(name + "-drag"); + injector().mouseButton(1, false); + sleep(Duration.ofMillis(300)); + String placed = onGameThread(() -> status.anchor().get() + " " + + status.offsetX().get() + "," + status.offsetY().get()); + boolean right = placed.startsWith("RIGHT ") && placed.contains(" 2,"); + report.check(name + ": dragged to the right edge, snapped", right, placed); + + // Its corner handle, dragged outward, makes it bigger. + float before = status.scale().get(); + int[] rect = onGameThread(() -> { + int width = Math.round(minecraft.font.width("[Sprinting (Toggled)]") + * status.scale().get()); + int height = + Math.round(minecraft.font.lineHeight * status.scale().get()); + return new int[] { + status.anchor().get().x(status.offsetX().get(), width, guiWidth), + status.anchor().get().y(status.offsetY().get(), height, guiHeight), + width, + height + }; + }); + System.arraycopy(rect, 0, bounds, 0, 4); + float handleX = (bounds[0] + bounds[2] + 2) * toWindow; + float handleY = (bounds[1] + bounds[3] + 2) * toWindow; + injector().moveTo(handleX, handleY); + sleep(Duration.ofMillis(200)); + injector().mouseButton(1, true); + sleep(Duration.ofMillis(100)); + injector().moveTo(handleX + 40 * toWindow, handleY + 20 * toWindow); + sleep(Duration.ofMillis(100)); + injector().moveTo(handleX + 60 * toWindow, handleY + 30 * toWindow); + sleep(Duration.ofMillis(300)); + screenshot(name + "-resize"); + injector().mouseButton(1, false); + sleep(Duration.ofMillis(200)); + float after = status.scale().get(); + report.check(name + ": the corner resizes", after > before, before + " -> " + after); + injector().moveTo(guiWidth / 2.0F * toWindow, guiHeight * 0.7F * toWindow); + sleep(Duration.ofMillis(300)); + screenshot(name + "-chosen"); + + clickButton("gui.done"); + boolean back = waitUntil(Duration.ofSeconds(3), () -> screenName().equals("ModuleListScreen")); + report.check(name + ": Done goes back to the module menu", back, stateDescription()); + } + onGameThread(() -> { + minecraft.gui.setScreen(null); + return null; + }); + sleep(Duration.ofMillis(1500)); + screenshot("hudeditor-hud"); + Path profile = directory.resolveSibling("incari/modules/profiles/Default.json"); + String saved = Files.isRegularFile(profile) ? Files.readString(profile) : ""; + boolean kept = saved.contains("\"anchor\": \"right\"") || saved.contains("\"anchor\": \"RIGHT\""); + report.check("placement saved", kept, kept ? profile.toString() : saved); + onGameThread(() -> { + incari.client.ui.Look.set(incari.client.ui.GuiPreset.POTATO); + minecraft.gui.setScreen(new PauseScreen(true)); + return null; + }); + sleep(Duration.ofMillis(500)); + clickButton("menu.returnToMenu"); + waitUntil( + Duration.ofMinutes(1), () -> minecraft.level == null && minecraft.gui.screen() instanceof TitleScreen); + } + + private String screenName() { + return onGameThread(() -> minecraft.gui.screen() == null + ? "none" + : minecraft.gui.screen().getClass().getSimpleName()); + } + + /** + * Checks Incari's mesher against the game's section compiler: with the game run with + * {@code -Dincari.mesher=verify}, every section is meshed both ways and compared. Visits + * terrain of many kinds, every dimension, and the debug world (every block state), with smooth + * lighting and cutout leaves on and off, and fails if any section's mesh differs. + */ + private void mesherScenario() throws Exception { + waitForTitle(); + report.check( + "mesher in verify mode", + incari.client.render.mesher.Meshing.mode() == incari.client.render.mesher.Meshing.Mode.VERIFY, + "run with -Dincari.mesher=verify"); + onGameThread(() -> { + minecraft.options.renderDistance().set(10); + minecraft.options.ambientOcclusion().set(true); + minecraft.options.cutoutLeaves().set(true); + return null; + }); + createWorld("incari-mesher-", WorldPresets::createNormalWorldDimensions); + if (!waitForWorld("normal world")) { + return; + } + for (String setup : + new String[] {"gamemode spectator", "gamerule advance_time false", "time set 6000", "weather clear"}) { + serverCommand(setup); + } + int[][] places = { + {0, 120, 0, 0, 30}, {900, 110, 40, 90, 25}, {-1300, 100, 700, 180, 35}, {2600, 130, -2100, -90, 20}, + {-3900, 90, -3300, 45, 40}, {5200, 140, 4100, 135, 30}, {300, 40, -500, 0, 10}, {-800, -20, -800, 90, 5}, + {7000, 100, -6000, -45, 45}, {-9000, 120, 9000, 0, 30}, + }; + for (int[] place : places) { + serverCommand("tp @s " + place[0] + " " + place[1] + " " + place[2] + " " + place[3] + " " + place[4]); + settle("overworld " + place[0] + " " + place[2]); + } + serverCommand("execute in minecraft:the_nether run tp @s 0 70 0 0 20"); + settle("the nether"); + serverCommand("execute in minecraft:the_nether run tp @s 600 60 -400 90 20"); + settle("the nether, farther"); + serverCommand("execute in minecraft:the_end run tp @s 0 90 0 0 30"); + settle("the end"); + serverCommand("execute in minecraft:the_end run tp @s 1000 70 1000 0 30"); + settle("the end's islands"); + serverCommand("execute in minecraft:overworld run tp @s 0 120 0 0 30"); + settle("overworld again"); + setOption( + "smooth lighting off", + () -> minecraft.options.ambientOcclusion().set(false)); + setOption("cutout leaves off", () -> minecraft.options.cutoutLeaves().set(false)); + setOption( + "smooth lighting on, cutout leaves off", + () -> minecraft.options.ambientOcclusion().set(true)); + onGameThread(() -> { + minecraft.options.cutoutLeaves().set(true); + minecraft.disconnectWithSavingScreen(); + return null; + }); + waitUntil(Duration.ofMinutes(1), () -> minecraft.level == null); + + createWorld( + "incari-mesher-debug-", + registries -> registries + .lookupOrThrow(net.minecraft.core.registries.Registries.WORLD_PRESET) + .getOrThrow(WorldPresets.DEBUG) + .value() + .createWorldDimensions()); + if (waitForWorld("debug world")) { + serverCommand("gamemode spectator"); + for (int x = 0; x < 360; x += 60) { + for (int z = 0; z < 360; z += 60) { + serverCommand("tp @s " + x + " 90 " + z + " 45 60"); + settle("debug world " + x + " " + z); + } + } + setOption( + "debug world, smooth lighting off", + () -> minecraft.options.ambientOcclusion().set(false)); + } + int[] counts = incari.client.render.mesher.Meshing.verifyCounts(); + report.check( + "Incari's mesher matches the game's", + counts[0] > 2000 && counts[1] == 0, + counts[0] + " sections compared, " + counts[1] + " differ (the log has the first ones)"); + onGameThread(() -> { + minecraft.options.ambientOcclusion().set(true); + minecraft.disconnectWithSavingScreen(); + return null; + }); + waitUntil(Duration.ofMinutes(1), () -> minecraft.level == null); + } + + private void createWorld( + String prefix, + java.util.function.Function< + net.minecraft.core.HolderLookup.Provider, + net.minecraft.world.level.levelgen.WorldDimensions> + dimensions) { + onGameThread(() -> { + String name = prefix + System.currentTimeMillis(); + LevelSettings settings = new LevelSettings( + name, + GameType.CREATIVE, + new LevelSettings.DifficultySettings(Difficulty.PEACEFUL, false, false), + true, + WorldDataConfiguration.DEFAULT); + minecraft + .createWorldOpenFlows() + .createFreshLevel( + name, settings, new WorldOptions(SEED, true, false), dimensions, new TitleScreen()); + return null; + }); + } + + private boolean waitForWorld(String what) { + boolean loaded = waitUntil(Duration.ofMinutes(3), () -> inWorld() && player().tickCount > 60); + report.check(what, loaded, loaded ? "created and loaded" : stateDescription()); + return loaded; + } + + /** Runs a command as the player, through the connection (the world allows commands). */ + private void serverCommand(String command) { + onGameThread(() -> { + player().connection.sendCommand(command); + return null; + }); + sleep(Duration.ofMillis(300)); + } + + /** Waits for the terrain around to be meshed, then a little longer. */ + private void settle(String where) { + sleep(Duration.ofSeconds(3)); + boolean done = waitUntil(Duration.ofSeconds(90), () -> minecraft.levelRenderer.hasRenderedAllSections()); + sleep(Duration.ofSeconds(2)); + int[] counts = incari.client.render.mesher.Meshing.verifyCounts(); + org.slf4j.LoggerFactory.getLogger("Smoke test") + .info( + "Mesher at {}: {} sections compared, {} differ{}", + where, + counts[0], + counts[1], + done ? "" : " (still meshing)"); + screenshot("mesher-" + where.replace(' ', '-').replace(",", "")); + } + + private void setOption(String what, Runnable change) { + // The options recompile every section themselves when they change. + onGameThread(() -> { + change.run(); + return null; + }); + settle(what); + } + + private void joinScenario(String address) throws Exception { + waitForTitle(); + onGameThread(() -> { + ConnectScreen.startConnecting( + new TitleScreen(), + minecraft, + ServerAddress.parseString(address), + new ServerData("Incari smoke host", address, ServerData.Type.OTHER), + false, + null); + return null; + }); + boolean joined = waitUntil(Duration.ofMinutes(2), () -> inWorld() && player().tickCount > 40); + report.check( + "join over the platform transport", + joined, + joined ? "logged in to " + address + " and received the world" : stateDescription()); + if (!joined) { + screenshot("fail-join"); + } + if (!inWorld()) { + return; + } + takeControl(); + screenshot("join-world"); + walk(); + chat("hello from the second client"); + sleep(Duration.ofSeconds(3)); + injector().tap(41, 0x1B); // Escape + waitUntil(Duration.ofSeconds(3), () -> minecraft.gui.screen() instanceof PauseScreen); + clickButton("menu.disconnect"); + report.check( + "disconnect", + waitUntil(Duration.ofMinutes(1), () -> minecraft.level == null), + "left the server cleanly"); + } + + /** + * Joins a dedicated server: over a WebSocket when the address is a {@code ws://} URL. + * Changes dimension there and back, disconnects, and reconnects. The player must be an + * operator on the server, for the teleport commands. + */ + private void serverScenario(String address) throws Exception { + waitForTitle(); + ping(address); + for (int attempt = 1; attempt <= 2; attempt++) { + String label = attempt == 1 ? "join " : "reconnect to "; + connect(address); + boolean joined = waitUntil(Duration.ofMinutes(2), () -> inWorld() && player().tickCount > 40); + report.check( + label + address, + joined, + joined + ? "logged in and received the world over " + transportDescription() + " as " + + versionDescription() + : stateDescription()); + if (!joined) { + screenshot("fail-server-join-" + attempt); + return; + } + boolean translated = viaInPipeline(); + if (attempt == 1) { + takeControl(); + screenshot("server-world"); + chat("hello over " + (address.startsWith("ws") ? "a WebSocket" : "TCP")); + if (translated) { + // An older server: moving, the inventory, and staying connected while idle + // (1.8 wants a movement packet every tick, which Via sends for the game). + walk(); + jump(); + inventory(); + stayConnected(Duration.ofSeconds(20)); + } else { + // The teleports land inside rock or water; a creative player takes no damage. + command("gamemode creative"); + changeDimension("minecraft:the_nether"); + changeDimension("minecraft:overworld"); + transfer(address); + } + } else { + injector().focus(); + sleep(Duration.ofSeconds(2)); + connectionDetails(); + return; + } + injector().tap(41, 0x1B); // Escape + waitUntil(Duration.ofSeconds(3), () -> minecraft.gui.screen() instanceof PauseScreen); + clickButton("menu.disconnect"); + report.check( + "disconnect (" + attempt + ")", + waitUntil( + Duration.ofMinutes(1), () -> minecraft.level == null && minecraft.getConnection() == null), + "left the server cleanly"); + sleep(Duration.ofSeconds(2)); + } + } + + /** + * Kicked by the server: the disconnection screen offers Connection Details, which shows how the + * connection went and returns to it. + */ + private void connectionDetails() { + command("kick @s Connection details check"); + boolean disconnected = + waitUntil(Duration.ofSeconds(30), () -> minecraft.gui.screen() instanceof DisconnectedScreen); + report.check("kicked", disconnected, stateDescription()); + if (!disconnected) { + return; + } + sleep(Duration.ofSeconds(1)); + screenshot("server-disconnected"); + clickButton("Connection Details"); + boolean shown = + waitUntil(Duration.ofSeconds(5), () -> minecraft.gui.screen() instanceof ConnectionDetailsScreen); + sleep(Duration.ofSeconds(1)); + screenshot("server-connection-details"); + report.check("connection details", shown, stateDescription()); + if (shown) { + clickButton("gui.back"); + report.check( + "connection details back", + waitUntil(Duration.ofSeconds(5), () -> minecraft.gui.screen() instanceof DisconnectedScreen), + stateDescription()); + } + } + + /** + * Skins both ways: this player sets a skin generated from its name (and, as + * IncariSkinA, a slim model and a cape), joins, and waits for {@code peer}, running the same + * scenario, to appear with the skin it sent, as a texture of exactly those pixels. + */ + private void skinsScenario(String peer, String address) throws Exception { + waitForTitle(); + String self = minecraft.getUser().getName(); + writeGeneratedSkin(self, self.endsWith("A")); + connect(address); + waitUntil(Duration.ofMinutes(2), this::inWorld); + respawnIfDead(); + boolean joined = waitUntil(Duration.ofMinutes(2), () -> inWorld() && player().tickCount > 40); + report.check("join " + address + " as " + self, joined, joined ? "in the world" : stateDescription()); + if (!joined) { + screenshot("fail-skins-join"); + return; + } + String own = onGameThread(() -> skinDescription(self)); + report.check("own skin", own.startsWith("custom"), own); + + String[] seen = {"not in the player list"}; + boolean arrived = waitUntil(Duration.ofMinutes(3), () -> { + seen[0] = onGameThread(() -> skinDescription(peer)); + return seen[0].equals(expectedSkin(peer)); + }); + report.check(peer + "'s skin from the server", arrived, seen[0]); + if (arrived) { + takeControl(); + command("tp " + peer); + sleep(Duration.ofSeconds(2)); + injector().tap(62, 0x4000003E); // F5: third person, facing the peer from behind + sleep(Duration.ofSeconds(1)); + screenshot("skins-" + peer); + } + // Stay for the peer's check. + sleep(Duration.ofSeconds(30)); + } + + /** + * Incari accounts and chat (ADR 0058, ADR 0059) against a real online service + * ({@code incari.online.url}, an online service run locally): this player and {@code peer}, running + * the same scenario at once, each make an account and join {@code address}. Each must see the + * other as an Incari player there, and the chat menu must list them under On This Server. Then + * A sends B a friend request by its per-server id and B accepts; they message as friends, and B + * messages A by its per-server id (A lets everyone on the server message it); B blocks A, and + * both see the friendship end. Last, each deletes its account, so runs don't pile them up. + */ + private void onlineScenario(String peer, String address) throws Exception { + waitForTitle(); + String self = minecraft.getUser().getName(); + boolean first = self.endsWith("A"); + incari.online.OnlineService online = onGameThread(incari.client.online.IncariOnline::service); + boolean reached = waitUntil(Duration.ofSeconds(30), () -> { + var status = online.status(); + return status == incari.framework.online.Online.Status.SIGNED_OUT + || status == incari.framework.online.Online.Status.SIGNED_IN; + }); + report.check( + "reach the online service", + reached, + onGameThread(() -> online.status().toString())); + if (!reached) { + return; + } + if (onGameThread(online::signedIn)) { + // A session left by an earlier run. + this.awaitOnline(done -> online.signOut(false, done)); + } + // A fresh account each run: usernames are 3 to 16 characters. + String username = + "Smoke" + (first ? "A" : "B") + Long.toString(System.currentTimeMillis() % 1_000_000_000L, 36); + String password = "smoke " + java.util.UUID.randomUUID(); + long started = System.nanoTime(); + incari.online.Result> signedUp = + this.>awaitOnline(done -> online.signUp(username, password, done)); + report.check( + "sign up as " + username, + signedUp.ok() && signedUp.value().size() == 10, + signedUp.ok() + ? "10 codes, " + (System.nanoTime() - started) / 1_000_000 + " ms with the proof of work" + : String.valueOf(signedUp.failure())); + if (!signedUp.ok()) { + return; + } + if (first) { + // So B can also reach A by its per-server id, not only as a friend. + this.awaitOnline(done -> online.setMessagesFrom(incari.online.Social.MessagesFrom.EVERYONE, done)); + } + + connect(address); + boolean joined = waitUntil(Duration.ofMinutes(2), () -> inWorld() && player().tickCount > 40); + report.check("join " + address + " as " + self, joined, joined ? "in the world" : stateDescription()); + if (!joined) { + screenshot("fail-online-join"); + return; + } + java.util.concurrent.atomic.AtomicReference other = + new java.util.concurrent.atomic.AtomicReference<>(); + boolean seen = waitUntil(Duration.ofMinutes(3), () -> { + var connection = minecraft.getConnection(); + var info = connection == null ? null : connection.getPlayerInfo(peer); + other.set(info == null ? null : online.player(info.getProfile().id())); + return other.get() != null; + }); + report.check( + peer + " is an Incari player here", + seen, + seen ? "pid " + java.util.Objects.requireNonNull(other.get()).pid() : "not seen"); + if (!seen) { + screenshot("fail-online-seen"); + return; + } + cosmeticsOnline(online, peer, first); + if (first) { + badgeShots(peer); + } + onGameThread(() -> { + minecraft.gui.setScreen(new incari.client.online.ChatMenuScreen(null)); + return null; + }); + sleep(Duration.ofSeconds(2)); + screenshot("online-on-this-server"); + onGameThread(() -> { + minecraft.gui.setScreen(null); + return null; + }); + + // Friends: A asks by B's id here; B accepts whatever arrives. + if (first) { + incari.framework.online.IncariPlayer target = java.util.Objects.requireNonNull(other.get()); + var asked = this.awaitOnline(done -> online.befriend(peer, target, done)); + report.check("send " + peer + " a friend request", asked.ok(), String.valueOf(asked.failure())); + } else { + boolean arrived = + waitUntil(Duration.ofMinutes(1), () -> online.social().pendingRequests() > 0); + report.check("a friend request arrives", arrived, arrived ? "" : "none in a minute"); + if (arrived) { + var request = onGameThread(() -> online.social().requests().get(0)); + var accepted = this.awaitOnline(done -> online.accept(request, done)); + report.check("accept it", accepted.ok(), String.valueOf(accepted.failure())); + } + } + boolean friends = + waitUntil(Duration.ofMinutes(1), () -> online.social().friends().size() == 1); + report.check( + "friends with " + peer, + friends, + onGameThread(() -> online.social().friends().toString())); + if (!friends) { + return; + } + var friend = onGameThread(() -> online.social().friends().get(0)); + var asFriend = new incari.online.Social.Peer(true, friend.fid(), friend.username()); + + // Messages: A first, then B answers, then B by A's id on this server. + String mine = "hello from " + self; + String theirs = "hello from " + peer; + if (first) { + report.check( + "send a message", + this.awaitOnline(done -> online.sendMessage(asFriend, mine, done)) + .ok(), + ""); + } + boolean heard = waitUntil( + Duration.ofMinutes(1), + () -> online.social().conversation(asFriend).messages().stream() + .anyMatch(m -> !m.mine() && m.text().equals(theirs))); + report.check("a message from " + peer, heard, heard ? "" : "nothing in a minute"); + if (!first) { + report.check( + "answer it", + this.awaitOnline(done -> online.sendMessage(asFriend, mine, done)) + .ok(), + ""); + var byPid = new incari.online.Social.Peer( + false, java.util.Objects.requireNonNull(other.get()).pid(), peer); + var sent = this.awaitOnline(done -> online.sendMessage(byPid, "by your id here", done)); + report.check("message " + peer + " by its id on this server", sent.ok(), String.valueOf(sent.failure())); + } else { + boolean byId = waitUntil( + Duration.ofMinutes(1), + () -> online.social().playersMessaged().containsValue(peer)); + report.check( + "a message by id on this server", + byId, + onGameThread(() -> online.social().playersMessaged().toString())); + } + onGameThread(() -> { + minecraft.gui.setScreen(new incari.client.online.ChatMenuScreen(null, asFriend)); + return null; + }); + sleep(Duration.ofSeconds(2)); + screenshot("online-conversation"); + onGameThread(() -> { + minecraft.gui.setScreen(null); + return null; + }); + + // B blocks A: the friendship ends on both sides, and A stops seeing B as an Incari player. + if (!first) { + var blocked = this.awaitOnline(done -> online.blockFriend(friend, done)); + report.check("block " + peer, blocked.ok(), String.valueOf(blocked.failure())); + } + boolean ended = + waitUntil(Duration.ofMinutes(1), () -> online.social().friends().isEmpty()); + report.check( + "the block ends the friendship", + ended, + onGameThread(() -> online.social().friends().toString())); + if (first) { + boolean hidden = waitUntil(Duration.ofSeconds(30), () -> { + var connection = minecraft.getConnection(); + var info = connection == null ? null : connection.getPlayerInfo(peer); + return info != null && online.player(info.getProfile().id()) == null; + }); + report.check(peer + " no longer shows as an Incari player", hidden, ""); + } + // Let the peer finish its checks, then clean up. + sleep(Duration.ofSeconds(10)); + var deleted = this.awaitOnline(done -> online.deleteAccount(password, done)); + report.check("delete the account", deleted.ok(), String.valueOf(deleted.failure())); + } + + /** + * Incari's badge before {@code peer}'s name tag (ADR 0062), seen from 4 and 12 blocks: over RCON + * ({@code incari.rcon}, password in {@code INCARI_RCON_PASSWORD}) a clear strip of snow is made + * where this player stands, and both are put on it facing each other at noon. + */ + private void badgeShots(String peer) throws Exception { + Rcon rcon = new Rcon( + System.getProperty("incari.rcon", "127.0.0.1:25592"), + System.getenv().getOrDefault("INCARI_RCON_PASSWORD", "incari-local")); + String self = minecraft.getUser().getName(); + net.minecraft.core.BlockPos at = onGameThread(() -> player().blockPosition()); + int x = at.getX(); + int y = at.getY(); + int z = at.getZ(); + try { + rcon.run("time set noon"); + rcon.run("weather clear"); + rcon.run("fill " + (x - 3) + " " + (y - 1) + " " + (z - 16) + " " + (x + 3) + " " + (y - 1) + " " + (z + 1) + + " minecraft:snow_block"); + rcon.run("fill " + (x - 3) + " " + y + " " + (z - 16) + " " + (x + 3) + " " + (y + 3) + " " + (z + 1) + + " minecraft:air"); + rcon.run("tp " + self + " " + (x + 0.5) + " " + y + " " + (z + 0.5) + " 180 0"); + for (int distance : new int[] {4, 12}) { + rcon.run("tp " + peer + " " + (x + 0.5) + " " + y + " " + (z + 0.5 - distance) + " 0 0"); + sleep(Duration.ofSeconds(3)); + screenshot("online-badge-" + distance); + } + report.check("badge shots", true, "online-badge-4, online-badge-12"); + } catch (java.io.IOException e) { + report.check("badge shots", false, "RCON: " + e); + } + } + + /** + * ADR 0061 against a real service: each player wears something different, sees what the other + * wears, sees the other's emote, and hides the other's cosmetics with the switch. + */ + private void cosmeticsOnline(incari.online.OnlineService online, String peer, boolean first) throws Exception { + incari.online.Wardrobe wardrobe = online.wardrobe(); + boolean synced = waitUntil(Duration.ofSeconds(30), wardrobe::shared); + report.check("the account's wardrobe arrives", synced, ""); + if (!synced) { + return; + } + java.util.List mine = first + ? java.util.List.of("cape.aurora", "hat.crown") + : java.util.List.of("back.angel_wings", "nametag.gold"); + java.util.List theirs = first + ? java.util.List.of("back.angel_wings", "nametag.gold") + : java.util.List.of("cape.aurora", "hat.crown"); + onGameThread(() -> { + wardrobe.setShowOthers(true); + wardrobe.wear(incari.online.Loadout.EMPTY); + for (String id : mine) { + wardrobe.wear(cosmetic(id)); + } + return null; + }); + java.util.function.Supplier peerNow = () -> { + var connection = minecraft.getConnection(); + var info = connection == null ? null : connection.getPlayerInfo(peer); + return info == null ? null : online.player(info.getProfile().id()); + }; + String[] last = {""}; + boolean wears = waitUntil(Duration.ofSeconds(45), () -> { + var player = peerNow.get(); + last[0] = + player == null ? "not an Incari player" : player.cosmetics().toString(); + return player != null && player.cosmetics().containsAll(theirs); + }); + report.check(peer + "'s cosmetics arrive", wears, last[0]); + boolean drawn = onGameThread(() -> { + var other = otherPlayer(peer); + if (other == null) { + return false; + } + var state = new net.minecraft.client.renderer.entity.state.AvatarRenderState(); + incari.client.cosmetics.Cosmetics.extract(other, state); + return state.incariWorn != incari.client.cosmetics.Worn.NONE; + }); + report.check(peer + "'s cosmetics are on their render state", drawn, ""); + + // Emotes both ways: each plays one every few seconds until it has seen the other's. + boolean sawEmote = false; + long deadline = System.nanoTime() + Duration.ofSeconds(40).toNanos(); + while (System.nanoTime() < deadline && !sawEmote) { + onGameThread(() -> incari.client.cosmetics.Cosmetics.playEmote(cosmetic("emote.wave"))); + sawEmote = waitUntil(Duration.ofMillis(2600), () -> { + var other = otherPlayer(peer); + if (other == null) { + return false; + } + var state = new net.minecraft.client.renderer.entity.state.AvatarRenderState(); + incari.client.cosmetics.Cosmetics.extract(other, state); + return incari.client.cosmetics.Cosmetics.emoteOf(state) != null; + }); + } + report.check(peer + "'s emote arrives", sawEmote, ""); + // Go on playing a while, for the peer's check. + for (int i = 0; i < 4; i++) { + onGameThread(() -> incari.client.cosmetics.Cosmetics.playEmote(cosmetic("emote.wave"))); + sleep(Duration.ofMillis(2600)); + } + onGameThread(() -> { + minecraft.options.setCameraType(net.minecraft.client.CameraType.FIRST_PERSON); + return null; + }); + + // The switch: the peer's cosmetics hide, and come back. + boolean hidden = onGameThread(() -> { + wardrobe.setShowOthers(false); + var other = otherPlayer(peer); + var state = new net.minecraft.client.renderer.entity.state.AvatarRenderState(); + if (other != null) { + incari.client.cosmetics.Cosmetics.extract(other, state); + } + wardrobe.setShowOthers(true); + return other != null && state.incariWorn == incari.client.cosmetics.Worn.NONE; + }); + report.check("Show others' cosmetics off hides " + peer + "'s", hidden, ""); + } + + private net.minecraft.client.player.@Nullable AbstractClientPlayer otherPlayer(String name) { + var level = minecraft.level; + if (level == null) { + return null; + } + for (var player : level.players()) { + if (player.getGameProfile().name().equals(name)) { + return player; + } + } + return null; + } + + /** Runs an online request on the game thread and waits for its answer (a minute at most). */ + private incari.online.Result awaitOnline( + java.util.function.Consumer>> request) + throws Exception { + java.util.concurrent.CompletableFuture> answer = + new java.util.concurrent.CompletableFuture<>(); + onGameThread(() -> { + request.accept(answer::complete); + return null; + }); + return answer.get(1, TimeUnit.MINUTES); + } + + /** + * Voice chat's signalling on an Eagler server with voice: this player turns global voice + * on and waits to be paired with {@code peer} (running the same scenario), through the server, + * with WebRTC scripted ({@link ScriptedRtc}): the offer, answer and candidates cross the server, + * and each side lists the other as a voice. + */ + private void voiceScenario(String peer, String address) throws Exception { + waitForTitle(); + connect(address); + boolean joined = waitUntil(Duration.ofMinutes(2), () -> inWorld() && player().tickCount > 40); + report.check("join " + address, joined, joined ? "in the world" : stateDescription()); + if (!joined) { + return; + } + boolean allowed = waitUntil( + Duration.ofSeconds(20), + () -> onGameThread(() -> { + var voice = incari.client.eagler.EaglerVoice.current(); + return voice != null && voice.available(); + })); + report.check("the server offers voice", allowed, allowed ? "voice allowed" : "no voice from the server"); + if (!allowed) { + return; + } + onGameThread(() -> { + var voice = incari.client.eagler.EaglerVoice.current(); + if (voice != null) { + voice.setChannel(incari.client.eagler.VoiceSettings.Channel.GLOBAL); + } + return null; + }); + String[] heard = {"nobody"}; + boolean paired = waitUntil( + Duration.ofMinutes(2), + () -> onGameThread(() -> { + var voice = incari.client.eagler.EaglerVoice.current(); + if (voice == null) { + return false; + } + heard[0] = voice.speakers().toString(); + return voice.speakers().stream().anyMatch(s -> s.name().equals(peer)); + })); + report.check("paired with " + peer + " by voice", paired, heard[0]); + // Stay for the peer's check. + sleep(Duration.ofSeconds(20)); + } + + /** + * The legacy behaviour on a 1.8 server, where the server itself can tell: sneaking's box and + * eye height, the pick margin, no attack cooldown, a ladder's thickness, and a held sword + * blocking, which the 1.8 server shows by halving an arrow's damage ((1 + d) / 2). Sets the + * world up over RCON ({@code incari.rcon}, password in {@code INCARI_RCON_PASSWORD}). + */ + private void legacyScenario(String address) throws Exception { + Rcon rcon = new Rcon( + System.getProperty("incari.rcon", "127.0.0.1:25611"), + System.getenv().getOrDefault("INCARI_RCON_PASSWORD", "incari-dev")); + String name = minecraft.getUser().getName(); + waitForTitle(); + connect(address); + boolean joined = waitUntil(Duration.ofMinutes(2), () -> inWorld() && player().tickCount > 40); + report.check("join " + address, joined, joined ? versionDescription() : stateDescription()); + if (!joined) { + return; + } + takeControl(); + rcon.run("difficulty 0"); + rcon.run("time set 1000"); + rcon.run("gamemode 0 " + name); + rcon.run("clear " + name); + rcon.run("effect " + name + " 6 1 10"); + sleep(Duration.ofSeconds(2)); + + int protocol = onGameThread(incari.client.legacy.LegacyRules::protocol); + report.check( + "rules follow the server", + protocol == 47 && incari.client.legacy.LegacyRules.combat18(), + "protocol " + protocol); + float pick = onGameThread(() -> player().getPickRadius()); + report.check("1.8's pick margin", Math.abs(pick - 0.1F) < 1e-6, "pick radius " + pick); + float strength = onGameThread(() -> { + player().resetAttackStrengthTicker(); + return player().getAttackStrengthScale(0.0F); + }); + report.check("no attack cooldown", strength == 1.0F, "strength right after a swing " + strength); + + injector().key(225, 0x400000E1, true); // left shift: sneak + sleep(Duration.ofMillis(800)); + float[] sneaking = onGameThread(() -> new float[] {player().getBbHeight(), player().getEyeHeight()}); + injector().key(225, 0x400000E1, false); + report.check( + "1.8's sneaking box", + Math.abs(sneaking[0] - 1.8F) < 1e-4 && Math.abs(sneaking[1] - 1.54F) < 1e-4, + "height " + sneaking[0] + ", eyes " + sneaking[1]); + + net.minecraft.core.BlockPos ladder = + onGameThread(() -> player().blockPosition().offset(3, 0, 0)); + rcon.run("setblock " + ladder.getX() + " " + ladder.getY() + " " + ladder.getZ() + " minecraft:ladder 2"); + boolean placed = waitUntil( + Duration.ofSeconds(5), + () -> onGameThread( + () -> level().getBlockState(ladder).is(net.minecraft.world.level.block.Blocks.LADDER))); + double thickness = onGameThread(() -> { + var bounds = level().getBlockState(ladder) + .getCollisionShape(level(), ladder) + .bounds(); + return Math.min(bounds.getXsize(), bounds.getZsize()); + }); + report.check("1.8's ladder", placed && Math.abs(thickness - 0.125) < 1e-6, "thickness " + thickness); + rcon.run("setblock " + ladder.getX() + " " + ladder.getY() + " " + ladder.getZ() + " minecraft:air"); + + rcon.run("give " + name + " minecraft:diamond_sword 1"); + waitUntil( + Duration.ofSeconds(5), + () -> onGameThread(() -> !player().getInventory().getItem(0).isEmpty())); + injector().tap(30, '1'); // the first hotbar slot + sleep(Duration.ofMillis(500)); + float open = arrowDamage(rcon, name); + injector().mouseButton(3, true); // right button: use, which raises the sword + boolean raised = waitUntil( + Duration.ofSeconds(3), + () -> onGameThread(() -> player().isUsingItem() + && player().getUseItem().getUseAnimation() == net.minecraft.world.item.ItemUseAnimation.BLOCK)); + screenshot("legacy-blocking"); + float blocked = arrowDamage(rcon, name); + injector().mouseButton(3, false); + report.check( + "sword blocking", + raised && open > 0 && Math.abs(blocked - (1 + open) / 2) < 0.05F, + "raised " + raised + "; an arrow took " + open + " open, " + blocked + " blocking"); + } + + /** Health an arrow dropped onto the player takes, after healing it to full. */ + private float arrowDamage(Rcon rcon, String name) throws Exception { + rcon.run("effect " + name + " 6 1 10"); + waitUntil(Duration.ofSeconds(5), () -> onGameThread(() -> player().getHealth() >= player().getMaxHealth())); + sleep(Duration.ofMillis(600)); // past the hurt cooldown of any earlier hit + float before = onGameThread(() -> player().getHealth()); + net.minecraft.world.phys.Vec3 at = onGameThread(() -> player().position()); + rcon.run(String.format( + java.util.Locale.ROOT, + "summon Arrow %.2f %.2f %.2f {Motion:[0.0,-1.5,0.0],damage:2.0}", + at.x, + at.y + 3.2, + at.z)); + // Read at the first change: peaceful's regeneration would add to it a second later. + float[] after = {before}; + waitUntil(Duration.ofSeconds(4), () -> (after[0] = onGameThread(() -> player().getHealth())) < before); + return before - after[0]; + } + + /** + * Password logins and cookies, against an Eagler server whose auth plugin wants a + * password for this player's name: the password screen comes up, the password typed there + * logs in, the server's cookie is kept, and the next join logs in by the cookie alone. + */ + private void authScenario(String address) throws Exception { + waitForTitle(); + Path cookies = minecraft.gameDirectory.toPath().resolve("incari").resolve("eagler-cookies.txt"); + Files.deleteIfExists(cookies); + connect(address); + boolean asked = waitUntil( + Duration.ofSeconds(30), + () -> onGameThread(() -> minecraft.gui.screen() instanceof incari.client.eagler.PasswordScreen)); + report.check("the server asks for a password", asked, asked ? "the password screen is up" : stateDescription()); + if (!asked) { + screenshot("fail-auth-screen"); + return; + } + screenshot("auth-password-screen"); + if (input == null) { + // Not takeControl(): grabbing the mouse closes the screen being typed into. + int windowId = onGameThread( + () -> SDLVideo.SDL_GetWindowID(minecraft.getWindow().handle())); + input = new SdlInjector(windowId); + } + injector().focus(); + sleep(Duration.ofMillis(300)); + injector().text("incari"); + sleep(Duration.ofMillis(200)); + injector().tap(40, 0x0D); // Enter logs in + boolean joined = waitUntil(Duration.ofMinutes(1), () -> inWorld() && player().tickCount > 40); + report.check("join with the password", joined, joined ? "in the world" : stateDescription()); + if (!joined) { + screenshot("fail-auth-join"); + return; + } + boolean kept = waitUntil(Duration.ofSeconds(15), () -> Files.isRegularFile(cookies)); + report.check("the server's cookie is kept", kept, kept ? cookies.toString() : "no cookie file"); + injector().tap(41, 0x1B); // Escape + waitUntil(Duration.ofSeconds(3), () -> minecraft.gui.screen() instanceof PauseScreen); + clickButton("menu.disconnect"); + waitUntil(Duration.ofMinutes(1), () -> minecraft.level == null && minecraft.getConnection() == null); + sleep(Duration.ofSeconds(2)); + + // A fresh session: no password in memory, only the cookie. + onGameThread(() -> { + incari.client.eagler.EaglerAuth.forget(address); + return null; + }); + connect(address); + boolean[] askedAgain = {false}; + boolean rejoined = waitUntil(Duration.ofMinutes(1), () -> { + askedAgain[0] |= onGameThread(() -> minecraft.gui.screen() instanceof incari.client.eagler.PasswordScreen); + return inWorld() && player().tickCount > 40; + }); + report.check( + "join with the cookie", + rejoined && !askedAgain[0], + rejoined + ? (askedAgain[0] ? "asked for the password again" : "logged in without one") + : stateDescription()); + } + + /** + * M2: the screens Incari adds, drawn: the edit-server screen's Version and Wispcraft buttons, the + * Wispcraft screen, the Eagler skin screen. + */ + private void screensScenario() { + waitForTitle(); + onGameThread(() -> { + net.minecraft.client.multiplayer.ServerData server = new net.minecraft.client.multiplayer.ServerData( + "Test", "ws://127.0.0.1:8801", ServerData.Type.OTHER); + server.incariVersion = 47; + minecraft.gui.setScreen(new net.minecraft.client.gui.screens.ManageServerScreen( + new TitleScreen(), + net.minecraft.network.chat.Component.literal("Edit Server Info"), + ok -> {}, + server)); + return null; + }); + sleep(Duration.ofSeconds(2)); + screenshot("screen-edit-server"); + // Into the Wispcraft screen and back: the edit screen is shown again, only laid out again. + Screen editServer = onGameThread(() -> minecraft.gui.screen()); + onGameThread(() -> { + ServerData server = new ServerData("Test", "mc.example.com", ServerData.Type.OTHER); + server.incariWisp = new incari.client.net.WispChoice(true, incari.client.net.WispChoice.DEFAULT_PROXY); + minecraft.gui.setScreen(incari.client.net.WispServers.screen(editServer, server, () -> {})); + return null; + }); + sleep(Duration.ofSeconds(2)); + screenshot("screen-wispcraft"); + String widths = onGameThread(() -> { + minecraft.gui.setScreen(editServer); + StringBuilder found = new StringBuilder(); + for (var child : editServer.children()) { + if (child instanceof net.minecraft.client.gui.components.AbstractWidget widget + && widget.getMessage().getString().matches("(Version|Wispcraft): .*")) { + found.append(found.isEmpty() ? "" : ", ") + .append(widget.getMessage().getString()) + .append(" ") + .append(widget.getWidth()); + } + } + return found.toString(); + }); + sleep(Duration.ofSeconds(1)); + screenshot("screen-edit-server-again"); + report.check( + "edit-server buttons after the Wispcraft screen", + widths.matches("Version: [^,]+ 98, Wispcraft: \\w+ 98"), + widths); + onGameThread(() -> { + minecraft.gui.setScreen(new net.minecraft.client.gui.screens.options.SkinCustomizationScreen( + new TitleScreen(), minecraft.options)); + return null; + }); + sleep(Duration.ofSeconds(2)); + screenshot("screen-skin-customisation"); + onGameThread(() -> { + minecraft.gui.setScreen(incari.client.profile.ProfileScreen.from(new TitleScreen())); + return null; + }); + sleep(Duration.ofSeconds(2)); + screenshot("screen-edit-profile"); + report.check("screens drawn", true, "screenshots in incari-smoke/screenshots"); + screenEdits(); + skin(); + } + + /** + * The game's GUI redrawn by a skin ({@code incari.client.ui.Skins}): a flat test skin draws + * buttons' sprites, the separators, the backdrop and one widget whole, on the title screen and + * the video settings; with no skin the game's look is back; a skin that throws is dropped. + */ + private void skin() { + FlatTestSkin skin = new FlatTestSkin(); + onGameThread(() -> { + incari.client.ui.Skins.use(skin); + minecraft.gui.setScreen(new TitleScreen()); + return null; + }); + sleep(Duration.ofSeconds(1)); + screenshot("skin-title"); + onGameThread(() -> { + minecraft.gui.setScreen(new net.minecraft.client.gui.screens.options.VideoSettingsScreen( + shownScreen(), minecraft, minecraft.options)); + return null; + }); + sleep(Duration.ofSeconds(1)); + screenshot("skin-video-settings"); + String drawn = onGameThread(() -> skin.widgets + " widgets, " + skin.sprites + " sprites, " + skin.textures + + " textures, " + skin.backgrounds + " backdrops"); + boolean all = + onGameThread(() -> skin.widgets > 0 && skin.sprites > 0 && skin.textures > 0 && skin.backgrounds > 0); + report.check("skin drew the GUI", all, drawn); + + int before = onGameThread(() -> { + incari.client.ui.Skins.use(null); + return skin.sprites; + }); + sleep(Duration.ofMillis(500)); + int after = onGameThread(() -> skin.sprites); + report.check("no skin, the game's look", before == after, (after - before) + " sprites drawn by the old skin"); + + onGameThread(() -> { + incari.client.ui.Skins.use(new incari.client.ui.GuiSkin() { + @Override + public boolean background( + net.minecraft.client.gui.GuiGraphicsExtractor graphics, Screen screen, float a) { + throw new IllegalStateException("a broken skin"); + } + }); + return null; + }); + sleep(Duration.ofMillis(500)); + boolean dropped = onGameThread(() -> incari.client.ui.Skins.current() == null); + report.check("a skin that throws is dropped", dropped, ""); + screenshot("skin-dropped"); + onGameThread(() -> { + minecraft.gui.setScreen(new TitleScreen()); + return null; + }); + } + + /** A flat look for {@link #skin}, counting what it drew. Render thread. */ + private static final class FlatTestSkin implements incari.client.ui.GuiSkin { + int widgets; + int sprites; + int textures; + int backgrounds; + + @Override + public boolean widget( + net.minecraft.client.gui.GuiGraphicsExtractor graphics, + AbstractWidget widget, + int mouseX, + int mouseY, + float a) { + if (!widget.getMessage().getString().equals("Edited")) { + return false; + } + graphics.fill( + widget.getX(), + widget.getY(), + widget.getX() + widget.getWidth(), + widget.getY() + widget.getHeight(), + widget.isHovered() ? 0xFFFFD54F : 0xFFFFB300); + graphics.centeredText( + Minecraft.getInstance().font, + widget.getMessage(), + widget.getX() + widget.getWidth() / 2, + widget.getY() + (widget.getHeight() - 8) / 2, + 0xFF000000); + incari.client.ui.Skins.cursor(graphics, widget); + widgets++; + return true; + } + + @Override + public boolean sprite( + net.minecraft.client.gui.GuiGraphicsExtractor graphics, + net.minecraft.resources.Identifier sprite, + int x, + int y, + int width, + int height, + int color) { + String path = sprite.getPath(); + if (!path.startsWith("widget/button")) { + return false; + } + int fill = + path.endsWith("_highlighted") ? 0xFF3A7BD5 : path.endsWith("_disabled") ? 0xFF555555 : 0xFF263238; + graphics.fill(x, y, x + width, y + height, fill); + sprites++; + return true; + } + + @Override + public boolean texture( + net.minecraft.client.gui.GuiGraphicsExtractor graphics, + net.minecraft.resources.Identifier texture, + int x, + int y, + int width, + int height, + float u, + float v, + int srcWidth, + int srcHeight, + int textureWidth, + int textureHeight, + int color) { + if (!texture.getPath().endsWith("_separator.png")) { + return false; + } + graphics.fill(x, y, x + width, y + 1, 0xFF3A7BD5); + textures++; + return true; + } + + @Override + public boolean background(net.minecraft.client.gui.GuiGraphicsExtractor graphics, Screen screen, float a) { + graphics.fill(0, 0, screen.width, screen.height, 0xFF101418); + backgrounds++; + return true; + } + } + + /** + * The game's screens changed without a patch each ({@code incari.client.ui.ScreenEdits}): the + * title screen's Realms button removed, Quit moved and a button added, all still so after a + * resize; and a screen of the game's replaced. + */ + private void screenEdits() { + String edited = onGameThread(() -> { + incari.client.ui.ScreenEdits.edit(TitleScreen.class, screen -> { + screen.remove("menu.online"); + AbstractWidget quit = screen.find("menu.quit"); + if (quit != null) { + quit.setPosition(4, 4); + } + screen.add(incari.client.ui.Ui.button( + net.minecraft.network.chat.Component.literal("Edited"), 80, () -> {})) + .setPosition(screen.width() - 84, 4); + }); + incari.client.ui.ScreenEdits.replace( + net.minecraft.client.gui.screens.CreditsAndAttributionScreen.class, + credits -> new net.minecraft.client.gui.screens.GenericMessageScreen( + net.minecraft.network.chat.Component.literal("Replaced by Incari"))); + minecraft.gui.setScreen(new TitleScreen()); + String opened = titleEdits(); + Screen title = shownScreen(); + title.resize(title.width - 20, title.height); + return opened + "; after a resize: " + titleEdits(); + }); + sleep(Duration.ofSeconds(1)); + screenshot("screen-edits-title"); + String expected = "no Realms, Quit at 4,4, 1 added; after a resize: no Realms, Quit at 4,4, 1 added"; + report.check("title screen edited", edited.equals(expected), edited); + + String replaced = onGameThread(() -> { + minecraft.gui.setScreen(new net.minecraft.client.gui.screens.CreditsAndAttributionScreen(shownScreen())); + return shownScreen().getClass().getSimpleName(); + }); + report.check("screen replaced", replaced.equals("GenericMessageScreen"), replaced); + onGameThread(() -> { + minecraft.gui.setScreen(new TitleScreen()); + return null; + }); + } + + /** The screen shown, which a scenario knows there is. Game thread. */ + private Screen shownScreen() { + return java.util.Objects.requireNonNull(minecraft.gui.screen(), "no screen"); + } + + /** What the title screen's edits did, as {@link #screenEdits} expects it. Game thread. */ + private String titleEdits() { + boolean realms = false; + String quit = "no Quit"; + int added = 0; + for (var child : shownScreen().children()) { + if (child instanceof AbstractWidget widget) { + String key = widget.getMessage().getContents() instanceof TranslatableContents label + ? label.getKey() + : widget.getMessage().getString(); + realms |= key.equals("menu.online"); + if (key.equals("menu.quit")) { + quit = "Quit at " + widget.getX() + "," + widget.getY(); + } + added += key.equals("Edited") ? 1 : 0; + } + } + return (realms ? "Realms" : "no Realms") + ", " + quit + ", " + added + " added"; + } + + /** A player saved dead on the server rejoins on the death screen: respawn. */ + private void respawnIfDead() { + if (onGameThread(() -> minecraft.gui.screen() instanceof net.minecraft.client.gui.screens.DeathScreen)) { + onGameThread(() -> { + player().respawn(); + minecraft.gui.setScreen(null); + return null; + }); + } + } + + /** A 64x64 skin in one colour made from {@code name} (red kept even: Eagler sends 7 bits of it). */ + private static int skinColour(String name) { + int hash = name.hashCode() * 0x9E3779B1; + return 0xFF000000 | (((hash >>> 16) & 0xFE) << 16) | (((hash >>> 8) & 0xFF) << 8) | (hash & 0xFF); + } + + private void writeGeneratedSkin(String name, boolean slim) throws java.io.IOException { + Path folder = minecraft.gameDirectory.toPath().resolve("incari").resolve("skin"); + java.nio.file.Files.createDirectories(folder.resolve("library")); + try (com.mojang.blaze3d.platform.NativeImage image = + new com.mojang.blaze3d.platform.NativeImage(64, 64, false)) { + for (int y = 0; y < 64; y++) { + for (int x = 0; x < 64; x++) { + // A slim skin leaves the wide arm's last columns empty (OwnSkin reads its model from them). + boolean wideOnly = x >= 54 && x < 56 && y >= 20 && y < 32; + image.setPixel(x, y, slim && wideOnly ? 0 : skinColour(name)); + } + } + image.writeToFile(folder.resolve("library").resolve("generated.png")); + } + if (slim) { + try (com.mojang.blaze3d.platform.NativeImage cape = + new com.mojang.blaze3d.platform.NativeImage(64, 32, false)) { + for (int y = 0; y < 32; y++) { + for (int x = 0; x < 64; x++) { + cape.setPixel(x, y, 0xFF3060C0); + } + } + cape.writeToFile(folder.resolve("cape.png")); + } + } else { + java.nio.file.Files.deleteIfExists(folder.resolve("cape.png")); + } + java.nio.file.Files.writeString(folder.resolve("skin.properties"), "skin=custom:generated.png\n"); + } + + private static String expectedSkin(String name) { + boolean slim = name.endsWith("A"); + return "custom " + (slim ? "slim" : "wide") + " #" + Integer.toHexString(skinColour(name)) + + (slim ? " with cape #ff3060c0" : " no cape"); + } + + /** How the game will draw {@code name}'s skin: its texture's colour, model and cape. */ + private String skinDescription(String name) { + var connection = minecraft.getConnection(); + if (connection == null) { + return "no connection"; + } + var info = connection.getPlayerInfo(name); + if (info == null) { + return "not in the player list"; + } + net.minecraft.world.entity.player.PlayerSkin skin = info.getSkin(); + String kind = pixel(skin.body().texturePath(), 10, 10); + if (kind == null) { + return "a default skin (" + skin.body().texturePath() + ")"; + } + String cape = skin.cape() == null + ? " no cape" + : " with cape " + pixel(skin.cape().texturePath(), 1, 1); + return "custom " + (skin.model() == net.minecraft.world.entity.player.PlayerModelType.SLIM ? "slim" : "wide") + + " " + kind + cape; + } + + private @org.jspecify.annotations.Nullable String pixel(net.minecraft.resources.Identifier texture, int x, int y) { + if (!texture.getNamespace().equals("incari")) { + return null; + } + var loaded = minecraft.getTextureManager().getTexture(texture); + if (!(loaded instanceof net.minecraft.client.renderer.texture.DynamicTexture dynamic) + || dynamic.getPixels() == null) { + return "(no pixels)"; + } + return "#" + Integer.toHexString(dynamic.getPixels().getPixel(x, y)); + } + + /** Whether the last join translates through Via (the server speaks another version). */ + private boolean viaInPipeline() { + return incari.client.net.ServerConnections.lastJoinedProtocol() + != net.minecraft.SharedConstants.getCurrentVersion().protocolVersion(); + } + + private String versionDescription() { + int protocol = incari.client.net.ServerConnections.lastJoinedProtocol(); + return incari.client.net.ServerVersions.name(protocol) + " (protocol " + protocol + ")" + + (viaInPipeline() ? " through Via" : ""); + } + + private void stayConnected(Duration duration) { + boolean dropped = waitUntil(duration, () -> !inWorld() || minecraft.getConnection() == null); + report.check( + "stay connected for " + duration.toSeconds() + " s", + !dropped, + dropped ? stateDescription() : "still in the world"); + } + + /** A server list ping: handshake, status and ping packets, as the multiplayer screen sends them. */ + private void ping(String address) throws Exception { + ServerData data = smokeServerData(address); + ServerStatusPinger pinger = new ServerStatusPinger(); + pinger.pingServer(data, () -> {}, () -> {}, EventLoopGroupHolder.remote(false)); + boolean answered = waitUntil(Duration.ofSeconds(15), () -> { + pinger.tick(); + return data.motd != null && data.ping >= 0 && data.players != null; + }); + report.check( + "server list ping to " + address, + answered, + answered ? "motd '" + data.motd.getString() + "', " + data.ping + " ms" : "no status reply"); + pinger.removeAll(); + } + + private void connect(String address) { + onGameThread(() -> { + ConnectScreen.startConnecting( + new TitleScreen(), + minecraft, + ServerAddress.parseString(address), + smokeServerData(address), + false, + null); + return null; + }); + } + + /** The dedicated server's list entry: through the Wisp proxy {@code -Pincari.wisp} names, if any. */ + private static ServerData smokeServerData(String address) { + ServerData data = new ServerData("Incari smoke server", address, ServerData.Type.OTHER); + // Via on: the smoke servers run other versions too (ADR 0071). + data.incariVersion = incari.client.net.ServerVersions.AUTO; + String wisp = System.getProperty("incari.smoke.wisp"); + if (wisp != null) { + data.incariWisp = new incari.client.net.WispChoice(true, wisp); + } + return data; + } + + /** How the current connection reaches the server, for the report. */ + private String transportDescription() { + return onGameThread(() -> { + var listener = minecraft.getConnection(); + if (listener == null) { + return "no connection"; + } + var remote = listener.getConnection().getRemoteAddress(); + if (remote instanceof incari.net.wisp.WispAddress) { + return "Wisp to " + remote; + } + return (remote instanceof incari.net.WebSocketAddress ? "a WebSocket to " : "TCP to ") + remote; + }); + } + + /** + * Asks the server to transfer the player to {@code address} (the same server): the client + * disconnects and connects again by itself. A {@code ws://} address travels in the packet's host + * field. The server needs {@code accepts-transfers=true}. + */ + private void transfer(String address) { + Object before = onGameThread(() -> minecraft.getConnection()); + String target = address.contains("://") ? address : address.substring(0, address.lastIndexOf(':')); + String port = address.contains("://") ? "" : " " + address.substring(address.lastIndexOf(':') + 1); + command("transfer \"" + target + "\"" + port); + boolean transferred = waitUntil( + Duration.ofMinutes(1), + () -> minecraft.level != null + && minecraft.player != null + && !java.util.Objects.equals(minecraft.getConnection(), before) + && minecraft.player.tickCount > 20); + String connection = onGameThread(() -> + (java.util.Objects.equals(minecraft.getConnection(), before) ? "the same connection" : "a new one") + + ", player ticks " + (minecraft.player == null ? -1 : minecraft.player.tickCount)); + report.check( + "transfer to " + address, + transferred, + transferred + ? "reconnected by itself over " + transportDescription() + : connection + ", " + stateDescription()); + } + + /** Teleports into another dimension with a command and checks the client follows. */ + private void changeDimension(String dimension) { + command("execute in " + dimension + " run tp @s 0 100 0"); + boolean changed = waitUntil( + Duration.ofMinutes(1), + () -> inWorld() + && level().dimension().identifier().toString().equals(dimension) + && player().tickCount > 20); + report.check( + "change dimension to " + dimension, + changed, + changed ? "the client is in " + dimension : stateDescription()); + if (changed) { + screenshot("dimension-" + dimension.substring(dimension.indexOf(':') + 1)); + } + } + + // ---------------------------------------------------------------------------------------- + // Checks + // ---------------------------------------------------------------------------------------- + + private void waitForTitle() { + // The title screen exists behind the loading overlay; wait until the overlay is gone too. + boolean title = waitUntil( + Duration.ofMinutes(3), + () -> minecraft.gui.screen() instanceof TitleScreen && minecraft.gui.overlay() == null); + report.check("boot to the title screen", title, title ? "" : "screen: " + minecraft.gui.screen()); + screenshot("01-title"); + } + + /** Focuses the window and grabs the mouse, as clicking into the game does. */ + private void takeControl() { + int windowId = onGameThread( + () -> SDLVideo.SDL_GetWindowID(minecraft.getWindow().handle())); + onGameThread(() -> { + minecraft.gui.hud.getChat().setVisibleMessageFilter(message -> { + seenChat.add(message.content().getString()); + return true; + }); + return null; + }); + SdlInjector injector = new SdlInjector(windowId); + input = injector; + injector.focus(); + sleep(Duration.ofMillis(300)); + onGameThread(() -> { + minecraft.mouseHandler.grabMouse(); + return null; + }); + waitUntil(Duration.ofSeconds(5), () -> minecraft.mouseHandler.isMouseGrabbed()); + } + + private void walk() { + Vec3 start = onGameThread(() -> player().position()); + // Space with W climbs the one-block steps the spawn point often faces. + injector().key(44, ' ', true); + holdKey(26, 'w', Duration.ofSeconds(2)); // W + injector().key(44, ' ', false); + Vec3 end = onGameThread(() -> player().position()); + double moved = horizontalDistance(start, end); + report.check("walk (W key)", moved > 1.0, String.format(java.util.Locale.ROOT, "moved %.1f blocks", moved)); + } + + private void jump() { + // Start from the ground: the walk before may have ended mid-climb. + waitUntil(Duration.ofSeconds(3), () -> player().onGround()); + sleep(Duration.ofMillis(200)); + double before = onGameThread(() -> player().getY()); + injector().key(44, ' ', true); // Space + double highest = before; + long until = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(700); + while (System.nanoTime() < until) { + highest = Math.max(highest, onGameThread(() -> player().getY())); + sleep(Duration.ofMillis(20)); + } + injector().key(44, ' ', false); + report.check( + "jump (Space)", + highest - before > 0.5, + String.format(java.util.Locale.ROOT, "rose %.2f blocks", highest - before)); + } + + private void look() { + // The game only turns the player while its window is active, and a real focus change + // from the desktop (someone using the machine) can land after the injected one. + injector().focus(); + sleep(Duration.ofMillis(100)); + float before = onGameThread(() -> player().getYRot()); + for (int i = 0; i < 10; i++) { + injector().look(40, 0); + sleep(Duration.ofMillis(30)); + } + sleep(Duration.ofMillis(200)); + float after = onGameThread(() -> player().getYRot()); + boolean active = onGameThread(() -> minecraft.isWindowActive()); + report.check( + "look around (mouse motion)", + Math.abs(after - before) > 5, + "turned " + Math.round(after - before) + " degrees" + (active ? "" : ", window not active")); + } + + private void breakAndPlace() { + // Aim at the ground a little ahead: not the block the player stands in, which a new + // block couldn't be placed back into. (Looking itself was checked with mouse input.) + onGameThread(() -> { + player().setXRot(60.0F); + return null; + }); + sleep(Duration.ofMillis(300)); + BlockPos target = onGameThread( + () -> minecraft.hitResult instanceof BlockHitResult hit && hit.getType() == HitResult.Type.BLOCK + ? hit.getBlockPos() + : null); + if (target == null) { + report.fail("break a block (left mouse)", "not looking at a block"); + return; + } + String before = onGameThread(() -> blockName(level().getBlockState(target))); + injector().mouseButton(1, true); + boolean broken = waitUntil( + Duration.ofSeconds(8), () -> level().getBlockState(target).isAir()); + injector().mouseButton(1, false); + report.check("break a block (left mouse)", broken, before + " at " + target.toShortString()); + if (!broken) { + return; + } + // Snow and sand don't drop by hand, and the spawn biome varies: get a block to place + // with a command instead, typed through chat like a player would. + command("give @s minecraft:dirt 8"); + boolean given = waitUntil( + Duration.ofSeconds(5), + () -> !player().getInventory().getSelectedItem().isEmpty()); + report.check( + "run a command (/give)", + given, + onGameThread(() -> player().getInventory().getSelectedItem().toString())); + + // The block below the hole is now the target; place into the hole. + sleep(Duration.ofMillis(300)); + injector().mouseButton(3, true); + sleep(Duration.ofMillis(100)); + injector().mouseButton(3, false); + boolean placed = waitUntil( + Duration.ofSeconds(3), () -> !level().getBlockState(target).isAir()); + report.check( + "place a block (right mouse)", placed, onGameThread(() -> blockName(level().getBlockState(target)))); + } + + /** + * Schematics (ADR 0066): the igloo's top, a structure file of the game's own, chosen in the file + * chooser and drawn as ghosts where the player stands; then the same structure placed there by + * the game, and the ghosts gone. + */ + private void schematicsSteps(incari.framework.ModuleSystem system) throws Exception { + byte[] igloo; + try (var in = SmokeTest.class.getClassLoader().getResourceAsStream("data/minecraft/structure/igloo/top.nbt")) { + igloo = in == null ? null : in.readAllBytes(); + } + report.check("the igloo's structure file is there to load", igloo != null, ""); + if (igloo == null) { + return; + } + Path folder = minecraft.gameDirectory.toPath().resolve("schematics"); + Files.createDirectories(folder); + Files.write(folder.resolve("igloo_top.nbt"), igloo); + serverCommands( + "execute as @p at @s run fill ~-8 ~-1 ~-4 ~12 ~-1 ~18 stone", + "execute as @p at @s run fill ~-8 ~ ~-4 ~12 ~10 ~18 air", + "execute as @p at @s run tp @s ~3 ~ ~14 180 20"); + sleep(Duration.ofSeconds(1)); + incari.framework.Module schematics = module(system, "schematics"); + onGameThread(() -> { + schematics.settings().resetAll(); + schematics.setEnabled(true); + // Placed at the player's feet; the player then steps back to see it. + ((incari.framework.setting.ActionSetting) java.util.Objects.requireNonNull( + schematics.settings().get("choose"))) + .run(); + return null; + }); + sleep(Duration.ofMillis(500)); + screenshot("visual-schematics-chooser"); + // The player stood where it's placed: back there for the load, then away to look. + serverCommands("execute as @p at @s run tp @s ~-3 ~ ~-14"); + sleep(Duration.ofMillis(300)); + clickNested("Load"); + boolean closed = waitUntil(Duration.ofSeconds(5), () -> onGameThread(() -> minecraft.gui.screen() == null)); + report.check("choosing a file closes the chooser", closed, stateDescription()); + serverCommands("execute as @p at @s run tp @s ~3 ~ ~14 180 20"); + boolean ghosts = + waitUntil(Duration.ofSeconds(5), () -> onGameThread(incari.client.modules.ModuleGhosts::quads) > 0); + report.check( + "the schematic's ghosts are meshed", + ghosts, + onGameThread(incari.client.modules.ModuleGhosts::quads) + " quads"); + sleep(Duration.ofMillis(500)); + screenshot("visual-schematics-ghosts"); + + serverCommands("execute as @p at @s run place template minecraft:igloo/top ~-3 ~ ~-14"); + boolean built = + waitUntil(Duration.ofSeconds(8), () -> onGameThread(incari.client.modules.ModuleGhosts::quads) == 0); + report.check( + "blocks built where it wants them stop being ghosts", + built, + onGameThread(incari.client.modules.ModuleGhosts::quads) + " quads"); + serverCommands("execute as @p at @s run setblock ~-3 ~ ~-14 minecraft:gold_block"); + sleep(Duration.ofSeconds(1)); + screenshot("visual-schematics-built"); + onGameThread(() -> { + schematics.setEnabled(false); + return null; + }); + } + + /** + * Clicks the first widget labelled {@code label} anywhere on the shown screen, in lists too, + * with injected pointer events at its centre. + */ + private void clickNested(String label) { + float[] centre = onGameThread(() -> { + Screen screen = minecraft.gui.screen(); + AbstractWidget widget = screen == null ? null : findWidget(screen.children(), label); + if (widget == null) { + return null; + } + var window = minecraft.getWindow(); + float toWindowX = (float) window.getScreenWidth() / window.getGuiScaledWidth(); + float toWindowY = (float) window.getScreenHeight() / window.getGuiScaledHeight(); + return new float[] { + (widget.getX() + widget.getWidth() / 2.0F) * toWindowX, + (widget.getY() + widget.getHeight() / 2.0F) * toWindowY + }; + }); + if (centre == null) { + report.fail("click " + label, "no such widget on " + stateDescription()); + return; + } + injector().moveTo(centre[0], centre[1]); + sleep(Duration.ofMillis(150)); + injector().mouseButton(1, true); + sleep(Duration.ofMillis(80)); + injector().mouseButton(1, false); + } + + private static @Nullable AbstractWidget findWidget( + java.util.List children, + String label) { + for (var child : children) { + if (child instanceof AbstractWidget widget + && widget.getMessage().getString().equals(label)) { + return widget; + } + if (child instanceof net.minecraft.client.gui.components.events.ContainerEventHandler container) { + AbstractWidget found = findWidget(container.children(), label); + if (found != null) { + return found; + } + } + } + return null; + } + + /** + * Clicks the button whose label has this translation key, with injected pointer events at its + * centre: the same path as a player clicking a menu. + */ + private void clickButton(String translationKey) { + float[] centre = buttonCentre(translationKey); + if (centre == null) { + report.fail("click " + translationKey, "no such button on " + stateDescription()); + return; + } + injector().moveTo(centre[0], centre[1]); + sleep(Duration.ofMillis(150)); + injector().mouseButton(1, true); + sleep(Duration.ofMillis(80)); + injector().mouseButton(1, false); + } + + /** The pointer over the shown screen's button labelled {@code translationKey}, if it has one. */ + private void hoverButton(String translationKey) { + float[] centre = buttonCentre(translationKey); + if (centre != null) { + injector().moveTo(centre[0], centre[1]); + } + } + + /** The centre in window coordinates of the shown screen's button labelled {@code translationKey}. */ + private float @Nullable [] buttonCentre(String translationKey) { + return onGameThread(() -> { + if (minecraft.gui.screen() == null) { + return null; + } + for (var child : minecraft.gui.screen().children()) { + if (child instanceof AbstractWidget widget + && ((widget.getMessage().getContents() instanceof TranslatableContents label + && label.getKey().equals(translationKey)) + // An Incari button's label is literal text. + || widget.getMessage().getString().equals(translationKey))) { + // GUI units to window coordinates: the GUI spans the whole window. + var window = minecraft.getWindow(); + float toWindowX = (float) window.getScreenWidth() / window.getGuiScaledWidth(); + float toWindowY = (float) window.getScreenHeight() / window.getGuiScaledHeight(); + return new float[] { + (widget.getX() + widget.getWidth() / 2.0F) * toWindowX, + (widget.getY() + widget.getHeight() / 2.0F) * toWindowY + }; + } + } + return null; + }); + } + + /** Types a command into chat and sends it. */ + private void command(String command) { + injector().tap(56, '/'); // Slash opens chat with "/" typed + waitUntil(Duration.ofSeconds(3), () -> minecraft.gui.screen() instanceof ChatScreen); + sleep(Duration.ofMillis(200)); + injector().text(command); + sleep(Duration.ofMillis(200)); + injector().tap(40, 0x0D); // Enter + waitUntil(Duration.ofSeconds(3), () -> minecraft.gui.screen() == null); + } + + private void inventory() { + injector().tap(8, 'e'); // E + boolean open = waitUntil(Duration.ofSeconds(3), () -> minecraft.gui.screen() instanceof InventoryScreen); + report.check("open the inventory (E)", open, ""); + if (open) { + screenshot("03-inventory"); + injector().tap(41, 0x1B); // Escape + report.check( + "close the inventory (Escape)", + waitUntil(Duration.ofSeconds(3), () -> minecraft.gui.screen() == null), + ""); + } + } + + private void chat(String message) { + injector().tap(23, 't'); // T + boolean open = waitUntil(Duration.ofSeconds(3), () -> minecraft.gui.screen() instanceof ChatScreen); + if (!open) { + report.fail("chat (T, typing, Enter)", "the chat screen didn't open"); + return; + } + sleep(Duration.ofMillis(200)); + injector().text(message); + sleep(Duration.ofMillis(200)); + injector().tap(40, 0x0D); // Enter + boolean echoed = waitUntil(Duration.ofSeconds(5), () -> chatContains(message)); + report.check("chat (T, typing, Enter)", echoed, echoed ? "the server echoed it" : "no echo"); + if (echoed) { + screenshot("04-chat"); + } + } + + private void sound() { + String channels = onGameThread(() -> minecraft.getSoundManager().getChannelDebugString()); + report.check("sound engine", !channels.isBlank(), channels); + } + + private void lan(int waitForJoinSeconds) throws Exception { + int port = LAN_PORT; + boolean published = onGameThread(() -> { + IntegratedServer server = minecraft.getSingleplayerServer(); + if (server == null) { + return false; + } + // Vanilla LAN worlds always authenticate guests with Mojang, which offline test + // clients can't: the same as online-mode=false on a dedicated server. + server.setUsesAuthentication(false); + return server.publishServer(MinecraftServer.MultiplayerScope.LAN, false, port); + }); + report.check("open to LAN", published, "port " + port); + if (!published) { + return; + } + + // A server list ping: handshake, status and ping packets through PlatformSocketChannel. + ServerData data = new ServerData("LAN", "127.0.0.1:" + port, ServerData.Type.OTHER); + ServerStatusPinger pinger = new ServerStatusPinger(); + pinger.pingServer(data, () -> {}, () -> {}, EventLoopGroupHolder.remote(false)); + boolean answered = waitUntil(Duration.ofSeconds(15), () -> { + pinger.tick(); + return data.motd != null && data.ping >= 0 && data.players != null; + }); + report.check( + "server list ping over the platform transport", + answered, + answered ? "motd '" + data.motd.getString() + "', " + data.ping + " ms" : "no status reply"); + pinger.removeAll(); + + if (waitForJoinSeconds > 0) { + boolean joined = waitUntil(Duration.ofSeconds(waitForJoinSeconds), () -> playersOnLanServer() > 1); + report.check("a second client joined the LAN world", joined, ""); + if (joined) { + boolean greeted = waitUntil(Duration.ofSeconds(30), () -> chatContains("hello from the second client")); + report.check("chat from the second client arrived", greeted, ""); + screenshot("05-lan-guest"); + waitUntil(Duration.ofSeconds(60), () -> playersOnLanServer() == 1); + } + } + } + + // ---------------------------------------------------------------------------------------- + // Helpers + // ---------------------------------------------------------------------------------------- + + private net.minecraft.client.player.LocalPlayer player() { + net.minecraft.client.player.LocalPlayer player = minecraft.player; + if (player == null) { + throw new IllegalStateException("Not in a world"); + } + return player; + } + + private net.minecraft.client.multiplayer.ClientLevel level() { + net.minecraft.client.multiplayer.ClientLevel level = minecraft.level; + if (level == null) { + throw new IllegalStateException("Not in a world"); + } + return level; + } + + private int playersOnLanServer() { + IntegratedServer server = minecraft.getSingleplayerServer(); + return server == null ? 0 : server.getPlayerCount(); + } + + /** What the game shows right now, for a failed check's report line. */ + private String stateDescription() { + return onGameThread(() -> "screen " + + (minecraft.gui.screen() == null + ? "none" + : minecraft.gui.screen().getClass().getSimpleName()) + + ", player " + (minecraft.player == null ? "none" : "present") + + ", level " + (minecraft.level == null ? "none" : "present") + + ", connection " + (minecraft.getConnection() == null ? "none" : "present")); + } + + private boolean inWorld() { + return onGameThread( + () -> minecraft.player != null && minecraft.level != null && minecraft.gui.screen() == null); + } + + private boolean chatContains(String text) { + return seenChat.stream().anyMatch(line -> line.contains(text)); + } + + private void holdKey(int scancode, int keyCode, Duration duration) { + injector().key(scancode, keyCode, true); + sleep(duration); + injector().key(scancode, keyCode, false); + sleep(Duration.ofMillis(300)); + } + + private SdlInjector injector() { + SdlInjector current = input; + if (current == null) { + throw new IllegalStateException("takeControl() first"); + } + return current; + } + + private void screenshot(String name) { + File folder = directory.toFile(); + onGameThread(() -> { + Screenshot.grab(folder, name + ".png", minecraft.gameRenderer.mainRenderTarget(), 1, message -> {}); + return null; + }); + sleep(Duration.ofMillis(500)); + } + + private static String blockName(BlockState state) { + return state.getBlock().getName().getString(); + } + + private static double horizontalDistance(Vec3 a, Vec3 b) { + double dx = a.x - b.x; + double dz = a.z - b.z; + return Math.sqrt(dx * dx + dz * dz); + } + + /** + * Polls {@code condition} on the game thread until it holds or the time runs out. The game + * thread can be busy for a long time (generating a world), so a slow answer isn't a failure: + * the same query is waited on for a while instead of queueing new ones. Only a while: leaving a + * server drops the game's queued tasks, so a query asked just before a transfer never answers. + */ + private boolean waitUntil(Duration timeout, BooleanSupplier condition) { + long deadline = System.nanoTime() + timeout.toNanos(); + while (System.nanoTime() < deadline) { + java.util.concurrent.CompletableFuture answer = minecraft.submit(condition::getAsBoolean); + try { + long remaining = Math.max(1, deadline - System.nanoTime()); + if (answer.get(Math.min(remaining, QUERY_PATIENCE.toNanos()), TimeUnit.NANOSECONDS)) { + return true; + } + } catch (java.util.concurrent.TimeoutException e) { + answer.cancel(false); + continue; + } catch (Exception e) { + throw new IllegalStateException("A smoke test check failed on the game thread", e); + } + sleep(Duration.ofMillis(100)); + } + return false; + } + + /** Runs {@code task} on the game thread and waits for its result, however long the game is busy. */ + private T onGameThread(Callable task) { + if (minecraft.isSameThread()) { + // Already on it (a waitUntil condition calling a helper): queueing would deadlock. + try { + return task.call(); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + try { + return minecraft + .submit(() -> { + try { + return task.call(); + } catch (Exception e) { + throw new IllegalStateException(e); + } + }) + .get(5, TimeUnit.MINUTES); + } catch (Exception e) { + throw new IllegalStateException("A smoke test step failed on the game thread", e); + } + } + + private static void sleep(Duration duration) { + try { + Thread.sleep(duration); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted", e); + } + } +} diff --git a/incari-client/files/app-desktop/src/main/java/incari/app/desktop/smoke/WorldgenServer.java b/incari-client/files/app-desktop/src/main/java/incari/app/desktop/smoke/WorldgenServer.java new file mode 100644 index 0000000..cf11f5b --- /dev/null +++ b/incari-client/files/app-desktop/src/main/java/incari/app/desktop/smoke/WorldgenServer.java @@ -0,0 +1,79 @@ +package incari.app.desktop.smoke; + +import incari.client.startup.CriterionCodecs; +import incari.client.world.BiomeCells; +import incari.client.world.DensityBranches; +import incari.client.world.Heights; +import incari.client.world.SurfaceWrites; +import incari.platform.api.Platforms; +import incari.platform.desktop.DesktopPlatform; +import incari.platform.desktop.DesktopStorage; +import java.io.IOException; +import java.io.OutputStream; +import java.io.PipedInputStream; +import java.io.PipedOutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The game's dedicated server on the desktop platform, with the browser build's world generation + * changes (ADR 0041) on or off ({@code -Dincari.worldgen=on|off}): run twice on one seed, the + * worlds it saves must hold the same chunks ({@code tools/worldgen/compare.py} compares the region + * files). {@code -Dincari.worldgen.script=} types its lines into the server's console, a + * line {@code sleep } waiting instead. Arguments are the server's own + * ({@code --nogui --universe }). + */ +public final class WorldgenServer { + + private WorldgenServer() {} + + public static void main(String[] args) throws Exception { + boolean on = "on".equals(System.getProperty("incari.worldgen", "off")); + Logger logger = LoggerFactory.getLogger("Platform"); + DesktopStorage storage = new DesktopStorage(".", "assets", null); + Platforms.install(new DesktopPlatform(storage, (level, message, error) -> logger.info(message, error), false)); + SurfaceWrites.setEnabled(on); + BiomeCells.setEnabled(on); + BiomeCells.setVerify(on && Boolean.getBoolean("incari.worldgen.verify")); + Heights.setEnabled(on); + CriterionCodecs.setEnabled(on); + DensityBranches.setEnabled(on); + logger.info("[Incari] World generation changes (ADRs 0041, 0042): {}", on ? "on" : "off"); + String script = System.getProperty("incari.worldgen.script"); + if (script != null) { + typeInto(List.copyOf(Files.readAllLines(Path.of(script)))); + } + net.minecraft.server.Main.main(args); + } + + /** Types {@code lines} into the server's console, from a thread of its own. */ + private static void typeInto(List lines) throws IOException { + PipedOutputStream console = new PipedOutputStream(); + System.setIn(new PipedInputStream(console)); + Thread typist = new Thread(() -> type(lines, console), "Worldgen script"); + typist.setDaemon(true); + typist.start(); + } + + private static void type(List lines, OutputStream console) { + try { + for (String line : lines) { + if (line.isBlank() || line.startsWith("#")) { + continue; + } + if (line.startsWith("sleep ")) { + Thread.sleep(Long.parseLong(line.substring(6).trim()) * 1000); + continue; + } + console.write((line + "\n").getBytes(StandardCharsets.UTF_8)); + console.flush(); + } + } catch (IOException | InterruptedException e) { + System.err.println("[Incari] The worldgen script stopped: " + e); + } + } +} diff --git a/incari-client/files/app-desktop/src/test/java/incari/app/desktop/smoke/LayoutRulesTest.java b/incari-client/files/app-desktop/src/test/java/incari/app/desktop/smoke/LayoutRulesTest.java new file mode 100644 index 0000000..d6c055d --- /dev/null +++ b/incari-client/files/app-desktop/src/test/java/incari/app/desktop/smoke/LayoutRulesTest.java @@ -0,0 +1,93 @@ +package incari.app.desktop.smoke; + +import static org.assertj.core.api.Assertions.assertThat; + +import incari.app.desktop.smoke.LayoutRules.Box; +import java.util.List; +import org.junit.jupiter.api.Test; + +class LayoutRulesTest { + + private static final Box DONE = new Box("Done", 10, 10, 110, 30); + private static final Box RESET = new Box("Reset", 114, 10, 164, 30); + + @Test + void controlsSideBySideAreFine() { + Box label = new Box("Done text", 45, 16, 75, 25); + assertThat(LayoutRules.problems(320, 240, List.of(DONE, RESET), List.of(label))) + .isEmpty(); + } + + @Test + void widgetsOverEachOtherFail() { + Box over = new Box("Over", 100, 10, 150, 30); + assertThat(LayoutRules.problems(320, 240, List.of(DONE, over), List.of())) + .singleElement() + .asString() + .contains("Done", "overlaps", "Over"); + } + + @Test + void widgetsTouchingEdgesAreFine() { + Box next = new Box("Next", 110, 10, 160, 30); + assertThat(LayoutRules.problems(320, 240, List.of(DONE, next), List.of())) + .isEmpty(); + } + + @Test + void aWidgetOffTheScreenFails() { + Box wide = new Box("Wide", 200, 10, 340, 30); + assertThat(LayoutRules.problems(320, 240, List.of(wide), List.of())) + .singleElement() + .asString() + .contains("runs off the screen"); + } + + @Test + void textPastItsButtonFails() { + Box long_ = new Box("A very long label", 14, 16, 130, 25); + assertThat(LayoutRules.problems(320, 240, List.of(DONE, RESET), List.of(long_))) + .anyMatch(problem -> problem.contains("runs past Done")); + } + + @Test + void itsShadowMayReachAUnitPast() { + Box snug = new Box("Snug", 12, 16, 111, 26); + assertThat(LayoutRules.problems(320, 240, List.of(DONE), List.of(snug))).isEmpty(); + } + + @Test + void aLabelRunningIntoAControlFails() { + Box label = new Box("A row's long label", 0, 50, 140, 59); + Box toggle = new Box("Toggle", 120, 45, 170, 65); + assertThat(LayoutRules.problems(320, 240, List.of(toggle), List.of(label))) + .singleElement() + .asString() + .contains("runs into Toggle"); + } + + @Test + void textOverTextFails() { + Box title = new Box("Title", 100, 20, 200, 29); + Box status = new Box("Status", 120, 24, 220, 33); + assertThat(LayoutRules.problems(320, 240, List.of(), List.of(title, status))) + .singleElement() + .asString() + .contains("overlaps"); + } + + @Test + void emptyBoxesAreIgnored() { + Box hidden = new Box("Hidden", 50, 50, 50, 70); + assertThat(LayoutRules.problems(320, 240, List.of(DONE, hidden), List.of())) + .isEmpty(); + } + + @Test + void aScrollingScreenMayRunPastTheBottom() { + Box low = new Box("Low", 10, 230, 110, 250); + assertThat(LayoutRules.problems(320, 240, List.of(low), List.of())).hasSize(1); + assertThat(LayoutRules.problems(320, 240, true, List.of(low), List.of())) + .isEmpty(); + } +} diff --git a/incari-client/files/app-web/AGENTS.md b/incari-client/files/app-web/AGENTS.md new file mode 100644 index 0000000..1a8a38e --- /dev/null +++ b/incari-client/files/app-web/AGENTS.md @@ -0,0 +1,16 @@ +# app-web + +- Never commit or publish build output (`.wasm`, `.js` bundles, HTML with the game in it), and + never link to a hosted build. +- The page's TypeScript (`src/main/ts`) runs in the browser with its types stripped + (`:app-web:pageScripts`, Node's `stripTypeScriptTypes`), with no bundler: erasable syntax only, + relative imports end in `.ts`, and anything testable goes in a module without side effects + (`loader.ts`, `cache-policy.ts`) rather than `boot.ts` or `sw.ts`. +- TypeScript: no `any`; every eslint-disable comment says why; only erasable syntax (no enums, + namespaces or parameter properties). +- The entry point sets library properties before anything reads them (`LibraryDefaults`: Netty in + heap mode, JOML); keep new ones there. +- Test: `npm run check`, and `./gradlew :app-web:test` (`MemoryParityTest`: the game's vertex and + image bytes over web-classlib's memory against LWJGL's; needs `./incari setup`). +- `@Async` methods complete with a value that says they failed and throw in Java, never through + `AsyncCallback.error`, which crashes the page (`platform-web/AGENTS.md`, `probes/FetchFailureProbe`). diff --git a/incari-client/files/app-web/README.md b/incari-client/files/app-web/README.md new file mode 100644 index 0000000..c89a722 --- /dev/null +++ b/incari-client/files/app-web/README.md @@ -0,0 +1,141 @@ +# app-web: the browser build + +The game in a browser tab. `WebMain` installs `platform-web` and the WebGL2 backend, then starts the +game's own `Main`. `tools/webbuild` compiles it with TeaVM into two builds (ADR 0036): + +| Build | Output | Threads | Runs in | +| --- | --- | --- | --- | +| Fast (`-Pteavm.fast`) | `build/teavm-fast/` | JSPI | Chrome/Edge 137+, Firefox 153+ | +| Compatible (default) | `build/teavm/` | TeaVM coroutines: slower, twice the size | anything with WebAssembly GC, Safari too | +| Rust (experimental) | `build/rust/` | Web Workers (Horizon's own) | WebGPU: Chrome and Edge 113+ ([`rust/`](../rust/README.md), ADR 0068) | + +`-Pteavm.fast` also makes `browserCheck`, `screenshotDiff` and `benchmark` use Fast. The page offers +the builds that are compiled; delete a build's folder to leave it out. Rust isn't a TeaVM build: +`./incari build --only rust` writes it, and the page opens its own page, `rust/index.html`, with its +own files and service worker. + +## Tasks + +```sh +./gradlew :app-web:teavm # compile (~10 minutes); -Pteavm.release for an optimized build +./gradlew :app-web:serve # serve on http://localhost:8080/ +./gradlew :app-web:browserCheck # run headless until the game loop ticks +./gradlew :app-web:shaders # translate shaders only (seconds) +./gradlew :app-web:buildManifest # page scripts, asset pack, build.json (seconds) +./gradlew :app-web:checkDownloadSize # hold the download to download-budget.properties +./gradlew :app-web:screenshotDiff # desktop vs browser renders of fixed scenes (ADR 0012) +./gradlew :app-web:benchmark # profiler figures against a baseline (docs/benchmark.md) +``` + +Editing the page or its scripts needs no recompile: `serve` and `browserCheck` rebuild the manifest +and serve the page's files directly. + +## Page options + +| Option | Effect | +| --- | --- | +| `?build=fast` / `compatible` / `rust` | Pick a build, skipping the loading screen's choice. Rust's page gets the other options (Horizon reads `?args=`) | +| `?server=ws://host:port` | Join that server once the game starts | +| `?via=auto` / `off` / `1.8.9` | Via for that join (ADR 0071); without it, a new entry has Via off | +| `?name=` | Offline player name; skips Edit Profile | +| `?world=&seed=` | Create or open a singleplayer world | +| `?options=` | Start with that options file, fetched from beside the page | +| `?online=`, `?updates=on` | Another online service; show the update notice in a dev build | +| `?profile`, `?overlay` | Profiler collecting from the start; its overlay (F9 in game) | +| `?tier=`, `?particles=` | Force a quality tier | +| `?sw=off` | No service worker (and unregister it) | +| `?netwake=timers` | A server message's connection thread waits for TeaVM's timer, which play delays ~35 ms, instead of running as the message comes (ADR 0075) | +| `?wakeups=channel` / `timers` | The game's threads always wake through a `MessageChannel`; or always on the page's own timers. By default they use the page's timers while visible and a worker's timer while hidden, so a background tab still answers servers (ADR 0072) | +| `?fchord=on` / `off` | F then a digit as a function key; on by default only on ChromeOS | +| `?renderer=headless` | Run the game loop without drawing | +| `?shaders=eager` | Link every WebGL program at start-up | +| `?multidraw=off`, `?drawcensus`, `?gpucensus` | Compare terrain drawing; count draws | +| `?=game` (or `off`, `all`) | Turn one optimization off to compare it. `WebMain` lists every switch | + +## Driving the page in checks + +`browserCheck` can act like a player over the DevTools protocol, from inline steps or a script: + +```sh +./gradlew :app-web:browserCheck -Pbrowser.steps="shot:build/title.png;click:0.5,0.45;sleep:2000" +./gradlew :app-web:browserCheck -Pbrowser.steps=@browser-checks/input.steps +``` + +Steps cover screenshots, mouse, keys (`key:F3+KeyB`), typing and input methods, clipboard, viewport +size, page assertions (`holds:`, `until:`), reloads, file choosers, downloads, dropped files, test +resource packs and RCON commands on a test server. `BrowserCheck.runStep` lists them all. The +scripts and the checklist for what needs a real browser are in [`browser-checks/`](browser-checks/README.md). + +## Code map + +| Where | What | +| --- | --- | +| `WebMain` | Entry point and page options | +| `WebStorage` | The game's files under `/incari`, kept by `platform-web` (ADR 0011) | +| `ClientJar` | Mounts the client jar's resources read-only; the storage worker downloads it once | +| `WebAssets` | Sound list and pack metadata from the asset index; sounds fetched when first played (ADR 0013, 0037) | +| `WebShaders`, `AssetPack` | The build's translated shaders and asset pack (ADR 0014) | +| `LoaderPage`, `Fetch` | Loading-screen steps; downloads before the game starts | +| `headless/` | A graphics device that draws nothing | +| `src/main/web/index.html` | The loader page | +| `src/main/ts/` | `boot.ts` (loader), `loader.ts` (its decisions), `jspi.ts`, `features.ts` (feature detection), `sw.ts` and `cache-policy.ts` (service worker), `offline.ts` (single-file shim, ADR 0057) | + +## Packaging + +- `build.json` lists every file with size and SHA-256, so the service worker keeps each file until + it changes. `incari.pack` holds build-time data (shaders, sprites, Via mappings). See ADR 0014. +- `./incari build` writes a folder for a static web server (ADR 0028); `--html` writes one HTML + file (ADR 0057). Neither may be shared ([`docs/self-hosting.md`](../docs/self-hosting.md)). + +## Download budget + +`download-budget.properties` limits what a player downloads at start (gzip level 9, plus raw module +size; brotli reported). Every file is classed `download`, `debug`, `report` or `vendor` (Mojang's +jar, measured but not ours). An unclassed file fails the check. Raise a limit in the PR that needs +it, and say why. CI doesn't compile the browser build, so it only unit-tests the budget logic. + +```sh +./gradlew :app-web:checkDownloadSize -PdownloadSize.skipBuild # measure the existing build +``` + +## Screenshot diffs + +Renders `screenshot-scenes/scenes.txt` on the desktop (OpenGL, the reference) and in headless +Chromium (WebGL2), on a fresh local server, and compares each pair by SSIM. Fails under a scene's +threshold, on any WebGL error, or on a skipped pipeline. Needs a display and GPU, so it runs +locally, not in CI. Output goes to `build/screenshots/` and is never committed. + +```sh +./gradlew :app-web:screenshotDiff -Pscreenshots.skipBuild -Pscreenshots.only=sky,gui +./gradlew :app-web:screenshotDiff -Pscreenshots.reuseDesktop # browser side only +./gradlew :app-web:screenshotDiff -Pscreenshots.gpu=swiftshader # software WebGL, lower scores +``` + +Ports: `-Pscreenshots.port` (18210) and the five above it. The benchmark uses 18310 and four above. + +## Probes + +A full compile takes ten minutes. To test one behaviour of TeaVM or the class library, compile a +small program instead (seconds): + +```sh +app-web/probes/run.sh [-Pteavm.fast] +``` + +[`probes/README.md`](probes/README.md) lists them. A one-off program runs the same way: +`./gradlew :app-web:browserCheck -Pteavm.main=Probe -Pteavm.classpath=

"-Pbrowser.expect=probe done"`. + +## Invariants + +- **Builds are never committed or published.** The dev server binds to localhost only. +- **Mojang's assets and client jar are never copied into the build.** The page fetches them, and + the storage worker keeps the jar outside the game's heap. +- **TypeScript is strict**, lint-clean, and uses only syntax Node's type stripping can erase, so + tests run straight from source. + +## How to test + +```sh +npm ci && npm run check +./gradlew :app-web:browserCheck # needs Chromium (Playwright's, or INCARI_CHROME) +``` diff --git a/incari-client/files/app-web/benchmark/baseline.properties b/incari-client/files/app-web/benchmark/baseline.properties new file mode 100644 index 0000000..8be6ef3 --- /dev/null +++ b/incari-client/files/app-web/benchmark/baseline.properties @@ -0,0 +1,230 @@ +# The benchmark's baseline (ADR 0021; tools/webbuild's PerfBaseline). ./gradlew +# :app-web:benchmark fails when a figure is worse than this machine's recorded one by more than +# its rule allows: both more than the percentage and more than the absolute amount, so noise in a +# small figure doesn't fail a run. Figures without a rule are recorded but never fail. +# +# Re-record a machine with -Pbenchmark.updateBaseline (and say why in the pull request). Figures +# are machine-specific: -Pbenchmark.machine names the machine, and only its own lines are compared. +# They're recorded on the release build (-Pteavm.release, ADR 0025); the lobby's from then +# on are of the whole scene (its floor and signs, built once its chunks have loaded). +# docs/benchmark.md lists the reference machines. +# +# rule.
= + +# Frame rate and frame time. +rule.fpsMedian=higher 5 1 +rule.fpsLow1=higher 15 3 +rule.frameP99Millis=lower 15 2 +# Where the frame's time goes (milliseconds a frame). +rule.tickMillis=lower 20 0.5 +rule.extractMillis=lower 20 0.5 +rule.renderMillis=lower 20 0.5 +rule.gpuMillis=lower 20 0.5 +# Draw calls: steady for a fixed scene, so tighter. +rule.drawCalls=lower 10 5 +rule.terrainDrawCalls=lower 10 3 +# Memory, in megabytes, and garbage collection pauses. +rule.heapMaxMB=lower 10 16 +rule.nativeMaxMB=lower 10 16 +rule.gcMaxPauseMillis=lower 30 4 +# Loading (milliseconds from navigation) and the download (bytes, gzip). +rule.coldTitleMillis=lower 20 500 +rule.warmTitleMillis=lower 20 500 +rule.joinMillis=lower 20 500 +rule.rejoinMillis=lower 20 500 +rule.gzipBytes=lower 2 10000 + +desktop.combat.drawCalls=84.27 +desktop.combat.extractMillis=0.40 +desktop.combat.fpsLow1=46.54 +desktop.combat.fpsMean=60.00 +desktop.combat.fpsMedian=59.24 +desktop.combat.frameP99Millis=20.69 +desktop.combat.frames=2430 +desktop.combat.gcCount=33 +desktop.combat.gcMaxPauseMillis=1.81 +desktop.combat.gcTotalMillis=25.36 +desktop.combat.gpuMillis=0.87 +desktop.combat.heapLiveMB=344.91 +desktop.combat.heapMaxMB=409.06 +desktop.combat.meshQueueMax=0 +desktop.combat.meshQueueMean=0 +desktop.combat.nativeLiveMB=52.46 +desktop.combat.nativeMaxMB=74.44 +desktop.combat.poolMillis=0 +desktop.combat.renderMillis=0.69 +desktop.combat.slow1.extractMillis=0.43 +desktop.combat.slow1.frameMillis=5.75 +desktop.combat.slow1.intervalMillis=21.49 +desktop.combat.slow1.poolLateMillis=0 +desktop.combat.slow1.poolMillis=0 +desktop.combat.slow1.renderMillis=1.21 +desktop.combat.slow1.tickMillis=4.04 +desktop.combat.terrainDrawCalls=4 +desktop.combat.terrainSections=521 +desktop.combat.tickMillis=1.30 +desktop.download.gzipBytes=20397515 +desktop.flythrough.drawCalls=79.69 +desktop.flythrough.extractMillis=0.38 +desktop.flythrough.fpsLow1=45.74 +desktop.flythrough.fpsMean=60.00 +desktop.flythrough.fpsMedian=59.68 +desktop.flythrough.frameP99Millis=20.86 +desktop.flythrough.frames=3340 +desktop.flythrough.gcCount=83 +desktop.flythrough.gcMaxPauseMillis=5.48 +desktop.flythrough.gcTotalMillis=88.74 +desktop.flythrough.gpuMillis=0.73 +desktop.flythrough.heapLiveMB=349.90 +desktop.flythrough.heapMaxMB=524.32 +desktop.flythrough.meshQueueMax=76 +desktop.flythrough.meshQueueMean=4.27 +desktop.flythrough.nativeLiveMB=51.90 +desktop.flythrough.nativeMaxMB=74.44 +desktop.flythrough.poolMillis=1.58 +desktop.flythrough.renderMillis=0.99 +desktop.flythrough.slow1.extractMillis=1.28 +desktop.flythrough.slow1.frameMillis=6.44 +desktop.flythrough.slow1.intervalMillis=21.86 +desktop.flythrough.slow1.poolLateMillis=0.01 +desktop.flythrough.slow1.poolMillis=2.24 +desktop.flythrough.slow1.renderMillis=1.72 +desktop.flythrough.slow1.tickMillis=3.26 +desktop.flythrough.terrainDrawCalls=4.36 +desktop.flythrough.terrainSections=568.07 +desktop.flythrough.tickMillis=0.95 +desktop.load.coldFirstFrameMillis=1737.96 +desktop.load.coldTitleMillis=2845.94 +desktop.load.joinMillis=5067.91 +desktop.load.titleHeapLiveMB=264.58 +desktop.load.titleNativeLiveMB=20.16 +desktop.load.warmFirstFrameMillis=1112.94 +desktop.load.warmReloadedMillis=1605.84 +desktop.load.warmTitleMillis=2117.80 +desktop.lobby.drawCalls=128.92 +desktop.lobby.extractMillis=2.18 +desktop.lobby.fpsLow1=41.77 +desktop.lobby.fpsMean=59.98 +desktop.lobby.fpsMedian=60.42 +desktop.lobby.frameP99Millis=22.87 +desktop.lobby.frames=2427 +desktop.lobby.gcCount=200 +desktop.lobby.gcMaxPauseMillis=3.70 +desktop.lobby.gcTotalMillis=122.74 +desktop.lobby.gpuMillis=0.65 +desktop.lobby.heapLiveMB=337.17 +desktop.lobby.heapMaxMB=539.22 +desktop.lobby.meshQueueMax=19 +desktop.lobby.meshQueueMean=1.58 +desktop.lobby.nativeLiveMB=44.98 +desktop.lobby.nativeMaxMB=74.44 +desktop.lobby.poolMillis=0.47 +desktop.lobby.renderMillis=9.89 +desktop.lobby.slow1.extractMillis=4.21 +desktop.lobby.slow1.frameMillis=18.85 +desktop.lobby.slow1.intervalMillis=23.94 +desktop.lobby.slow1.poolLateMillis=1.49 +desktop.lobby.slow1.poolMillis=1.79 +desktop.lobby.slow1.renderMillis=10.03 +desktop.lobby.slow1.tickMillis=4.55 +desktop.lobby.terrainDrawCalls=2 +desktop.lobby.terrainSections=114.89 +desktop.lobby.tickMillis=1.26 + +laptop-floor.combat.drawCalls=16.61 +laptop-floor.combat.extractMillis=0.89 +laptop-floor.combat.fpsLow1=22.98 +laptop-floor.combat.fpsMean=59.20 +laptop-floor.combat.fpsMedian=61.65 +laptop-floor.combat.frameP99Millis=20.94 +laptop-floor.combat.frames=2425 +laptop-floor.combat.gcCount=18 +laptop-floor.combat.gcMaxPauseMillis=4.36 +laptop-floor.combat.gcTotalMillis=48.58 +laptop-floor.combat.gpuMillis=6.17 +laptop-floor.combat.heapLiveMB=335.05 +laptop-floor.combat.heapMaxMB=398.42 +laptop-floor.combat.meshQueueMax=1 +laptop-floor.combat.meshQueueMean=0.00 +laptop-floor.combat.nativeLiveMB=69.24 +laptop-floor.combat.nativeMaxMB=92.56 +laptop-floor.combat.poolMillis=0.00 +laptop-floor.combat.renderMillis=1.91 +laptop-floor.combat.slow1.extractMillis=0.74 +laptop-floor.combat.slow1.frameMillis=29.54 +laptop-floor.combat.slow1.intervalMillis=43.52 +laptop-floor.combat.slow1.poolLateMillis=0 +laptop-floor.combat.slow1.poolMillis=0 +laptop-floor.combat.slow1.renderMillis=23.55 +laptop-floor.combat.slow1.tickMillis=4.74 +laptop-floor.combat.terrainDrawCalls=3 +laptop-floor.combat.terrainSections=1028 +laptop-floor.combat.tickMillis=1.43 +laptop-floor.download.gzipBytes=20397515 +laptop-floor.flythrough.drawCalls=18.83 +laptop-floor.flythrough.extractMillis=0.79 +laptop-floor.flythrough.fpsLow1=24.20 +laptop-floor.flythrough.fpsMean=59.27 +laptop-floor.flythrough.fpsMedian=60.24 +laptop-floor.flythrough.frameP99Millis=23.44 +laptop-floor.flythrough.frames=3298 +laptop-floor.flythrough.gcCount=35 +laptop-floor.flythrough.gcMaxPauseMillis=18.05 +laptop-floor.flythrough.gcTotalMillis=333.28 +laptop-floor.flythrough.gpuMillis=6.46 +laptop-floor.flythrough.heapLiveMB=338.39 +laptop-floor.flythrough.heapMaxMB=487.57 +laptop-floor.flythrough.meshQueueMax=72 +laptop-floor.flythrough.meshQueueMean=6.46 +laptop-floor.flythrough.nativeLiveMB=69.21 +laptop-floor.flythrough.nativeMaxMB=92.56 +laptop-floor.flythrough.poolMillis=1.86 +laptop-floor.flythrough.renderMillis=2.05 +laptop-floor.flythrough.slow1.extractMillis=5.17 +laptop-floor.flythrough.slow1.frameMillis=27.34 +laptop-floor.flythrough.slow1.intervalMillis=41.33 +laptop-floor.flythrough.slow1.poolLateMillis=2.66 +laptop-floor.flythrough.slow1.poolMillis=4.24 +laptop-floor.flythrough.slow1.renderMillis=7.64 +laptop-floor.flythrough.slow1.tickMillis=12.63 +laptop-floor.flythrough.terrainDrawCalls=4.45 +laptop-floor.flythrough.terrainSections=861.95 +laptop-floor.flythrough.tickMillis=0.99 +laptop-floor.load.coldFirstFrameMillis=6345.27 +laptop-floor.load.coldTitleMillis=12002.17 +laptop-floor.load.joinMillis=14670.95 +laptop-floor.load.rejoinMillis=11880.94 +laptop-floor.load.titleHeapLiveMB=237.58 +laptop-floor.load.titleNativeLiveMB=42.75 +laptop-floor.load.warmFirstFrameMillis=3814.29 +laptop-floor.load.warmReloadedMillis=7527.75 +laptop-floor.load.warmTitleMillis=8035.69 +laptop-floor.lobby.drawCalls=28.08 +laptop-floor.lobby.extractMillis=3.38 +laptop-floor.lobby.fpsLow1=32.60 +laptop-floor.lobby.fpsMean=58.68 +laptop-floor.lobby.fpsMedian=60.92 +laptop-floor.lobby.frameP99Millis=25.46 +laptop-floor.lobby.frames=2386 +laptop-floor.lobby.gcCount=121 +laptop-floor.lobby.gcMaxPauseMillis=7.13 +laptop-floor.lobby.gcTotalMillis=422.09 +laptop-floor.lobby.gpuMillis=5.65 +laptop-floor.lobby.heapLiveMB=323.68 +laptop-floor.lobby.heapMaxMB=497.13 +laptop-floor.lobby.meshQueueMax=34 +laptop-floor.lobby.meshQueueMean=3.62 +laptop-floor.lobby.nativeLiveMB=62.91 +laptop-floor.lobby.nativeMaxMB=92.56 +laptop-floor.lobby.poolMillis=0.56 +laptop-floor.lobby.renderMillis=9.34 +laptop-floor.lobby.slow1.extractMillis=5.38 +laptop-floor.lobby.slow1.frameMillis=25.26 +laptop-floor.lobby.slow1.intervalMillis=30.68 +laptop-floor.lobby.slow1.poolLateMillis=0.67 +laptop-floor.lobby.slow1.poolMillis=1.47 +laptop-floor.lobby.slow1.renderMillis=13.54 +laptop-floor.lobby.slow1.tickMillis=5.72 +laptop-floor.lobby.terrainDrawCalls=2 +laptop-floor.lobby.terrainSections=271.76 +laptop-floor.lobby.tickMillis=1.56 diff --git a/incari-client/files/app-web/benchmark/benchmark.txt b/incari-client/files/app-web/benchmark/benchmark.txt new file mode 100644 index 0000000..b36d563 --- /dev/null +++ b/incari-client/files/app-web/benchmark/benchmark.txt @@ -0,0 +1,141 @@ +# The benchmark (ADR 0021): ./gradlew :app-web:benchmark plays these scenarios in the browser +# build and reports what the page's profiler measured. The format is tools/webbuild's +# BenchmarkScript; docs/benchmark.md explains the figures and how to run it on a Chromebook. +# +# The page joins a fresh world from server.properties' seed as IncariBench, with options.txt's +# options (render distance 8). The world is made ready before anyone joins: time and weather +# stopped, no natural spawns, and the terrain both scenarios see generated in advance, so a scenario +# measures the client loading and drawing it, not the server making it. The player watches each +# scenario as a spectator of an invisible armor stand: a camera the server moves, so every run +# sees the same frames. options.txt throttles the frame rate only when minimized. + +server + rcon:gamerule advance_time false + rcon:gamerule advance_weather false + rcon:gamerule spawn_mobs false + rcon:gamerule spawn_patrols false + rcon:gamerule spawn_phantoms false + rcon:gamerule spawn_wandering_traders false + rcon:gamerule command_block_output false + rcon:gamerule mob_drops false + rcon:time set 6000 + rcon:weather clear + # The fly-through's corridor, x -128 to 895 and z -128 to 127: the flight and its render + # distance. forceload takes 256 chunks at a time. + rcon:forceload add -128 -128 127 127 + rcon:forceload add 128 -128 383 127 + rcon:forceload add 384 -128 639 127 + rcon:forceload add 640 -128 895 127 + # The arena, 2000 blocks north, with its render distance. + rcon:forceload add -128 -2128 127 -1873 + # The lobby, 2000 blocks south, with its render distance. + rcon:forceload add -128 1872 127 2127 + rconwait:execute if loaded -128 64 -128 => passed + rconwait:execute if loaded 383 64 127 => passed + rconwait:execute if loaded 895 64 -128 => passed + rconwait:execute if loaded 895 64 127 => passed + rconwait:execute if loaded 127 64 -1873 => passed + rconwait:execute if loaded -128 64 -2128 => passed + rconwait:execute if loaded 127 64 2127 => passed + rconwait:execute if loaded -128 64 1872 => passed + rcon:forceload remove all + # The fly-through's engine: each tick, the camera moves 0.55 blocks east (11 blocks a second, a + # sprint-fly). Its chunk stays loaded so it always runs. + rcon:forceload add 0 0 + rcon:setblock 0 318 0 minecraft:repeating_command_block{auto:1b,Command:"execute as @e[tag=incari_camera] at @s run tp @s ~0.55 ~ ~"} + +setup + rcon:gamemode spectator IncariBench + rcon:tp IncariBench 0.5 140 0.5 -90 25 + sleep:5000 + +scenario flythrough A straight flight east over fresh terrain at 11 blocks a second, render distance 8 + rcon:kill @e[tag=incari_camera] + rcon:summon minecraft:armor_stand 0.5 140 0.5 {Tags:["incari_camera"],Invisible:1b,Marker:1b,NoGravity:1b,Rotation:[-90f,25f]} + rcon:spectate @e[tag=incari_camera,limit=1] IncariBench + sleep:3000 + measure:55 + # A teleport ends the spectating. + rcon:tp IncariBench 0.5 212 -2026 0 35 + rcon:kill @e[tag=incari_camera] + +scenario combat Iron golems against waves of vindicators, pillagers and husks in an arena, watched from its edge + rcon:tp IncariBench 0.5 212 -2026 0 35 + # The teleport loads the arena's chunks a moment later: building before then fails. + rconwait:execute if loaded -17 199 -2017 => passed + rconwait:execute if loaded 17 204 -1983 => passed + rcon:fill -17 199 -2017 17 204 -1983 minecraft:barrier outline + rcon:fill -16 199 -2016 16 199 -1984 minecraft:smooth_stone + rcon:summon minecraft:armor_stand 0.5 212 -2026 {Tags:["incari_watch"],Invisible:1b,Marker:1b,NoGravity:1b,Rotation:[0f,35f]} + rcon:spectate @e[tag=incari_watch,limit=1] IncariBench + rcon*10:summon minecraft:iron_golem 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b} + rcon*4:summon minecraft:vindicator 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b} + rcon*3:summon minecraft:pillager 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b} + rcon*3:summon minecraft:husk 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b} + rcon:spreadplayers 0 -2000 2 14 under 203 false @e[tag=incari_fighter] + sleep:5000 + measure:10 + rcon*4:summon minecraft:vindicator 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b} + rcon*3:summon minecraft:pillager 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b} + rcon*3:summon minecraft:husk 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b} + measure:10 + rcon*4:summon minecraft:vindicator 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b} + rcon*3:summon minecraft:pillager 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b} + rcon*3:summon minecraft:husk 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b} + measure:10 + rcon*4:summon minecraft:vindicator 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b} + rcon*3:summon minecraft:pillager 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b} + rcon*3:summon minecraft:husk 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b} + measure:10 + rcon:kill @e[tag=incari_fighter] + rcon:kill @e[tag=incari_watch] + +# The crowded lobby: a crowd of player-shaped mannequins in armor with their names shown, floating +# hologram text, signs, floating items, particle fountains, a sidebar and a boss bar, watched by a +# camera orbiting the crowd 20 blocks out (a command block moves it each tick: sideways and turning, +# so it circles the lobby's centre while facing it). +scenario lobby A crowded server lobby: 80 players in armor with name tags, holograms, signs and particles, circled by the camera + rcon:tp IncariBench 0.5 212 1980 0 25 + # As in the arena: wait for the lobby's chunks before building it. + rconwait:execute if loaded -22 199 1978 => passed + rconwait:execute if loaded 22 214 2022 => passed + rcon:fill -22 199 1978 22 199 2022 minecraft:polished_andesite + rcon:fill -22 200 1978 22 214 2022 minecraft:air + rcon:fill -22 200 1978 22 200 1978 minecraft:oak_sign[rotation=0]{front_text:{messages:["Welcome","to the","Incari","lobby"]}} + rcon:fill -22 200 2022 22 200 2022 minecraft:oak_sign[rotation=8]{front_text:{messages:["Pick a","game","below","!"]}} + rcon:fill -22 200 1979 -22 200 2021 minecraft:oak_sign[rotation=12]{front_text:{messages:["Bedwars","Skywars","Duels","Parkour"]}} + rcon:fill 22 200 1979 22 200 2021 minecraft:oak_sign[rotation=4]{front_text:{messages:["Rules:","be kind","no hacks","have fun"]}} + rcon*80:summon minecraft:mannequin 0 200 2000 {Tags:["incari_lobby"],CustomName:"LobbyPlayer",CustomNameVisible:1b,equipment:{head:{id:"minecraft:iron_helmet"},chest:{id:"minecraft:diamond_chestplate"},legs:{id:"minecraft:iron_leggings"},feet:{id:"minecraft:golden_boots"},mainhand:{id:"minecraft:diamond_sword"}}} + rcon:spreadplayers 0 2000 1 15 under 205 false @e[tag=incari_lobby,type=minecraft:mannequin] + rcon*24:summon minecraft:armor_stand 0 203 2000 {Tags:["incari_lobby","incari_hologram"],Invisible:1b,Marker:1b,NoGravity:1b,CustomName:"Play now: 1,024 online",CustomNameVisible:1b} + rcon:spreadplayers 0 2000 2 18 under 205 false @e[tag=incari_hologram] + rcon*12:summon minecraft:text_display 0 205 2000 {Tags:["incari_lobby"],billboard:"center",text:"Incari Network",background:1073741824} + rcon:spreadplayers 0 2000 4 18 under 205 false @e[tag=incari_lobby,type=minecraft:text_display] + rcon*30:summon minecraft:item 0 201 2000 {Tags:["incari_lobby"],Item:{id:"minecraft:diamond",count:1},NoGravity:1b,Age:-32768,PickupDelay:32767} + rcon:spreadplayers 0 2000 1 16 under 205 false @e[tag=incari_lobby,type=minecraft:item] + rcon:setblock 1 318 1 minecraft:repeating_command_block{auto:1b,Command:"particle minecraft:end_rod 0 204 2000 10 3 10 0.01 30 force"} + rcon:setblock 2 318 0 minecraft:repeating_command_block{auto:1b,Command:"particle minecraft:happy_villager 0 202 2000 14 2 14 0 20 force"} + rcon:setblock 2 318 1 minecraft:repeating_command_block{auto:1b,Command:"particle minecraft:flame 0 201 2000 16 1 16 0.01 15 force"} + rcon:scoreboard objectives add incari_lobby dummy "Incari Network" + rcon:scoreboard objectives setdisplay sidebar incari_lobby + rcon:scoreboard players set Online incari_lobby 1024 + rcon:scoreboard players set Bedwars incari_lobby 312 + rcon:scoreboard players set Skywars incari_lobby 288 + rcon:scoreboard players set Duels incari_lobby 201 + rcon:scoreboard players set Parkour incari_lobby 97 + rcon:bossbar add incari_lobby "Welcome to the Incari lobby" + rcon:bossbar set incari_lobby players @a + rcon:summon minecraft:armor_stand 0.5 207 1980 {Tags:["incari_lobbycam"],Invisible:1b,Marker:1b,NoGravity:1b,Rotation:[0f,25f]} + rcon:spectate @e[tag=incari_lobbycam,limit=1] IncariBench + rcon:setblock 1 318 0 minecraft:repeating_command_block{auto:1b,Command:"execute as @e[tag=incari_lobbycam] at @s run tp @s ^0.35 ^ ^ ~1 ~"} + sleep:5000 + measure:40 + rcon:setblock 1 318 0 minecraft:air + rcon:setblock 1 318 1 minecraft:air + rcon:setblock 2 318 0 minecraft:air + rcon:setblock 2 318 1 minecraft:air + rcon:bossbar remove incari_lobby + rcon:scoreboard objectives remove incari_lobby + rcon:tp IncariBench 0.5 212 1980 0 25 + rcon:kill @e[tag=incari_lobby] + rcon:kill @e[tag=incari_lobbycam] diff --git a/incari-client/files/app-web/benchmark/budgets.properties b/incari-client/files/app-web/benchmark/budgets.properties new file mode 100644 index 0000000..c33a70b --- /dev/null +++ b/incari-client/files/app-web/benchmark/budgets.properties @@ -0,0 +1,32 @@ +# The budgets, set for memory (ADR 0025) and start-up (ADR 0026): absolute limits the +# benchmark (tools/webbuild's PerfBudget) fails a figure over, whatever the baseline says. Figures are +# as report.json names them; a * stands for one part of the name (a scenario). Measured on the +# release build (-Pteavm.release), which is what players get. +# +# max.
= for every machine: memory (the same build in the same scene keeps +# the same heap wherever it runs) +# .max.
= for one machine: times, which are the machine's speed +# +# Raising a limit is fine when the pull request says why; the point is that growth is noticed. + +# Memory, in megabytes. The live figures are what the page still holds after a full collection +# (the game's own memory, not garbage the browser hasn't collected yet). Set from the release build +# of 2026-10-01 (title screen 262 MB live; in the world 337 to 351 MB live, 45 to 53 MB of linear +# memory in use, 75 MB of it at its largest) with about a fifth of headroom. +max.load.titleHeapLiveMB=320 +max.*.heapLiveMB=420 +# Linear memory never shrinks: its largest is what the page keeps for good. +max.*.nativeMaxMB=128 + +# The memory gate: no garbage collection pause above 16 ms (a frame at 60 fps). +max.*.gcMaxPauseMillis=16 + +# Start-up, in milliseconds from the navigation (the gate: the warm start to the title screen). +# The development desktop (Ryzen 5 9600X): 2.2 s warm and 3.2 s cold measured on 2026-10-01. +desktop.max.load.warmTitleMillis=3000 +desktop.max.load.coldTitleMillis=4500 +# The floor device, a 4 GB Chromebook (docs/benchmark.md): targets, not measurements, until the +# device is measured. Its CPU (Celeron N4500 class) is estimated at about a fifth of the desktop's +# single-thread speed, which puts the desktop's 2.2 s warm start near 10 s there. +chromebook-4gb.max.load.warmTitleMillis=10000 +chromebook-4gb.max.load.coldTitleMillis=20000 diff --git a/incari-client/files/app-web/benchmark/features.txt b/incari-client/files/app-web/benchmark/features.txt new file mode 100644 index 0000000..2822223 --- /dev/null +++ b/incari-client/files/app-web/benchmark/features.txt @@ -0,0 +1,56 @@ +# The client's modules in play, in the page's own world: +# ./gradlew :app-web:benchmark -Pbenchmark.singleplayer -Pbenchmark.script=features.txt +# -Pbenchmark.history= -Pteavm.release -Pteavm.fast +# -Pbenchmark.query=modules= +# Run it twice, with no modules (modules=) and with the HUD and play modules on, to see what they +# cost: +# modules=armorpotionview,blockoutline,clearchat,cooldownindicator,coordinates,cps,crosshair, +# customscoreboard,fpsdisplay,freelook,fullbright,glintcolor,hitcolor,hiteffects,keystrokes, +# lowfire,lowshield,minimap,nohurtcam,oldanimations,reachdisplay,shieldtotem,shortswords, +# shulkertooltips,togglesprint,waypoints,weatherchanger +# (no commas' spaces; Old Textures is left out: its pack reloads every resource at start). +# The player is in creative, in armor, with a shield, totems and three effects, so every HUD +# module has something to show. Scenarios: standing at spawn, then flying east at 11 blocks a +# second, a command block teleporting the player each tick, so the minimap draws new chunks. + +setup + rcon:gamerule advance_time false + rcon:gamerule advance_weather false + rcon:gamerule spawn_mobs false + rcon:gamerule spawn_patrols false + rcon:gamerule spawn_phantoms false + rcon:gamerule spawn_wandering_traders false + rcon:gamerule command_block_output false + rcon:gamerule send_command_feedback false + rcon:time set 6000 + rcon:weather clear + rcon:gamemode creative @s + rcon:item replace entity @s armor.head with minecraft:diamond_helmet + rcon:item replace entity @s armor.chest with minecraft:diamond_chestplate + rcon:item replace entity @s armor.legs with minecraft:diamond_leggings + rcon:item replace entity @s armor.feet with minecraft:diamond_boots + rcon:item replace entity @s weapon.mainhand with minecraft:diamond_sword + rcon:item replace entity @s weapon.offhand with minecraft:shield + rcon:give @s minecraft:totem_of_undying 3 + rcon:effect give @s minecraft:speed infinite 1 + rcon:effect give @s minecraft:strength infinite 0 + rcon:effect give @s minecraft:fire_resistance infinite 0 + rcon:forceload add 0 0 + sleep:10000 + +scenario still Standing at spawn with the HUD + shot:features-still + measure:20 + +scenario travel Flying east at 11 blocks a second over terrain the page's server generates, the minimap drawing new chunks + rcon:tp @s 0.5 120 0.5 -90 20 + rcon:gamerule send_command_feedback true + rconwait:execute if loaded 0 64 0 => passed + rconwait:execute if loaded 96 64 0 => passed + rcon:gamerule send_command_feedback false + sleep:5000 + rcon:setblock 0 318 0 minecraft:repeating_command_block{auto:1b,Command:"execute as @a at @s run tp @s ~0.55 120 ~"} + sleep:2000 + shot:features-travel + measure:40 + rcon:setblock 0 318 0 minecraft:air diff --git a/incari-client/files/app-web/benchmark/hudeditor.txt b/incari-client/files/app-web/benchmark/hudeditor.txt new file mode 100644 index 0000000..29c6172 --- /dev/null +++ b/incari-client/files/app-web/benchmark/hudeditor.txt @@ -0,0 +1,92 @@ +# The HUD editor's cost (ADR 0049), in the page's own world: +# ./gradlew :app-web:benchmark -Pbenchmark.singleplayer -Pbenchmark.script=hudeditor.txt +# -Pbenchmark.history= +# The player stands at the world's spawn with Toggle Sprint on (its line is what the editor shows). +# Scenarios: the HUD alone; the pause menu (Potato: no blur); the HUD editor in Potato, its blurred +# backdrop drawn ten times a second and kept (BackdropCache); the editor in Normal, blurred every +# frame, which is what Potato would pay without the cache. The menus are reached with the keyboard +# (Tab order in the module menu: All, Movement, GUI, Profile, Done, Edit HUD, the search, the cards), +# and each scenario takes a screenshot in build/benchmark to show it got there. + +setup + rcon:gamerule advance_time false + rcon:gamerule advance_weather false + rcon:gamerule spawn_mobs false + rcon:gamerule send_command_feedback false + rcon:time set 6000 + rcon:weather clear + sleep:10000 + # Toggle Sprint on: its card is the eighth stop. + key:ShiftRight + sleep:1500 + key:Tab + key:Tab + key:Tab + key:Tab + key:Tab + key:Tab + key:Tab + key:Tab + key:Enter + sleep:500 + shot:hudeditor-setup + key:Escape + sleep:3000 + +scenario hud The world at spawn with the HUD, no screen open + measure:20 + +scenario pause The pause menu over the world (Potato: no blur) + key:Escape + sleep:2000 + shot:hudeditor-pause + measure:20 + key:Escape + sleep:2000 + +scenario editor_potato The HUD editor in Potato: the blurred world drawn ten times a second and kept + key:ShiftRight + sleep:1500 + key:Tab + key:Tab + key:Tab + key:Tab + key:Tab + key:Tab + key:Enter + sleep:2000 + shot:hudeditor-potato + measure:20 + key:Escape + sleep:1000 + key:Escape + sleep:2000 + +scenario editor_normal The HUD editor in Normal: the world drawn and blurred every frame + # The module menu's GUI entry (the third stop) switches to Normal. + key:ShiftRight + sleep:1500 + key:Tab + key:Tab + key:Tab + key:Enter + sleep:1000 + # Opened again, so the Tabs start from the top. + key:Escape + sleep:1500 + key:ShiftRight + sleep:1500 + key:Tab + key:Tab + key:Tab + key:Tab + key:Tab + key:Tab + key:Enter + sleep:2000 + shot:hudeditor-normal + measure:20 + key:Escape + sleep:1000 + key:Escape + sleep:2000 diff --git a/incari-client/files/app-web/benchmark/menus.txt b/incari-client/files/app-web/benchmark/menus.txt new file mode 100644 index 0000000..6e17b1e --- /dev/null +++ b/incari-client/files/app-web/benchmark/menus.txt @@ -0,0 +1,92 @@ +# The client's menus and screens (the look's first performance pass), in the page's own world: +# ./gradlew :app-web:benchmark -Pbenchmark.singleplayer -Pbenchmark.script=menus.txt +# -Pbenchmark.history= -Pteavm.release -Pteavm.fast +# The player stands at the world's spawn in survival with a few items. Scenarios: the HUD alone (the +# world's own cost, for comparison), then the module menu, the pause menu and the inventory, in +# Potato and again in Normal (glows, eased hovers, the menus' blur). The pointer rests over the +# module menu's first card, so its hover is drawn. The menus are reached with the keyboard (Tab +# order in the module menu: All, the five categories, GUI, Profile, Done, Edit HUD, the search, the +# cards), and each scenario takes a screenshot in build/benchmark to show it got there. + +setup + rcon:gamerule advance_time false + rcon:gamerule advance_weather false + rcon:gamerule spawn_mobs false + rcon:gamerule send_command_feedback false + rcon:time set 6000 + rcon:weather clear + rcon:gamemode survival @s + rcon:give @s minecraft:diamond_sword + rcon:give @s minecraft:bow + rcon:give @s minecraft:arrow 64 + rcon:give @s minecraft:oak_planks 64 + rcon:give @s minecraft:cooked_beef 32 + rcon:give @s minecraft:iron_chestplate + sleep:10000 + +scenario hud The world at spawn with the HUD, no screen open + measure:20 + +scenario menu_potato The module menu in Potato, the pointer over its first card + key:ShiftRight + sleep:1500 + move:0.36,0.3 + sleep:1000 + shot:menus-menu-potato + measure:20 + key:Escape + sleep:2000 + +scenario pause_potato The pause menu in Potato + key:Escape + sleep:2000 + shot:menus-pause-potato + measure:20 + key:Escape + sleep:2000 + +scenario inventory_potato The inventory in Potato: the glass panel with a well under each slot + key:KeyE + sleep:2000 + shot:menus-inventory-potato + measure:20 + key:Escape + sleep:2000 + +scenario menu_normal The module menu in Normal, the pointer over its first card + # The module menu's GUI entry (the seventh stop) switches to Normal. + key:ShiftRight + sleep:1500 + key:Tab + key:Tab + key:Tab + key:Tab + key:Tab + key:Tab + key:Tab + key:Enter + sleep:1000 + move:0.5,0.5 + sleep:300 + move:0.36,0.3 + sleep:1000 + shot:menus-menu-normal + measure:20 + key:Escape + sleep:2000 + +scenario pause_normal The pause menu in Normal, blurred + key:Escape + sleep:2000 + shot:menus-pause-normal + measure:20 + key:Escape + sleep:2000 + +scenario inventory_normal The inventory in Normal + key:KeyE + sleep:2000 + shot:menus-inventory-normal + measure:20 + key:Escape + sleep:2000 diff --git a/incari-client/files/app-web/benchmark/options.txt b/incari-client/files/app-web/benchmark/options.txt new file mode 100644 index 0000000..bb82d8b --- /dev/null +++ b/incari-client/files/app-web/benchmark/options.txt @@ -0,0 +1,45 @@ +version:5023 +onboardAccessibility:false +pauseOnLostFocus:false +joinedFirstServer:true +skipMultiplayerWarning:true +tutorialStep:none +realmsNotifications:false +graphicsPreset:"custom" +fov:0.0 +fovEffectScale:0.0 +guiScale:2 +renderDistance:8 +simulationDistance:6 +biomeBlendRadius:2 +ao:true +renderClouds:"true" +cloudRange:64 +particles:0 +mipmapLevels:4 +textureFiltering:1 +maxAnisotropyBit:1 +entityShadows:true +entityDistanceScaling:1.0 +improvedTransparency:false +cutoutLeaves:true +weatherRadius:10 +chunkSectionFadeInTime:0.0 +menuBackgroundBlurriness:5 +prioritizeChunkUpdates:0 +bobView:false +gamma:0.5 +vignette:true +screenEffectScale:1.0 +darknessEffectScale:1.0 +damageTiltStrength:0.0 +hideLightningFlashes:true +enableVsync:false +maxFps:260 +inactivityFpsLimit:"minimized" +fullscreen:false +chatVisibility:2 +showSubtitles:false +narrator:0 +soundCategory_master:0.0 +lang:en_us diff --git a/incari-client/files/app-web/benchmark/server.properties b/incari-client/files/app-web/benchmark/server.properties new file mode 100644 index 0000000..67bac4a --- /dev/null +++ b/incari-client/files/app-web/benchmark/server.properties @@ -0,0 +1,20 @@ +# The benchmark's game server (see benchmark.txt). The runner adds the address, ports and a +# random RCON password, and starts every run with a fresh world from this seed. Command blocks +# move the fly-through's camera, a step each tick. +level-seed=20260928 +level-type=minecraft\:normal +generate-structures=true +online-mode=false +white-list=false +difficulty=easy +spawn-monsters=false +view-distance=8 +simulation-distance=6 +spawn-protection=0 +enable-command-block=true +pause-when-empty-seconds=0 +max-tick-time=-1 +broadcast-console-to-ops=false +broadcast-rcon-to-ops=false +sync-chunk-writes=false +enable-status=true diff --git a/incari-client/files/app-web/benchmark/singleplayer-baseline.properties b/incari-client/files/app-web/benchmark/singleplayer-baseline.properties new file mode 100644 index 0000000..f4ae19f --- /dev/null +++ b/incari-client/files/app-web/benchmark/singleplayer-baseline.properties @@ -0,0 +1,266 @@ +# The singleplayer benchmark's baseline (ADR 0039; ./gradlew :app-web:benchmark -Pbenchmark.singleplayer, +# singleplayer.txt): as baseline.properties, for the scenarios a world the page runs itself plays. +# Kept apart from the server benchmark's: recording one machine's figures replaces all of them. +# +# rule.
= + +# Frame rate and frame time. +rule.fpsMedian=higher 5 1 +rule.fpsLow1=higher 15 3 +rule.frameP99Millis=lower 15 2 +# Where the frame's time goes (milliseconds a frame). +rule.tickMillis=lower 20 0.5 +rule.extractMillis=lower 20 0.5 +rule.renderMillis=lower 20 0.5 +rule.gpuMillis=lower 20 0.5 +# Memory, in megabytes, and garbage collection pauses: the page's, then the server worker's. +rule.heapMaxMB=lower 10 16 +rule.nativeMaxMB=lower 10 16 +rule.gcMaxPauseMillis=lower 30 4 +rule.workerHeapLiveMB=lower 10 16 +# The server worker's ticks: 20 a second when it keeps up. +rule.serverTicksPerSecond=higher 5 1 +rule.serverTickMillis=lower 20 2 +rule.serverTickP95Millis=lower 20 5 +# Loading, in milliseconds: the world created from the title screen, Save and Quit until it's +# stored, and opening it again from a reload (from the navigation). +rule.coldTitleMillis=lower 20 500 +rule.createMillis=lower 20 1000 +rule.saveQuitMillis=lower 20 500 +rule.openMillis=lower 20 1000 +rule.gzipBytes=lower 2 10000 + + + + +desktop.combat.drawCalls=14.19 +desktop.combat.extractMillis=0.25 +desktop.combat.fpsLow1=54.31 +desktop.combat.fpsMean=60.00 +desktop.combat.fpsMedian=60.04 +desktop.combat.frameP99Millis=18.34 +desktop.combat.frames=1813 +desktop.combat.gcCount=9 +desktop.combat.gcMaxPauseMillis=0.73 +desktop.combat.gcTotalMillis=5.68 +desktop.combat.gpuMillis=0.39 +desktop.combat.heapLiveMB=411.81 +desktop.combat.heapMaxMB=441.17 +desktop.combat.meshQueueMax=0 +desktop.combat.meshQueueMean=0 +desktop.combat.nativeLiveMB=77.32 +desktop.combat.nativeMaxMB=100.56 +desktop.combat.poolMillis=0 +desktop.combat.renderMillis=0.55 +desktop.combat.serverChunks=2578 +desktop.combat.serverPausedTicks=0 +desktop.combat.serverTickMaxMillis=3.73 +desktop.combat.serverTickMillis=3.13 +desktop.combat.serverTickP95Millis=3.42 +desktop.combat.serverTicksPerSecond=19.97 +desktop.combat.slow1.extractMillis=0.27 +desktop.combat.slow1.frameMillis=2.42 +desktop.combat.slow1.intervalMillis=18.41 +desktop.combat.slow1.poolLateMillis=0 +desktop.combat.slow1.poolMillis=0 +desktop.combat.slow1.renderMillis=0.54 +desktop.combat.slow1.tickMillis=1.55 +desktop.combat.terrainDrawCalls=3 +desktop.combat.terrainSections=1021 +desktop.combat.tickMillis=0.45 +desktop.combat.workerHeapLiveMB=371.04 +desktop.download.gzipBytes=20397515 +desktop.flythrough.drawCalls=18.94 +desktop.flythrough.extractMillis=0.26 +desktop.flythrough.fpsLow1=43.63 +desktop.flythrough.fpsMean=59.98 +desktop.flythrough.fpsMedian=60.15 +desktop.flythrough.frameP99Millis=18.75 +desktop.flythrough.frames=3335 +desktop.flythrough.gcCount=58 +desktop.flythrough.gcMaxPauseMillis=45.37 +desktop.flythrough.gcTotalMillis=160.67 +desktop.flythrough.gpuMillis=0.38 +desktop.flythrough.heapLiveMB=383.78 +desktop.flythrough.heapMaxMB=607.93 +desktop.flythrough.meshQueueMax=56 +desktop.flythrough.meshQueueMean=2.96 +desktop.flythrough.nativeLiveMB=69.30 +desktop.flythrough.nativeMaxMB=100.56 +desktop.flythrough.poolMillis=0.69 +desktop.flythrough.renderMillis=0.60 +desktop.flythrough.serverChunks=2578 +desktop.flythrough.serverPausedTicks=0 +desktop.flythrough.serverTickMaxMillis=10.55 +desktop.flythrough.serverTickMillis=2.50 +desktop.flythrough.serverTickP95Millis=4.51 +desktop.flythrough.serverTicksPerSecond=20.01 +desktop.flythrough.slow1.extractMillis=0.78 +desktop.flythrough.slow1.frameMillis=3.26 +desktop.flythrough.slow1.intervalMillis=22.92 +desktop.flythrough.slow1.poolLateMillis=0 +desktop.flythrough.slow1.poolMillis=1.33 +desktop.flythrough.slow1.renderMillis=0.86 +desktop.flythrough.slow1.tickMillis=1.55 +desktop.flythrough.terrainDrawCalls=4.75 +desktop.flythrough.terrainSections=868.08 +desktop.flythrough.tickMillis=0.38 +desktop.flythrough.workerHeapLiveMB=298.95 +desktop.load.coldTitleMillis=3210.55 +desktop.load.createMillis=6011.25 +desktop.load.leftHeapLiveMB=375.48 +desktop.load.leftNativeLiveMB=70.16 +desktop.load.openMillis=5312.63 +desktop.load.saveQuitMillis=1034.09 +desktop.spawn.drawCalls=18.79 +desktop.spawn.extractMillis=0.22 +desktop.spawn.fpsLow1=51.82 +desktop.spawn.fpsMean=60.00 +desktop.spawn.fpsMedian=60.11 +desktop.spawn.frameP99Millis=18.67 +desktop.spawn.frames=1806 +desktop.spawn.gcCount=8 +desktop.spawn.gcMaxPauseMillis=0.77 +desktop.spawn.gcTotalMillis=5.59 +desktop.spawn.gpuMillis=0.32 +desktop.spawn.heapLiveMB=384.43 +desktop.spawn.heapMaxMB=414.11 +desktop.spawn.meshQueueMax=2 +desktop.spawn.meshQueueMean=0.00 +desktop.spawn.nativeLiveMB=69.95 +desktop.spawn.nativeMaxMB=90.44 +desktop.spawn.poolMillis=0.00 +desktop.spawn.renderMillis=0.39 +desktop.spawn.serverChunks=1849 +desktop.spawn.serverPausedTicks=0 +desktop.spawn.serverTickMaxMillis=7.44 +desktop.spawn.serverTickMillis=4.98 +desktop.spawn.serverTickP95Millis=5.73 +desktop.spawn.serverTicksPerSecond=19.97 +desktop.spawn.slow1.extractMillis=0.25 +desktop.spawn.slow1.frameMillis=3.23 +desktop.spawn.slow1.intervalMillis=19.30 +desktop.spawn.slow1.poolLateMillis=0 +desktop.spawn.slow1.poolMillis=0 +desktop.spawn.slow1.renderMillis=0.82 +desktop.spawn.slow1.tickMillis=2.09 +desktop.spawn.terrainDrawCalls=4 +desktop.spawn.terrainSections=531 +desktop.spawn.tickMillis=0.58 +desktop.spawn.workerHeapLiveMB=227.31 + +laptop-floor.combat.drawCalls=14.86 +laptop-floor.combat.extractMillis=0.91 +laptop-floor.combat.fpsLow1=33.84 +laptop-floor.combat.fpsMean=59.77 +laptop-floor.combat.fpsMedian=58.86 +laptop-floor.combat.frameP99Millis=23.03 +laptop-floor.combat.frames=1829 +laptop-floor.combat.gcCount=17 +laptop-floor.combat.gcMaxPauseMillis=2.30 +laptop-floor.combat.gcTotalMillis=20.50 +laptop-floor.combat.gpuMillis=5.01 +laptop-floor.combat.heapLiveMB=341.80 +laptop-floor.combat.heapMaxMB=382.74 +laptop-floor.combat.meshQueueMax=2 +laptop-floor.combat.meshQueueMean=0.00 +laptop-floor.combat.nativeLiveMB=69.24 +laptop-floor.combat.nativeMaxMB=88.56 +laptop-floor.combat.poolMillis=0.00 +laptop-floor.combat.renderMillis=1.92 +laptop-floor.combat.serverChunks=2578 +laptop-floor.combat.serverPausedTicks=0 +laptop-floor.combat.serverTickMaxMillis=64.22 +laptop-floor.combat.serverTickMillis=7.34 +laptop-floor.combat.serverTickP95Millis=10.54 +laptop-floor.combat.serverTicksPerSecond=20.04 +laptop-floor.combat.slow1.extractMillis=2.02 +laptop-floor.combat.slow1.frameMillis=16.56 +laptop-floor.combat.slow1.intervalMillis=29.55 +laptop-floor.combat.slow1.poolLateMillis=0 +laptop-floor.combat.slow1.poolMillis=0 +laptop-floor.combat.slow1.renderMillis=5.18 +laptop-floor.combat.slow1.tickMillis=8.92 +laptop-floor.combat.terrainDrawCalls=3 +laptop-floor.combat.terrainSections=1043 +laptop-floor.combat.tickMillis=1.40 +laptop-floor.combat.workerHeapLiveMB=366.58 +laptop-floor.download.gzipBytes=20397515 +laptop-floor.flythrough.drawCalls=13.65 +laptop-floor.flythrough.extractMillis=0.82 +laptop-floor.flythrough.fpsLow1=14.91 +laptop-floor.flythrough.fpsMean=58.34 +laptop-floor.flythrough.fpsMedian=59.92 +laptop-floor.flythrough.frameP99Millis=31 +laptop-floor.flythrough.frames=3307 +laptop-floor.flythrough.gcCount=26 +laptop-floor.flythrough.gcMaxPauseMillis=18.29 +laptop-floor.flythrough.gcTotalMillis=225.14 +laptop-floor.flythrough.gpuMillis=2.45 +laptop-floor.flythrough.heapLiveMB=304.75 +laptop-floor.flythrough.heapMaxMB=444.96 +laptop-floor.flythrough.meshQueueMax=34 +laptop-floor.flythrough.meshQueueMean=1.34 +laptop-floor.flythrough.nativeLiveMB=61.21 +laptop-floor.flythrough.nativeMaxMB=88.56 +laptop-floor.flythrough.poolMillis=0.93 +laptop-floor.flythrough.renderMillis=1.65 +laptop-floor.flythrough.serverChunks=2039 +laptop-floor.flythrough.serverPausedTicks=0 +laptop-floor.flythrough.serverTickMaxMillis=53.18 +laptop-floor.flythrough.serverTickMillis=5.05 +laptop-floor.flythrough.serverTickP95Millis=13.72 +laptop-floor.flythrough.serverTicksPerSecond=19.97 +laptop-floor.flythrough.slow1.extractMillis=4.02 +laptop-floor.flythrough.slow1.frameMillis=54.03 +laptop-floor.flythrough.slow1.intervalMillis=67.05 +laptop-floor.flythrough.slow1.poolLateMillis=4.04 +laptop-floor.flythrough.slow1.poolMillis=2.26 +laptop-floor.flythrough.slow1.renderMillis=6.51 +laptop-floor.flythrough.slow1.tickMillis=42.54 +laptop-floor.flythrough.terrainDrawCalls=2.99 +laptop-floor.flythrough.terrainSections=97.49 +laptop-floor.flythrough.tickMillis=1.85 +laptop-floor.flythrough.workerHeapLiveMB=317.97 +laptop-floor.load.coldTitleMillis=11817.60 +laptop-floor.load.createMillis=26397.91 +laptop-floor.load.leftHeapLiveMB=295.76 +laptop-floor.load.leftNativeLiveMB=68.10 +laptop-floor.load.openMillis=19986.34 +laptop-floor.load.saveQuitMillis=3757.05 +laptop-floor.spawn.drawCalls=21.33 +laptop-floor.spawn.extractMillis=1.07 +laptop-floor.spawn.fpsLow1=25.02 +laptop-floor.spawn.fpsMean=59.54 +laptop-floor.spawn.fpsMedian=60.37 +laptop-floor.spawn.frameP99Millis=27.12 +laptop-floor.spawn.frames=1837 +laptop-floor.spawn.gcCount=9 +laptop-floor.spawn.gcMaxPauseMillis=29.12 +laptop-floor.spawn.gcTotalMillis=68.98 +laptop-floor.spawn.gpuMillis=5.94 +laptop-floor.spawn.heapLiveMB=319.04 +laptop-floor.spawn.heapMaxMB=473.25 +laptop-floor.spawn.meshQueueMax=6 +laptop-floor.spawn.meshQueueMean=0.05 +laptop-floor.spawn.nativeLiveMB=68.09 +laptop-floor.spawn.nativeMaxMB=88.56 +laptop-floor.spawn.poolMillis=0.06 +laptop-floor.spawn.renderMillis=2.26 +laptop-floor.spawn.serverChunks=1849 +laptop-floor.spawn.serverPausedTicks=0 +laptop-floor.spawn.serverTickMaxMillis=93.41 +laptop-floor.spawn.serverTickMillis=14.30 +laptop-floor.spawn.serverTickP95Millis=19.97 +laptop-floor.spawn.serverTicksPerSecond=20.02 +laptop-floor.spawn.slow1.extractMillis=2.29 +laptop-floor.spawn.slow1.frameMillis=21.32 +laptop-floor.spawn.slow1.intervalMillis=39.97 +laptop-floor.spawn.slow1.poolLateMillis=0 +laptop-floor.spawn.slow1.poolMillis=0 +laptop-floor.spawn.slow1.renderMillis=7.81 +laptop-floor.spawn.slow1.tickMillis=10.84 +laptop-floor.spawn.terrainDrawCalls=4.53 +laptop-floor.spawn.terrainSections=542.32 +laptop-floor.spawn.tickMillis=1.97 +laptop-floor.spawn.workerHeapLiveMB=270.99 diff --git a/incari-client/files/app-web/benchmark/singleplayer.txt b/incari-client/files/app-web/benchmark/singleplayer.txt new file mode 100644 index 0000000..8eb7c7c --- /dev/null +++ b/incari-client/files/app-web/benchmark/singleplayer.txt @@ -0,0 +1,80 @@ +# The singleplayer benchmark (ADR 0039's server in a worker): ./gradlew :app-web:benchmark +# -Pbenchmark.singleplayer plays these scenarios in a world the page creates itself, from +# server.properties' seed (the server benchmark's terrain), with options.txt's options but commands +# shown in chat. Same format as benchmark.txt, but there's no server section: nothing runs before +# the world exists, and each rcon step is typed into the game's chat as the player (who may run +# commands: the world allows them). rconwait reads the answer from the page's console. +# +# Unlike the server benchmark, nothing is generated in advance: the page's own server generates +# terrain as the camera reaches it, on the same machine as the page, which is what a player's +# singleplayer world does. Each scenario's figures add the server worker's ticks: ticks a second +# (20 when it keeps up), their length, the chunks it holds, and its heap. + +setup + rcon:gamerule advance_time false + rcon:gamerule advance_weather false + rcon:gamerule spawn_mobs false + rcon:gamerule spawn_patrols false + rcon:gamerule spawn_phantoms false + rcon:gamerule spawn_wandering_traders false + rcon:gamerule command_block_output false + rcon:gamerule send_command_feedback false + rcon:gamerule mob_drops false + rcon:time set 6000 + rcon:weather clear + rcon:gamemode spectator @s + # The fly-through's engine, as in benchmark.txt: each tick, the camera moves 0.55 blocks east. + rcon:forceload add 0 0 + rcon:setblock 0 318 0 minecraft:repeating_command_block{auto:1b,Command:"execute as @e[tag=incari_camera] at @s run tp @s ~0.55 ~ ~"} + sleep:10000 + +# Where the world put the player: its spawn area, generated when the world was created. +scenario spawn At the world's spawn, where the player stands when the world opens: the server ticking the area around them, nothing new to generate + measure:30 + +scenario flythrough A straight flight east at 11 blocks a second, over terrain the page's own server generates as the camera reaches it + rcon:tp @s 0.5 140 0.5 -90 25 + # The flight starts over generated terrain: the server makes the start area first. + rcon:gamerule send_command_feedback true + rconwait:execute if loaded 0 64 0 => passed + rconwait:execute if loaded 96 64 0 => passed + rcon:gamerule send_command_feedback false + sleep:5000 + rcon:kill @e[tag=incari_camera] + rcon:summon minecraft:armor_stand 0.5 140 0.5 {Tags:["incari_camera"],Invisible:1b,Marker:1b,NoGravity:1b,Rotation:[-90f,25f]} + rcon:spectate @e[tag=incari_camera,limit=1] @s + sleep:3000 + measure:55 + # A teleport ends the spectating. + rcon:tp @s 0.5 212 -2026 0 35 + rcon:kill @e[tag=incari_camera] + +scenario combat Iron golems against waves of vindicators, pillagers and husks in an arena, the server running their AI beside the page + rcon:tp @s 0.5 212 -2026 0 35 + # The arena's chunks are generated once the teleport reaches them: building before then fails. + # Feedback on for the waits' answers, off again for the building. + rcon:gamerule send_command_feedback true + rconwait:execute if loaded -17 199 -2017 => passed + rconwait:execute if loaded 17 204 -1983 => passed + rcon:gamerule send_command_feedback false + rcon:fill -17 199 -2017 17 204 -1983 minecraft:barrier outline + rcon:fill -16 199 -2016 16 199 -1984 minecraft:smooth_stone + rcon:summon minecraft:armor_stand 0.5 212 -2026 {Tags:["incari_watch"],Invisible:1b,Marker:1b,NoGravity:1b,Rotation:[0f,35f]} + rcon:spectate @e[tag=incari_watch,limit=1] @s + rcon*10:summon minecraft:iron_golem 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b} + rcon*4:summon minecraft:vindicator 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b} + rcon*3:summon minecraft:pillager 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b} + rcon*3:summon minecraft:husk 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b} + rcon:spreadplayers 0 -2000 2 14 under 203 false @e[tag=incari_fighter] + sleep:5000 + measure:10 + rcon*4:summon minecraft:vindicator 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b} + rcon*3:summon minecraft:pillager 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b} + rcon*3:summon minecraft:husk 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b} + measure:10 + rcon*4:summon minecraft:vindicator 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b} + rcon*3:summon minecraft:pillager 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b} + rcon*3:summon minecraft:husk 0 200 -2000 {Tags:["incari_fighter"],PersistenceRequired:1b} + measure:10 + rcon:kill @e[tag=incari_fighter] + rcon:kill @e[tag=incari_watch] diff --git a/incari-client/files/app-web/browser-checks/README.md b/incari-client/files/app-web/browser-checks/README.md new file mode 100644 index 0000000..fa7ed92 --- /dev/null +++ b/incari-client/files/app-web/browser-checks/README.md @@ -0,0 +1,164 @@ +# Browser check scripts + +Step scripts for `./gradlew :app-web:browserCheck`, one step per line (`#` comments). They play the +game in headless Chromium over the DevTools protocol and fail on the first `assert:` or `waitfor:` +that doesn't hold. Positions are fractions of the 1280×720 window. Screenshots go to +`build/browser-checks/`. `BrowserCheck.runStep` lists every step. + +```sh +./gradlew :app-web:browserCheck -Pbrowser.steps=@browser-checks/input.steps +``` + +The page opens as `?name=Player` (straight to the title screen) unless the query names someone; +`-Pbrowser.query=name=` opens Edit Profile first. + +## Scripts + +| Script | Checks | Needs | +| --- | --- | --- | +| `input.steps` | Text fields, copy/paste, input methods, key names on a French layout, F11, resize, dropped files, Pointer Lock | — | +| `loader.steps` | Loading screen, manifest, service worker caching, reload from cache | — | +| `storage.steps` | An option, a server and an imported pack survive a reload; F2 stores a PNG | — | +| `assets.steps` | Japanese from the asset index: the Unicode font and the language file | assets | +| `audio.steps` | The sound unlock prompt, menu music after the first click, click sounds | assets | +| `audio-positional.steps` | Panning, rear attenuation and distance fade within 1% of the desktop's OpenAL | assets, server | +| `server-join.steps` | Join over `ws://`, chat, the Nether and back, a transfer, a kick and rejoin | server | +| `version-join.steps` | Join a 1.8.9, 1.12.2 or 1.20.4 server through Via; idle 20 s; kick and rejoin | old server | +| `screenshot.steps` | F2 in a world, then the chat link downloads the PNG | server | +| `community-pack.steps` | A real community resource pack loads | a pack | +| `soak.steps` | 30 minutes over fresh terrain; fails if the render thread ever waits 50 ms | server, GPU | +| `voice-talker.steps`, `voice-listener.steps` | Eagler voice chat between two browsers | EaglerXServer | +| `relay-join.steps` | Join a world shared through an Eagler relay | relay | +| `share-host.steps`, `share-guest.steps` | Host a singleplayer world on a relay; a second page joins it | relay | +| `singleplayer.steps` | Create, play, save and reopen a world; World Options; zip download and import; delete | — | +| `singleplayer-lan.steps` | Open to LAN with the server on the page fails cleanly | — | +| `modules.steps` | Module menu, Toggle Sprint, its settings, the profile saved | — | +| `hudeditor.steps` | HUD editor: drag an element, blurred backdrop, saved anchor | — | +| `waypoints.steps` | Minimap, a new waypoint, its tag and beam, the list, the world map, saved data | — | +| `newmodules.steps` | Each module from ADRs 0052–0054 turned on and seen working | — | +| `incari-settings.steps` | Block-break sounds, Incari Settings, the screen recorder (F8) | — | +| `look.steps`, `menus-look.steps` | The Frost look in Potato and Normal; menus checked for overlapping text | — | +| `old-textures.steps` | Built-in packs listed; Old Textures switches Programmer Art on and off | — | +| `sound-retry.steps` | Sounds still play when their first downloads fail | assets | +| `legacy-sounds.steps` | Block sounds on a 1.8.9 server through Via | old server | +| `html-sounds.steps` | The single HTML file plays sounds from disk (`-Pbrowser.html=`) | an HTML build | + +Not covered: typing in chat and most F3 keys (check by hand). `input.steps` stops on the Resource +Packs screen because leaving it reloads resources. Ctrl+W and Ctrl+T aren't sent: Chromium acts on +them outside fullscreen. + +## Setting up what checks need + +**Assets:** `./incari assets` once. The dev server serves them from `work/cache/assets`. + +**Server** (`server-join`, `screenshot`, `soak`, `audio-positional`): a vanilla 26.3 server behind +`tools/wsbridge`, with RCON, played as `IncariWeb`. The jar is Mojang's: keep it in `run/` (ignored), +never commit it or its world. + +```sh +mkdir -p run/server && cd run/server && echo eula=true > eula.txt +cat > server.properties <<'EOF' +server-ip=127.0.0.1 +server-port=25582 +online-mode=false +accepts-transfers=true +white-list=false +enable-rcon=true +rcon.port=25592 +rcon.password= +EOF +java -jar server.jar nogui # jar from work/cache/versions/26.3/26.3.json, downloads.server + +./gradlew :tools:wsbridge:run --args="--listen 8817 --target 127.0.0.1:25582" # another terminal + +INCARI_RCON_PASSWORD= ./gradlew :app-web:browserCheck \ + "-Pbrowser.query=server=ws://127.0.0.1:8817&name=IncariWeb" \ + -Pbrowser.rcon=127.0.0.1:25592 -Pbrowser.seconds=300 \ + -Pbrowser.steps=@browser-checks/server-join.steps +``` + +- `rcon:` runs a command; `rconwait: => ` repeats until the reply matches. +- RCON runs as the console, so `~` is the world spawn, not the player. Turn a player with + `execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~`. +- `soak.steps` also wants `-Pbrowser.gpu=gl -Pbrowser.seconds=2100`. + +**Old servers** (`version-join`): vanilla 1.8.9, 1.12.2 or 1.20.4 (1.8.9 and 1.12.2 need Java 8; +use `difficulty=0`), each behind its own bridge. The suggested ports: 1.8.9 on 25601 (RCON 25611, +bridge 8801), 1.12.2 on 25602/25612/8802, 1.20.4 on 25603/25613/8803. Add `&via=auto` to +`browser.query`: Via is off unless the join asks for it (ADR 0071). + +**EaglerXServer** (`version-join`, voice): BungeeCord with the EaglerXServer plugin (downloaded, +never committed) in front of the 1.8.9 server: `online_mode: false`, lobby `127.0.0.1:25601`, +`inject_address` equal to Bungee's listener host. Join `ws://127.0.0.1:25577`. For voice, set +`voice_service.enable_voice_service: true`, then run both scripts at once (Chromium gets a fake +microphone): + +```sh +INCARI_RCON_PASSWORD= ./gradlew :app-web:browserCheck "-Pbrowser.query=server=ws://127.0.0.1:25577&via=auto&name=VoiceA" \ + -Pbrowser.rcon=127.0.0.1:25611 -Pbrowser.seconds=200 -Pbrowser.steps=@browser-checks/voice-talker.steps & +sleep 8 +INCARI_RCON_PASSWORD= ./gradlew :app-web:browserCheck "-Pbrowser.query=server=ws://127.0.0.1:25577&via=auto&name=VoiceB" \ + -Pbrowser.rcon=127.0.0.1:25611 -Pbrowser.seconds=200 -Pbrowser.steps=@browser-checks/voice-listener.steps +``` + +The desktop checks voice signalling alone: `smokeVoiceA` and `smokeVoiceB` together. + +**Relay** (`relay-join`, `share-*`): EaglerSPRelay on port 6699 (its jar ships in the EaglercraftX +workspace's `relay_download.zip`; keep it in `run/`). + +```sh +# relay-join: relay-host.html is a stand-in host that prints a join code +java -jar run/relay/EaglerSPRelay.jar & +chrome --headless=new --enable-logging=stderr --user-data-dir=$(mktemp -d) \ + "file://$PWD/app-web/browser-checks/relay-host.html?relay=ws://127.0.0.1:6699/" 2> host.log & +sleep 5; CODE=$(grep -ao 'incari-relay-code: [a-z0-9]*' host.log | tail -1 | cut -d' ' -f2) +sed "s/CODE/$CODE/" app-web/browser-checks/relay-join.steps > build/relay.steps +./gradlew :app-web:browserCheck -Pbrowser.seconds=150 -Pbrowser.steps=@build/relay.steps + +# share-host + share-guest: the guest runs BrowserCheck directly (Gradle runs one build at a time; +# the class path is printed by the first run with --info) +./gradlew :app-web:browserCheck -Pbrowser.seconds=300 \ + "-Pbrowser.query=name=Host&world=Shared&seed=2&share=ws://127.0.0.1:6699/" \ + -Pbrowser.steps=@browser-checks/share-host.steps | tee host.log & +java -cp incari.tools.webbuild.BrowserCheck app-web/build/teavm \ + --query "name=Guest&shared=ws://127.0.0.1:6699/|" --seconds 240 \ + --steps-file app-web/browser-checks/share-guest.steps +``` + +**Community pack:** download one into the ignored `build/`, never the repo. Tested with Faithful 32x: + +```sh +mkdir -p app-web/build/community-packs +curl -L -o app-web/build/community-packs/pack.zip \ + "https://cdn.modrinth.com/data/w0TnApzs/versions/lDYpMiqk/Faithful%2032x%20-%2026.3.zip" +``` + +**Audio notes:** Chromium runs muted with `--autoplay-policy=document-user-activation-required`, so +audio starts locked as for a player; the scripts measure the page's master bus. DevTools +evaluations count as a click, so steps before the first click use `holds:` and `until:`. Desktop +reference numbers come from `./gradlew :platform-desktop:openAlReference`. + +`window.incariStorage.read(path)` in the page reads a stored file back (handy in the console too). + +## By hand, in a real browser + +Headless Chromium can't do everything. With `./gradlew :app-web:serve` and a world, check in Chrome +(and Firefox where noted): + +- [ ] **Pointer Lock:** clicking into a world hides the cursor; turning is smooth, with no acceleration on Windows. +- [ ] **Escape:** opens the pause menu; Back to Game locks again (perhaps after one more click). +- [ ] **Focus:** Alt+Tab or a tab switch pauses the game; no key stays held on return. +- [ ] **Fullscreen:** F11 and the video setting both toggle it. Inside, Escape pauses, and Ctrl+W and Ctrl+1–9 don't reach the browser. +- [ ] **Ctrl+W while playing:** asks "Leave site?". Nothing asks on the title screen. +- [ ] **F3 and chat:** F3+B/G/H/T work without browser side effects; chat typing, editing, history and Tab completion work. +- [ ] **Clipboard:** paste into chat from another program; copy out of a game text field; F3+C copies the location. +- [ ] **Key names:** on AZERTY, Key Binds shows Z/Q/S/D; names follow a layout switch (Chrome) or are learned as you type (Firefox). +- [ ] **Input methods and dead keys:** Japanese/Chinese composition shows in the field; ´ then e types é. +- [ ] **Resize and density:** window resize, browser zoom and a move to another display redraw sharply; clicks land right. +- [ ] **Dropped files:** a pack .zip or folder dropped on Resource Packs is offered and survives a reload. +- [ ] **Sound by ear:** the unlock note, then music; positional sounds turn with you and fade with distance; each volume slider only moves its category; jukeboxes pause and loop; no gaps between tracks. Also in Firefox. +- [ ] **Chromebook tablet mode:** tapping a text field opens the on-screen keyboard (note if it takes a second tap). +- [ ] **Storage after closing the browser:** an option, a server and a pack are all still there. Over plain http from another machine the console says `indexeddb` and it still works. +- [ ] **A second tab:** warns that the other tab keeps the files. +- [ ] **Downloads:** F2, then the chat link saves the PNG (Chrome, Safari, Firefox). +- [ ] **Closing right after a change:** the change is kept (the same-frame window is accepted, ADR 0011). diff --git a/incari-client/files/app-web/browser-checks/assets.steps b/incari-client/files/app-web/browser-checks/assets.steps new file mode 100644 index 0000000..8079381 --- /dev/null +++ b/incari-client/files/app-web/browser-checks/assets.steps @@ -0,0 +1,31 @@ +# ADR 0037: the Unicode font and the languages from the asset index (the panorama is no longer +# fetched: menus show Incari's photo). The language list draws 日本語 with the +# Unicode font; picking Japanese fetches its file before the reload, and the title screen is in +# Japanese. Positions are for the 1280x577 viewport headless Chromium gives a 1280x720 window. +# +# ./gradlew :app-web:browserCheck -Pbrowser.seconds=300 -Pbrowser.steps=@browser-checks/assets.steps + +sleep:4000 +# The first-run accessibility screen: Continue. +click:0.5,0.945 +sleep:3000 +shot:build/browser-checks/assets-title.png +# Options, Language..., search for Japan's region name. +click:0.42,0.782 +sleep:1500 +click:0.376,0.515 +sleep:1500 +insert:日本 +sleep:1000 +shot:build/browser-checks/assets-language.png +click:0.5,0.17 +sleep:500 +# Done reloads the resources in Japanese. +click:0.62,0.945 +wait:.*\[Incari\] Assets: fetched 1 files .* +sleep:8000 +# Back to the title screen. +click:0.5,0.945 +sleep:3000 +shot:build/browser-checks/assets-title-ja.png +assert:window.incariStorage.read('/incari/game/options.txt').then(t => t !== null && t.includes('lang:ja_jp')) diff --git a/incari-client/files/app-web/browser-checks/audio-positional.steps b/incari-client/files/app-web/browser-checks/audio-positional.steps new file mode 100644 index 0000000..be1a91a --- /dev/null +++ b/incari-client/files/app-web/browser-checks/audio-positional.steps @@ -0,0 +1,82 @@ +# Positional sound, measured. The page joins a vanilla 26.3 server over ws:// (as +# server-join.steps does), floats in the sky facing south, and the server plays a mono note +# (block.note_block.harp, heard up to 16 blocks) at known offsets. A meter on the master bus sums +# each channel's energy; the ratios must match what the desktop's OpenAL Soft gives for the same +# offsets (measured by :platform-desktop:openAlReference, ADR 0013): +# 4 blocks to the right left/right = 0.000 (0.0000 / 0.7497) +# 30° to the left (2 left, 3.5 ahead) right/left = 0.236 (0.2169 / 0.9192 before distance) +# 4 blocks ahead vs 4 behind behind/ahead = 0.679 (0.4041 / 0.5955 per ear) +# 12 blocks ahead vs 4 ahead far/near = 0.333 (linear: 1 - d/16) +# README.md ("Audio") has the setup: a server with RCON behind tools/wsbridge. + +rcon:whitelist off +rcon:difficulty peaceful +rcon:time set day +rcon:weather clear + +# The first-run accessibility screen: Continue, which also unlocks the sound. Quick play connects. +sleep:4000 +click:0.5,0.945 +waitfor:incariAudio.context.state === 'running' +rconwait:list => IncariWeb +sleep:3000 + +# In the sky, where nothing else makes a sound: spectator (no footsteps), at a known eye position. +# Facing south (yaw 0): forward is +z, right is -x. The eye is 1.62 above the feet. +rcon:gamemode spectator IncariWeb +rcon:tp IncariWeb 0.5 200 0.5 0 0 +sleep:3000 +rcon:stopsound IncariWeb + +# Music is stereo and starts on its own schedule: mute every stream, now and later, so only the +# note is measured. +rcon:stopsound IncariWeb music +eval:(() => { const play = HTMLMediaElement.prototype.play; HTMLMediaElement.prototype.play = function () { this.muted = true; return play.call(this); }; incariAudio.streams.forEach(e => { e.muted = true; }); return 'music muted'; })() +# The meter: each channel of the master bus, summed over one burst of sound: from the first +# audible block after it's armed until the level falls 30 dB below the burst's peak (by then over +# 99.9% of the note's energy is in). The note rings for about half a second; the game plays quiet +# sounds of its own (ambience) just after, which the burst leaves out. +eval:(() => { const a = incariAudio, ctx = a.context; const p = ctx.createScriptProcessor(1024, 2, 2); const m = { l: 0, r: 0, now: 0, state: 'idle', runs: {} }; p.onaudioprocess = e => { const l = e.inputBuffer.getChannelData(0), r = e.inputBuffer.getChannelData(1); let sl = 0, sr = 0; for (let i = 0; i < l.length; i++) { sl += l[i] * l[i]; sr += r[i] * r[i]; } m.now = sl + sr; if (m.state === 'armed' && m.now > 1e-6) m.state = 'burst'; if (m.state === 'burst') { m.peak = Math.max(m.peak, m.now); if (m.now < m.peak * 1e-3) m.state = 'done'; else { m.l += sl; m.r += sr; } } }; const g = ctx.createGain(); g.gain.value = 0; a.master.connect(p); p.connect(g); g.connect(ctx.destination); m.arm = () => { m.l = 0; m.r = 0; m.peak = 0; m.state = 'armed'; }; m.keep = name => { m.runs[name] = { l: Math.sqrt(m.l), r: Math.sqrt(m.r) }; return name + ': left ' + m.runs[name].l.toFixed(4) + ', right ' + m.runs[name].r.toFixed(4); }; globalThis.incariMeter = m; return 'meter on'; })() +# Quiet first: whatever was playing dies away. +waitfor:incariMeter.now < 1e-7 + +# 4 blocks to the right. +waitfor:incariMeter.now < 1e-7 +eval:incariMeter.arm() +rcon:playsound minecraft:block.note_block.harp master IncariWeb -3.5 201.625 0.5 1 1 +waitfor:incariMeter.state === 'done' +eval:incariMeter.keep('right') +# About 30° to the left of straight ahead: +x is left, so 2 blocks that way and 3.5 ahead. Sound +# packets carry positions in eighths of a block, so every offset here is a multiple of one. Write +# every coordinate with a decimal point: commands centre a whole number on its block (4 is 4.5). +waitfor:incariMeter.now < 1e-7 +eval:incariMeter.arm() +rcon:playsound minecraft:block.note_block.harp master IncariWeb 2.5 201.625 4.0 1 1 +waitfor:incariMeter.state === 'done' +eval:incariMeter.keep('left30') +# 4 blocks ahead, 4 behind, 12 ahead. +waitfor:incariMeter.now < 1e-7 +eval:incariMeter.arm() +rcon:playsound minecraft:block.note_block.harp master IncariWeb 0.5 201.625 4.5 1 1 +waitfor:incariMeter.state === 'done' +eval:incariMeter.keep('ahead4') +waitfor:incariMeter.now < 1e-7 +eval:incariMeter.arm() +rcon:playsound minecraft:block.note_block.harp master IncariWeb 0.5 201.625 -3.5 1 1 +waitfor:incariMeter.state === 'done' +eval:incariMeter.keep('behind4') +waitfor:incariMeter.now < 1e-7 +eval:incariMeter.arm() +rcon:playsound minecraft:block.note_block.harp master IncariWeb 0.5 201.625 12.5 1 1 +waitfor:incariMeter.state === 'done' +eval:incariMeter.keep('ahead12') + +# The ratios, against the desktop's. +eval:JSON.stringify(Object.fromEntries(Object.entries(incariMeter.runs).map(([k, v]) => [k, [+v.l.toFixed(4), +v.r.toFixed(4)]]))) +eval:'right: left/right ' + (incariMeter.runs.right.l / incariMeter.runs.right.r).toFixed(4) + '; left30: right/left ' + (incariMeter.runs.left30.r / incariMeter.runs.left30.l).toFixed(4) + '; behind/ahead ' + (incariMeter.runs.behind4.l / incariMeter.runs.ahead4.l).toFixed(4) + '; far/near ' + (incariMeter.runs.ahead12.l / incariMeter.runs.ahead4.l).toFixed(4) +assert:incariMeter.runs.right.r > 0.01 && incariMeter.runs.right.l / incariMeter.runs.right.r < 0.005 +assert:Math.abs(incariMeter.runs.left30.r / incariMeter.runs.left30.l - 0.2360) < 0.01 +assert:Math.abs(incariMeter.runs.ahead4.l / incariMeter.runs.ahead4.r - 1) < 0.005 +assert:Math.abs(incariMeter.runs.behind4.l / incariMeter.runs.ahead4.l - 0.6787) < 0.01 +assert:Math.abs(incariMeter.runs.ahead12.l / incariMeter.runs.ahead4.l - 0.3333) < 0.01 +shot:build/browser-checks/audio-positional.png diff --git a/incari-client/files/app-web/browser-checks/audio.steps b/incari-client/files/app-web/browser-checks/audio.steps new file mode 100644 index 0000000..602d62d --- /dev/null +++ b/incari-client/files/app-web/browser-checks/audio.steps @@ -0,0 +1,44 @@ +# Sound on the title screen. The page starts with its audio context suspended, as a player's +# browser does (BrowserCheck runs Chromium with --autoplay-policy=document-user-activation-required, muted on +# this machine's speakers), and shows the unlock prompt; the first click resumes it. Then the menu +# music streams through a media element, and a button's click plays. Needs the assets +# `./incari assets` downloaded (the dev server serves them). README.md ("Audio") has the command. + +# --- Before any gesture: the context waits, and the prompt says so --- +# (The check starts once the game loop runs; by then the sound engine has started.) +# Until the click below, steps use holds:/until:, which don't count as a click themselves. +sleep:3000 +until:globalThis.incariAudio !== undefined && incariAudio.context.state === 'suspended' +holds:document.getElementById('incari-audio-unlock') !== null +# The menu music has been asked for by now (100 ticks after the game starts) and waits for the context. +until:incariAudio.pending.length === 1 && incariAudio.streamsStarted === 0 && incariAudio.buffersStarted === 0 +shot:build/browser-checks/audio-prompt.png + +# --- The first-run accessibility screen's Continue: that click unlocks the sound --- +click:0.5,0.945 +waitfor:incariAudio.context.state === 'running' && document.getElementById('incari-audio-unlock') === null +# The waiting music starts, and its element streams: it plays long before the whole file could have +# been decoded, and its position moves. +waitfor:incariAudio.streamsStarted >= 1 && incariAudio.streams.some(e => !e.paused && e.currentTime > 0.5) +eval:incariAudio.streams.map(e => e.src.slice(0, 5) + ' ' + e.currentTime.toFixed(2) + 's of ' + e.duration.toFixed(1) + 's').join(', ') +sleep:2000 +assert:incariAudio.streams.some(e => !e.paused && e.currentTime > 2) + +# --- A meter on the master bus: each channel's energy, from every sample the page plays --- +eval:(() => { const a = incariAudio, ctx = a.context; const p = ctx.createScriptProcessor(4096, 2, 2); const m = { l: 0, r: 0, n: 0 }; p.onaudioprocess = e => { const l = e.inputBuffer.getChannelData(0), r = e.inputBuffer.getChannelData(1); for (let i = 0; i < l.length; i++) { m.l += l[i] * l[i]; m.r += r[i] * r[i]; } m.n += l.length; }; const g = ctx.createGain(); g.gain.value = 0; a.master.connect(p); p.connect(g); g.connect(ctx.destination); globalThis.incariMeter = m; return 'meter on'; })() +sleep:1000 +# The music reaches the output: stereo, so both channels. +assert:incariMeter.n > 40000 && incariMeter.l > 0 && incariMeter.r > 0 + +# --- A UI sound: a button's click (a stereo sound, not positioned) --- +eval:globalThis.clicksBefore = incariAudio.buffersStarted +# Options... (its click), Escape back to the title screen, Options... again. +click:0.42,0.78 +sleep:1500 +shot:build/browser-checks/audio-options.png +key:Escape +sleep:1000 +click:0.42,0.78 +sleep:500 +waitfor:incariAudio.buffersStarted >= clicksBefore + 2 +eval:'buffers started: ' + incariAudio.buffersStarted + ', voices: ' + incariAudio.voices diff --git a/incari-client/files/app-web/browser-checks/community-pack.steps b/incari-client/files/app-web/browser-checks/community-pack.steps new file mode 100644 index 0000000..678d217 --- /dev/null +++ b/incari-client/files/app-web/browser-checks/community-pack.steps @@ -0,0 +1,41 @@ +# A real community resource pack loads. It's the one at build/community-packs/pack.zip, +# downloaded when the check runs, never committed (the browser-checks README says how; the check +# was run with Faithful 32x for 26.3). It's dropped on the Resource Packs screen, copied in, +# selected, and the game reloads its resources with it; then the page is reloaded and the game +# starts with it from storage. Positions are for the 1280x577 viewport. +# +# ./gradlew :app-web:browserCheck -Pbrowser.seconds=500 -Pbrowser.steps=@browser-checks/community-pack.steps + +sleep:4000 +# The first-run accessibility screen: Continue. +click:0.5,0.945 +sleep:3000 +# Options, Resource Packs, then the pack dropped on the screen and "Yes" to copy it. +click:0.42,0.782 +sleep:1500 +click:0.376,0.598 +sleep:2000 +drop:0.5,0.5,build/community-packs/pack.zip +sleep:4000 +click:0.38,0.585 +sleep:3000 +waitfor:window.incariStorage.list('/incari/game/resourcepacks').then(p => p.includes('/incari/game/resourcepacks/pack.zip')) +move:0.19,0.277 +sleep:300 +click:0.19,0.277 +sleep:1000 +shot:build/browser-checks/community-pack-selected.png +# Done: the game reloads its resources with the pack, which must finish without errors. +click:0.623,0.945 +wait:.*Reloading ResourceManager.*file/pack\.zip.* +wait:\[Incari\] Main loop running.* +sleep:3000 +shot:build/browser-checks/community-pack-title.png +waitfor:window.incariStorage.pending() === 0 +# After a reload the game starts with it. +reload +wait:\[Incari\] Client jar: .* from storage.* +wait:.*Reloading ResourceManager.*file/pack\.zip.* +wait:\[Incari\] Main loop running.* +sleep:4000 +shot:build/browser-checks/community-pack-after-reload.png diff --git a/incari-client/files/app-web/browser-checks/html-sounds.steps b/incari-client/files/app-web/browser-checks/html-sounds.steps new file mode 100644 index 0000000..63e9cd5 --- /dev/null +++ b/incari-client/files/app-web/browser-checks/html-sounds.steps @@ -0,0 +1,41 @@ +# The single HTML file's sounds (ADR 0062: all but music, smaller): opened from the disk, a quick world's block +# breaks play their sounds from the file. Build it first (./incari build --html --only fast), then: +# +# ./gradlew :app-web:browserCheck -Pteavm.fast -Pbrowser.html=$PWD/dist/incari.html -Pbrowser.gpu=gl \ +# -Pbrowser.seconds=300 "-Pbrowser.query=name=Player&world=Html&seed=1" \ +# -Pbrowser.steps=@browser-checks/html-sounds.steps + +sleep:6000 +# The first-run accessibility screen: Continue (also the gesture the audio waits for). +click:0.5,0.945 +wait:.*logged in with entity id.* +sleep:6000 +eval:globalThis.before = incariAudio.buffersStarted + +key:KeyT +sleep:800 +type:/fill ~-4 ~ ~-4 ~4 ~4 ~4 minecraft:air +key:Enter +sleep:800 +key:KeyT +sleep:800 +type:/fill ~-4 ~-3 ~-4 ~4 ~-1 ~4 minecraft:stone +key:Enter +sleep:800 +key:KeyT +sleep:800 +type:/gamemode creative +key:Enter +sleep:800 +key:KeyT +sleep:800 +type:/tp @s ~ ~ ~ 0 90 +key:Enter +sleep:1500 +click:0.5,0.5 +sleep:1500 +click:0.5,0.5 +sleep:1500 +click:0.5,0.5 +sleep:3000 +eval:'buffers started: ' + (incariAudio.buffersStarted - before) diff --git a/incari-client/files/app-web/browser-checks/hudeditor.steps b/incari-client/files/app-web/browser-checks/hudeditor.steps new file mode 100644 index 0000000..0cd52dc --- /dev/null +++ b/incari-client/files/app-web/browser-checks/hudeditor.steps @@ -0,0 +1,42 @@ +# The HUD editor in the page, in the Potato GUI preset (the default), where its blurred +# backdrop is drawn a few times a second and kept in between (BackdropCache). Creates a world, turns +# Toggle Sprint on from the module menu, opens Edit HUD beside the search, drags the status line +# from the top left to the right edge halfway down, and checks the profile stored in OPFS has it +# anchored on the right. No server needed. Positions are for the 1280x577 viewport (GUI scale 2, +# 640x288). +# +# ./gradlew :app-web:browserCheck -Pbrowser.gpu=gl -Pbrowser.seconds=300 -Pbrowser.steps=@browser-checks/hudeditor.steps + +sleep:4000 +# The first-run accessibility screen: Continue. Then Singleplayer, Create New World with the defaults. +click:0.5,0.945 +sleep:3000 +click:0.2,0.43 +sleep:4000 +click:0.38,0.945 +wait:.*logged in with entity id.* +sleep:8000 + +# --- The module menu: Toggle Sprint on, then Edit HUD --- +key:ShiftRight +sleep:1500 +click:0.545,0.215 +sleep:500 +click:0.798,0.104 +sleep:2000 +move:0.5,0.7 +sleep:500 +shot:build/browser-checks/hudeditor-potato.png + +# --- The status line dragged to the right edge, halfway down: it snaps there --- +drag:0.019,0.021,0.953,0.5 +sleep:800 +shot:build/browser-checks/hudeditor-placed.png + +# --- Back to the module menu and the game; the placement is stored --- +key:Escape +sleep:800 +key:Escape +sleep:2500 +until:window.incariStorage.pending() === 0 +assert:(async () => { let d = await navigator.storage.getDirectory(); for (const p of ["incari", "game", "incari", "modules", "profiles"]) d = await d.getDirectoryHandle(p); const text = await (await (await d.getFileHandle("Default.json")).getFile()).text(); console.log("[check] profile: " + text.replace(/\s+/g, " ")); const status = JSON.parse(text).modules.togglesprint.hud.status; return status.anchor === "right" && status.x === 2; })() diff --git a/incari-client/files/app-web/browser-checks/incari-settings.steps b/incari-client/files/app-web/browser-checks/incari-settings.steps new file mode 100644 index 0000000..fb4bfa9 --- /dev/null +++ b/incari-client/files/app-web/browser-checks/incari-settings.steps @@ -0,0 +1,75 @@ +# ADR 0062: in a quick world (-Pbrowser.query=name=Player&world=Batch&seed=1): the pause menu's one +# Incari Settings button and its screen, the screen recorder downloading a video (F8 twice), and +# block-breaking sounds: each break's sound fetched, decoded and started. No server needed. +# +# ./gradlew :app-web:browserCheck -Pbrowser.gpu=gl -Pbrowser.seconds=300 \ +# "-Pbrowser.query=name=Player&world=Batch&seed=1" -Pbrowser.steps=@browser-checks/incari-settings.steps + +downloads:build/browser-checks/downloads +sleep:4000 +# The first-run accessibility screen: Continue (also the gesture the audio waits for). +click:0.5,0.945 +wait:.*logged in with entity id.* +sleep:6000 +# Every sound file fetched from now on, with its status and time. +eval:(() => { const of = window.fetch; globalThis.fetchLog = []; window.fetch = (u, ...a) => { const t = performance.now(); return of(u, ...a).then(r => { if (String(u).includes('objects')) fetchLog.push(r.status + ' ' + Math.round(performance.now() - t) + 'ms'); return r; }, e => { fetchLog.push('ERR ' + u); throw e; }); }; return 'logging'; })() +eval:'buffers started before: ' + incariAudio.buffersStarted + +# --- On a dirt floor, looking straight down: creative breaks a block a click --- +key:KeyT +sleep:800 +type:/fill ~-4 ~ ~-4 ~4 ~4 ~4 minecraft:air +key:Enter +sleep:800 +key:KeyT +sleep:800 +type:/fill ~-4 ~-3 ~-4 ~4 ~-1 ~4 minecraft:dirt +key:Enter +sleep:800 +key:KeyT +sleep:800 +type:/gamemode creative +key:Enter +sleep:800 +key:KeyT +sleep:800 +type:/tp @s ~ ~ ~ 0 90 +key:Enter +sleep:1500 +click:0.5,0.5 +sleep:800 +click:0.5,0.5 +sleep:800 +click:0.5,0.5 +sleep:2000 +eval:'buffers started after breaking: ' + incariAudio.buffersStarted + ', fetches: ' + JSON.stringify(fetchLog) +shot:build/browser-checks/batch-broken.png + +# --- Survival: held, the dirt's hit sounds every 4 ticks and its break --- +key:KeyT +sleep:800 +type:/gamemode survival +key:Enter +sleep:1000 +eval:globalThis.beforeHold = incariAudio.buffersStarted +hold:0.5,0.5,4000 +sleep:1500 +eval:'buffers started while holding: ' + (incariAudio.buffersStarted - beforeHold) + ', fetches: ' + JSON.stringify(fetchLog) +shot:build/browser-checks/batch-mined.png + +# --- The pause menu and Incari Settings --- +key:Escape +sleep:1500 +shot:build/browser-checks/batch-pause.png + +# --- The recorder: F8 starts, F8 stops, and the video downloads --- +key:Escape +sleep:1000 +key:F8 +waitfor:globalThis.incariRecorder && incariRecorder.state === 'recording' +sleep:4000 +shot:build/browser-checks/batch-recording.png +key:F8 +waitfor:incariRecorder.state === 'idle' +eval:'recorder error: ' + incariRecorder.error +download:incari-.*\.(webm|mp4) diff --git a/incari-client/files/app-web/browser-checks/input.steps b/incari-client/files/app-web/browser-checks/input.steps new file mode 100644 index 0000000..7246f57 --- /dev/null +++ b/incari-client/files/app-web/browser-checks/input.steps @@ -0,0 +1,170 @@ +# Keyboard, mouse, text, clipboard, key names, fullscreen, resize and drops, on the title +# screen and its menus. Positions are for the 1280x577 +# viewport headless Chromium gives a 1280x720 window. +# +# ./gradlew :app-web:browserCheck -Pbrowser.steps=@browser-checks/input.steps + +# A French (AZERTY) layout, as Chrome's Keyboard Map API would report it, for every load from now on. +init:(function() { var fr = {KeyQ: 'a', KeyW: 'z', KeyA: 'q', KeyZ: 'w', KeyM: ',', Semicolon: 'm', Digit1: '&', Digit2: 'é', Minus: ')', BracketLeft: '^'}; var kb = navigator.keyboard; if (kb) kb.getLayoutMap = function() { return Promise.resolve(new Map(Object.entries(fr))); }; })(); +# The reloaded page's start (the first page's heartbeats may still be queued before it). +wait:\[Incari\] Client jar.* +wait:\[Incari\] Main loop running.* +sleep:4000 +# The first-run accessibility screen: Continue. +click:0.5,0.945 +sleep:3000 +shot:build/browser-checks/title.png + +# --- Nothing on the title screen holds the mouse, so leaving asks nothing --- +assert:!document.getElementById('incari-canvas').__incariGuard + +# --- Fullscreen in and out with F11 --- +key:F11 +waitfor:document.fullscreenElement === document.getElementById('incari-canvas') +sleep:1000 +assert:document.getElementById('incari-canvas').width === screen.width +shot:build/browser-checks/fullscreen.png +key:F11 +waitfor:!document.fullscreenElement +sleep:1000 +assert:document.getElementById('incari-canvas').width === innerWidth +# Leaving from the browser's side (Escape, the browser's own controls) turns the game's option off, +# so the next F11 enters again rather than doing nothing. +key:F11 +waitfor:!!document.fullscreenElement +eval:document.exitFullscreen() +waitfor:!document.fullscreenElement +sleep:1000 +key:F11 +waitfor:!!document.fullscreenElement +eval:document.exitFullscreen() +waitfor:!document.fullscreenElement +sleep:1000 + +# --- Resize and density --- +resize:960,540 +waitfor:document.getElementById('incari-canvas').width === 960 && document.getElementById('incari-canvas').height === 540 +sleep:1000 +shot:build/browser-checks/resized.png +# A denser display: the backing store follows the device-pixel size the browser reports. (Headless +# Chromium's emulated density reports the CSS size here, as its compositor does the scaling; a real +# 2x display reports twice it, which the unit tests cover.) +resize:640,360,2 +waitfor:devicePixelRatio === 2 && document.getElementById('incari-canvas').clientWidth === 640 +waitfor:new Promise(r => { const c = document.getElementById('incari-canvas'); const o = new ResizeObserver(es => { const d = es[0].devicePixelContentBoxSize[0]; o.disconnect(); r(c.width === d.inlineSize && c.height === d.blockSize); }); o.observe(c, {box: 'device-pixel-content-box'}); }) +sleep:1000 +shot:build/browser-checks/dense.png +resize:1280,577 +waitfor:document.getElementById('incari-canvas').width === 1280 && document.getElementById('incari-canvas').height === 577 +sleep:1500 +# Clicks land where the game drew after all that: Multiplayer, then Proceed on the safety screen. +click:0.5,0.534 +sleep:1500 +shot:build/browser-checks/multiplayer-warning.png +click:0.376,0.688 +sleep:1500 +# Add Server. +click:0.662,0.854 +sleep:1500 + +# --- Text: typing, selection, copy and paste, an input method --- +# The name field has the focus, so the page's text input element has it too. +assert:document.activeElement === document.getElementById('incari-canvas-text') +key:Control+KeyA +type:Hello Incari +clipboard: +key:Control+KeyA +key:Control+KeyC +waitfor:navigator.clipboard.readText().then(t => t === 'Hello Incari') +clipboard: & pasted +key:End +key:Control+KeyV +# Shift+Left twice selects the last two characters, and Backspace deletes them. +down:ShiftLeft +key:ArrowLeft +key:ArrowLeft +up:ShiftLeft +key:Backspace +# An input method: a composition shows in the field, then commits. +compose:にほ +sleep:500 +shot:build/browser-checks/composing.png +insert:日本 +type:! +key:Control+KeyA +key:Control+KeyX +waitfor:navigator.clipboard.readText().then(t => t === 'Hello Incari & past日本!') +sleep:500 +shot:build/browser-checks/cut.png +# Tab moves to the address field; the browser mustn't move its own focus. +key:Tab +type:localhost +key:Control+KeyA +key:Control+KeyC +waitfor:navigator.clipboard.readText().then(t => t === 'localhost') +assert:document.activeElement === document.getElementById('incari-canvas-text') +# Escape leaves the screen, and text input with it. +key:Escape +sleep:800 +key:Escape +sleep:800 +waitfor:document.activeElement !== document.getElementById('incari-canvas-text') + +# --- Key names in the player's layout, and binding a key --- +# Options, Controls, Key Binds. +click:0.42,0.782 +sleep:1500 +click:0.623,0.432 +sleep:1500 +click:0.623,0.161 +sleep:1500 +# With AZERTY, strafe left is Q and walking forward Z; the rest keep their US names. +shot:build/browser-checks/key-binds.png +# Bind "Walk Forward" to the key right of Tab: AZERTY's A. +click:0.617,0.64 +sleep:500 +key:KeyQ +sleep:800 +shot:build/browser-checks/key-bound.png +# Back to W, which the Reset button next to it does. +click:0.722,0.64 +sleep:800 +key:Escape +sleep:800 +key:Escape +sleep:800 + +# --- F3 and browser shortcuts: the game gets them, the browser does nothing --- +# (On the Options screen, where these keys change nothing in the game.) +# A mark on the page that a reload or navigation would wipe. +eval:window.__incariCheckMark = 1 +# F3 shows the debug screen here too, memory lines and all; the game keeps running under it, and a +# second F3 hides it. +key:F3 +sleep:1500 +shot:build/browser-checks/debug-screen.png +wait:\[Incari\] Main loop running.* +key:F3 +sleep:500 +# Not Ctrl+W or Ctrl+T: Chromium keeps those outside fullscreen whatever the page does (sent here, +# Ctrl+W closes the tab). The leave-page prompt and Keyboard Lock are on the manual checklist. +key:F5 +key:Alt+ArrowLeft +sleep:1000 +assert:window.__incariCheckMark === 1 +assert:document.activeElement === document.getElementById('incari-canvas') +shot:build/browser-checks/after-shortcuts.png + +# --- A dropped file --- +# Resource Packs, then a file dropped on it: the game asks whether to copy it in. +click:0.376,0.598 +sleep:2000 +drop:0.5,0.5,browser-checks/README.md +sleep:2000 +shot:build/browser-checks/dropped.png +# "No". Leaving the pack screen reloads resources, which restarts the sound engine, and that +# crashes the browser build today (the old sound thread ends with an IllegalMonitorStateException; +# audio has checks of its own): the script stops here. +click:0.62,0.585 +sleep:1000 +shot:build/browser-checks/packs.png diff --git a/incari-client/files/app-web/browser-checks/legacy-sounds.steps b/incari-client/files/app-web/browser-checks/legacy-sounds.steps new file mode 100644 index 0000000..6ff78d9 --- /dev/null +++ b/incari-client/files/app-web/browser-checks/legacy-sounds.steps @@ -0,0 +1,27 @@ +# F1 (2026-10-12): block sounds on a 1.8.9 server through Via. The server behind tools/wsbridge on +# 8801 with RCON on 25611 (run/servers, INCARI_RCON_PASSWORD=incari-dev): +# "-Pbrowser.query=server=ws://127.0.0.1:8801&name=IncariWeb" -Pbrowser.rcon=127.0.0.1:25611 +sleep:4000 +click:0.5,0.945 +sleep:15000 +eval:(() => { const of = window.fetch; globalThis.fetchLog = []; window.fetch = (u, ...a) => { const t = performance.now(); return of(u, ...a).then(r => { if (String(u).includes('objects')) fetchLog.push(r.status + ' ' + Math.round(performance.now() - t) + 'ms'); return r; }, e => { fetchLog.push('ERR ' + u); throw e; }); }; return 'logging'; })() +rcon:execute IncariWeb ~ ~ ~ fill ~-3 ~ ~-3 ~3 ~3 ~3 air +rcon:execute IncariWeb ~ ~ ~ fill ~-3 ~-3 ~-3 ~3 ~-1 ~3 dirt +rcon:execute IncariWeb ~ ~ ~ tp IncariWeb ~ ~ ~ 0 90 +rcon:gamemode 1 IncariWeb +sleep:2000 +eval:globalThis.before = incariAudio.buffersStarted +click:0.5,0.5 +sleep:800 +click:0.5,0.5 +sleep:800 +click:0.5,0.5 +sleep:2000 +eval:'creative breaks started ' + (incariAudio.buffersStarted - before) + ', fetches ' + JSON.stringify(fetchLog) +rcon:gamemode 0 IncariWeb +sleep:1500 +eval:globalThis.before = incariAudio.buffersStarted +hold:0.5,0.5,4000 +sleep:1500 +eval:'survival mining started ' + (incariAudio.buffersStarted - before) + ', fetches ' + JSON.stringify(fetchLog) +shot:build/browser-checks/legacy-mined.png diff --git a/incari-client/files/app-web/browser-checks/loader.steps b/incari-client/files/app-web/browser-checks/loader.steps new file mode 100644 index 0000000..57ddad4 --- /dev/null +++ b/incari-client/files/app-web/browser-checks/loader.steps @@ -0,0 +1,26 @@ +# The loader page. The loading screen reads the build manifest, shows the steps, and goes at +# the game's first frame; the service worker takes the page on its first visit and keeps the build, +# so a reload loads the module through it. No server needed. +# +# ./gradlew :app-web:browserCheck -Pbrowser.steps=@browser-checks/loader.steps + +# (The check waits for the game's loop before the first step, so the loader's own lines are past.) +until:window.incariBuild !== undefined && /^[0-9a-f]{64}$/.test(window.incariBuild.id) && window.incariBuild.pack !== null +# The first frame is drawn: the screen has gone. +until:document.getElementById('incari-loader').hidden === true +# The service worker controls the page, and the module went through it. +until:navigator.serviceWorker.controller !== null +holds:performance.getEntriesByType('resource').some(e => e.name.includes('incari.wasm?v=') && e.workerStart > 0) +# It's cached under its version (stored while the page compiled it; 157 MB can take a moment). +sleep:5000 +until:caches.open('incari-build-v1').then(c => c.keys()).then(k => k.some(r => r.url.includes('incari.wasm?v='))) +until:caches.open('incari-build-v1').then(c => c.keys()).then(k => k.some(r => r.url.includes('incari.pack?v='))) + +# A returning player: the module comes from the service worker's cache. +reload +wait:\[Incari\] Loader: build [0-9a-f]+ .* +wait:\[Incari\] Asset pack: 2 files, from storage.* +wait:\[Incari\] Main loop running.* +holds:performance.getEntriesByType('resource').some(e => e.name.includes('incari.wasm?v=') && e.workerStart > 0) +until:document.getElementById('incari-loader').hidden === true +shot:build/browser-checks/loader.png diff --git a/incari-client/files/app-web/browser-checks/look.steps b/incari-client/files/app-web/browser-checks/look.steps new file mode 100644 index 0000000..dbeb427 --- /dev/null +++ b/incari-client/files/app-web/browser-checks/look.steps @@ -0,0 +1,52 @@ +# ADR 0048: the client's look in the page. The title screen in Potato, the options, the module +# menu, then Normal switched on from the module menu's sidebar: the title again (snow, blur), then a +# new world's pause menu, inventory and HUD. Red Hat Display is drawn by the browser's canvas +# (PlatformFonts). No server needed. Positions are for the 1280x577 viewport (GUI scale 2, 640x288). +# +# ./gradlew :app-web:browserCheck -Pbrowser.gpu=gl -Pbrowser.seconds=300 -Pbrowser.steps=@browser-checks/look.steps + +sleep:4000 +# The first-run accessibility screen: Continue. +click:0.5,0.945 +sleep:3000 +shot:build/browser-checks/look-potato-title.png + +# Options (the left half of the column's last row), and back. +click:0.133,0.691 +sleep:1500 +shot:build/browser-checks/look-potato-options.png +key:Escape +sleep:1000 + +# Modules, then the sidebar's GUI entry: Normal. +click:0.2,0.604 +sleep:1500 +shot:build/browser-checks/look-potato-modules.png +click:0.2,0.771 +sleep:1000 +shot:build/browser-checks/look-normal-modules.png +key:Escape +sleep:2000 +shot:build/browser-checks/look-normal-title.png + +# Singleplayer, Create New World with the defaults. +click:0.2,0.43 +sleep:3000 +click:0.38,0.945 +wait:.*logged in with entity id.* +sleep:8000 +shot:build/browser-checks/look-normal-hud.png +key:Escape +sleep:1500 +shot:build/browser-checks/look-normal-pause.png +key:Escape +sleep:800 +key:KeyE +sleep:1500 +shot:build/browser-checks/look-normal-inventory.png +key:Escape +sleep:800 +down:Tab +sleep:800 +shot:build/browser-checks/look-normal-tab.png +up:Tab diff --git a/incari-client/files/app-web/browser-checks/menus-look.steps b/incari-client/files/app-web/browser-checks/menus-look.steps new file mode 100644 index 0000000..eca7c56 --- /dev/null +++ b/incari-client/files/app-web/browser-checks/menus-look.steps @@ -0,0 +1,27 @@ +# F2 (2026-10-12): the menus as the browser draws their text, to look for text drawn over text. +# Title, Multiplayer (the featured server), Options, the module menu, Incari Settings. No server. +sleep:4000 +click:0.5,0.945 +sleep:3000 +shot:build/browser-checks/menus-title.png +click:0.2,0.49 +sleep:1500 +# The first visit's warning: Proceed. +click:0.375,0.688 +sleep:3000 +shot:build/browser-checks/menus-servers.png +key:Escape +sleep:1500 +click:0.13,0.74 +sleep:2000 +shot:build/browser-checks/menus-options.png +key:Escape +sleep:1500 +click:0.2,0.573 +sleep:2000 +shot:build/browser-checks/menus-modules.png +key:Escape +sleep:1500 +click:0.3,0.657 +sleep:2000 +shot:build/browser-checks/menus-incari-settings.png diff --git a/incari-client/files/app-web/browser-checks/modules.steps b/incari-client/files/app-web/browser-checks/modules.steps new file mode 100644 index 0000000..1467967 --- /dev/null +++ b/incari-client/files/app-web/browser-checks/modules.steps @@ -0,0 +1,45 @@ +# ADR 0046: the module framework in the page. Creates a world, opens the module menu with +# Right Shift, turns Toggle Sprint on with its switch, opens its generated settings, then latches +# sprint with a tap of Left Control and walks: the HUD says "[Sprinting (Toggled)]". The profile is +# stored in OPFS with the module on. No server needed. Positions are for the 1280x577 viewport. +# +# ./gradlew :app-web:browserCheck -Pbrowser.gpu=gl -Pbrowser.seconds=300 -Pbrowser.steps=@browser-checks/modules.steps + +sleep:4000 +# The first-run accessibility screen: Continue. Then Singleplayer, Create New World with the defaults. +click:0.5,0.945 +sleep:3000 +click:0.2,0.43 +sleep:4000 +click:0.38,0.945 +wait:.*logged in with entity id.* +sleep:8000 + +# --- The module menu: Right Shift, then Toggle Sprint's switch and its settings --- +key:ShiftRight +sleep:1500 +shot:build/browser-checks/modules-menu.png +click:0.545,0.215 +sleep:500 +shot:build/browser-checks/modules-menu-on.png +click:0.553,0.292 +sleep:1500 +shot:build/browser-checks/modules-settings.png +key:Escape +sleep:800 +key:Escape +sleep:1500 + +# --- A tap of Left Control latches sprinting; W alone then sprints and the HUD says so --- +key:ControlLeft +sleep:300 +down:KeyW +sleep:1500 +shot:build/browser-checks/modules-hud.png +up:KeyW +sleep:500 + +# --- The profile is stored with Toggle Sprint on --- +sleep:2000 +until:window.incariStorage.pending() === 0 +assert:(async () => { let d = await navigator.storage.getDirectory(); for (const p of ["incari", "game", "incari", "modules", "profiles"]) d = await d.getDirectoryHandle(p); const text = await (await (await d.getFileHandle("Default.json")).getFile()).text(); console.log("[check] profile: " + text.replace(/\s+/g, " ")); return JSON.parse(text).modules.togglesprint.enabled === true; })() diff --git a/incari-client/files/app-web/browser-checks/newmodules.steps b/incari-client/files/app-web/browser-checks/newmodules.steps new file mode 100644 index 0000000..3f4d268 --- /dev/null +++ b/incari-client/files/app-web/browser-checks/newmodules.steps @@ -0,0 +1,229 @@ +# ADRs 0052-0054: the fifteen new modules in the page. Creates a world, turns each on from the +# module menu (its search narrows the grid to the one card, whose switch is the first card's), then +# shows the HUD, the crosshair and cooldown after a swing, Freelook with Left Alt held, F2 and the +# pause menu's Screenshots button, and the gallery. No server needed. Positions are for the +# 1280x577 viewport (GUI scale 2, 640x288). +# +# ./gradlew :app-web:browserCheck -Pbrowser.gpu=gl -Pbrowser.seconds=300 -Pbrowser.steps=@browser-checks/newmodules.steps + +sleep:4000 +# The first-run accessibility screen: Continue. Then Singleplayer, Create New World with the defaults. +click:0.5,0.945 +sleep:3000 +click:0.2,0.43 +sleep:4000 +click:0.38,0.945 +wait:.*logged in with entity id.* +sleep:8000 + +# --- Keystrokes --- +key:ShiftRight +sleep:1200 +click:0.40,0.125 +sleep:600 +type:Keystrokes +sleep:400 +shot:build/browser-checks/newmodules-search.png +click:0.545,0.215 +sleep:300 +key:Escape +sleep:800 + +# --- CPS --- +key:ShiftRight +sleep:1200 +click:0.40,0.125 +sleep:600 +type:CPS +sleep:400 +click:0.545,0.215 +sleep:300 +key:Escape +sleep:800 + +# --- FPS Display --- +key:ShiftRight +sleep:1200 +click:0.40,0.125 +sleep:600 +type:FPS Display +sleep:400 +click:0.545,0.215 +sleep:300 +key:Escape +sleep:800 + +# --- Reach Display --- +key:ShiftRight +sleep:1200 +click:0.40,0.125 +sleep:600 +type:Reach Display +sleep:400 +click:0.545,0.215 +sleep:300 +key:Escape +sleep:800 + +# --- Coordinates --- +key:ShiftRight +sleep:1200 +click:0.40,0.125 +sleep:600 +type:Coordinates +sleep:400 +click:0.545,0.215 +sleep:300 +key:Escape +sleep:800 + +# --- Shield & Totem --- +key:ShiftRight +sleep:1200 +click:0.40,0.125 +sleep:600 +type:Shield & Totem +sleep:400 +click:0.545,0.215 +sleep:300 +key:Escape +sleep:800 + +# --- Cooldown Indicator --- +key:ShiftRight +sleep:1200 +click:0.40,0.125 +sleep:600 +type:Cooldown Indicator +sleep:400 +click:0.545,0.215 +sleep:300 +key:Escape +sleep:800 + +# --- 1.7 Animations --- +key:ShiftRight +sleep:1200 +click:0.40,0.125 +sleep:600 +type:1.7 Animations +sleep:400 +click:0.545,0.215 +sleep:300 +key:Escape +sleep:800 + +# --- Freelook --- +key:ShiftRight +sleep:1200 +click:0.40,0.125 +sleep:600 +type:Freelook +sleep:400 +click:0.545,0.215 +sleep:300 +key:Escape +sleep:800 + +# --- Crosshair Editor --- +key:ShiftRight +sleep:1200 +click:0.40,0.125 +sleep:600 +type:Crosshair Editor +sleep:400 +click:0.545,0.215 +sleep:300 +key:Escape +sleep:800 + +# --- Low Shield --- +key:ShiftRight +sleep:1200 +click:0.40,0.125 +sleep:600 +type:Low Shield +sleep:400 +click:0.545,0.215 +sleep:300 +key:Escape +sleep:800 + +# --- Weather Changer --- +key:ShiftRight +sleep:1200 +click:0.40,0.125 +sleep:600 +type:Weather Changer +sleep:400 +click:0.545,0.215 +sleep:300 +key:Escape +sleep:800 + +# --- Theme Editor --- +key:ShiftRight +sleep:1200 +click:0.40,0.125 +sleep:600 +type:Theme Editor +sleep:400 +click:0.545,0.215 +sleep:300 +key:Escape +sleep:800 + +# --- Screenshot Manager --- +key:ShiftRight +sleep:1200 +click:0.40,0.125 +sleep:600 +type:Screenshot Manager +sleep:400 +click:0.545,0.215 +sleep:300 +key:Escape +sleep:800 + +# --- Shulker Tooltips --- +key:ShiftRight +sleep:1200 +click:0.40,0.125 +sleep:600 +type:Shulker Tooltips +sleep:400 +click:0.545,0.215 +sleep:300 +key:Escape +sleep:800 + +key:ShiftRight +sleep:1500 +shot:build/browser-checks/newmodules-menu.png +key:Escape +sleep:2000 + +# --- The HUD, the crosshair, a swing's cooldown --- +down:KeyW +sleep:300 +click:0.5,0.5 +sleep:150 +shot:build/browser-checks/newmodules-hud.png +up:KeyW +sleep:1500 + +# --- Freelook: Left Alt held --- +down:AltLeft +sleep:600 +shot:build/browser-checks/newmodules-freelook.png +up:AltLeft +sleep:800 + +# --- F2, then the pause menu with its Screenshots button --- +key:F2 +sleep:2500 +key:Escape +sleep:1500 +shot:build/browser-checks/newmodules-pause.png +until:window.incariStorage.pending() === 0 +assert:(async () => { let d = await navigator.storage.getDirectory(); for (const p of ["incari", "game", "screenshots"]) d = await d.getDirectoryHandle(p); let count = 0; for await (const [name] of d.entries()) { if (name.endsWith(".png")) count++; } console.log("[check] screenshots: " + count); return count > 0; })() diff --git a/incari-client/files/app-web/browser-checks/old-textures.steps b/incari-client/files/app-web/browser-checks/old-textures.steps new file mode 100644 index 0000000..2c1f409 --- /dev/null +++ b/incari-client/files/app-web/browser-checks/old-textures.steps @@ -0,0 +1,63 @@ +# ADR 0055: the built-in packs and Old Textures in the page. Programmer Art and High Contrast are +# fetched at start and listed in the Resource Packs screen. Selecting Programmer Art there reloads +# the resources with its zip and turns Old Textures on; turning the module off and on in the module +# menu takes the pack out and puts it back. Then a new world in the old textures. No server +# needed. Positions are for the 1280x577 viewport (GUI scale 2, 640x288). +# +# ./gradlew :app-web:browserCheck -Pbrowser.gpu=gl -Pbrowser.seconds=300 -Pbrowser.steps=@browser-checks/old-textures.steps + +# The packs' fetch is logged before the steps start ("Assets: fetched 2 files (705 KB)"); the +# reload with programmer_art below shows its zip was there. +sleep:4000 +# The first-run accessibility screen: Continue. +click:0.5,0.945 +sleep:3000 +# Options (the left half of the column's last row), Resource Packs. +click:0.133,0.691 +sleep:1500 +click:0.376,0.598 +sleep:2500 +shot:build/browser-checks/old-textures-packs.png +# Programmer Art's icon (the second available pack) moves it to Selected; Done reloads with it. +move:0.195,0.41 +sleep:300 +click:0.195,0.41 +sleep:1000 +shot:build/browser-checks/old-textures-selected.png +click:0.623,0.945 +wait:.*Reloading ResourceManager.*programmer_art.* +sleep:8000 +assert:window.incariStorage.read('/incari/game/options.txt').then(t => t !== null && t.includes('"programmer_art"')) +waitfor:window.incariStorage.read('/incari/game/incari/modules/profiles/Default.json').then(t => t !== null && JSON.parse(t).modules.oldtextures.enabled === true) +# Back to the title screen. +key:Escape +sleep:2000 +shot:build/browser-checks/old-textures-title.png + +# The module menu: Old Textures off takes the pack out. +click:0.2,0.604 +sleep:1500 +click:0.40,0.125 +sleep:600 +type:Old Textures +sleep:400 +shot:build/browser-checks/old-textures-module.png +click:0.545,0.215 +wait:.*Reloading ResourceManager.* +sleep:8000 +assert:window.incariStorage.read('/incari/game/options.txt').then(t => t !== null && !t.includes('"programmer_art"')) +# And on again puts it back. +click:0.545,0.215 +wait:.*Reloading ResourceManager.*programmer_art.* +sleep:8000 +assert:window.incariStorage.read('/incari/game/options.txt').then(t => t !== null && t.includes('"programmer_art"')) +key:Escape +sleep:1500 + +# Singleplayer, Create New World with the defaults, in the old textures. +click:0.2,0.43 +sleep:4000 +click:0.38,0.945 +wait:.*logged in with entity id.* +sleep:10000 +shot:build/browser-checks/old-textures-world.png diff --git a/incari-client/files/app-web/browser-checks/relay-host.html b/incari-client/files/app-web/browser-checks/relay-host.html new file mode 100644 index 0000000..e140020 --- /dev/null +++ b/incari-client/files/app-web/browser-checks/relay-host.html @@ -0,0 +1,133 @@ + + + +Incari relay host (test) + diff --git a/incari-client/files/app-web/browser-checks/relay-join.steps b/incari-client/files/app-web/browser-checks/relay-join.steps new file mode 100644 index 0000000..fd42d8e --- /dev/null +++ b/incari-client/files/app-web/browser-checks/relay-join.steps @@ -0,0 +1,29 @@ +# Joining a world shared through an Eagler relay. Needs the relay (EaglerSPRelay, local) and +# relay-host.html open in another headless Chromium, which prints the world's code; the command +# that runs this script puts the code in place of CODE (README.md, "Shared worlds"). + +# The first-run accessibility screen: Continue. +sleep:4000 +click:0.5,0.945 +sleep:2000 +# Title screen: Multiplayer; the first visit's warning: Proceed. +click:0.5,0.5 +sleep:1500 +click:0.375,0.688 +sleep:1500 +shot:build/browser-checks/relay-multiplayer.png +# The multiplayer screen's "Shared..." button, bottom row, fourth. +click:0.621,0.938 +sleep:1500 +shot:build/browser-checks/relay-screen.png +# The relay field: select what's there, type the local relay. +click:0.5,0.277 +key:Control+KeyA +type:ws://127.0.0.1:6699/ +click:0.5,0.416 +type:CODE +shot:build/browser-checks/relay-filled.png +# Join. +click:0.42,0.553 +wait:.*\[CHAT\] incari-relay-check.* +shot:build/browser-checks/relay-joined.png diff --git a/incari-client/files/app-web/browser-checks/screenshot.steps b/incari-client/files/app-web/browser-checks/screenshot.steps new file mode 100644 index 0000000..bab12f0 --- /dev/null +++ b/incari-client/files/app-web/browser-checks/screenshot.steps @@ -0,0 +1,26 @@ +# A screenshot taken in a world (F2) downloads as a PNG when the player clicks its name in +# the chat message, as it opens in the file manager on a desktop. Needs a world: a vanilla server +# behind tools/wsbridge, as server-join.steps (the browser-checks README has the setup), joined +# straight away with ?server=. Positions are for the 1280x577 viewport. +# +# INCARI_RCON_PASSWORD= ./gradlew :app-web:browserCheck \ +# "-Pbrowser.query=server=ws://127.0.0.1:8817&name=IncariWeb" -Pbrowser.rcon=127.0.0.1:25592 \ +# -Pbrowser.seconds=300 -Pbrowser.steps=@browser-checks/screenshot.steps + +downloads:build/browser-checks/downloads +rcon:whitelist off +rcon:time set day +# The first-run accessibility screen: Continue. Quick play connects after it. +sleep:4000 +click:0.5,0.945 +rconwait:list => IncariWeb +sleep:6000 +key:F2 +wait:.*\[CHAT\] Saved screenshot as .*\.png.* +sleep:1000 +# Open chat, and click the file name in the message ("Saved screenshot as "). +key:KeyT +sleep:1000 +shot:build/browser-checks/screenshot-chat.png +click:0.28,0.848 +download:.*\.png diff --git a/incari-client/files/app-web/browser-checks/server-join.steps b/incari-client/files/app-web/browser-checks/server-join.steps new file mode 100644 index 0000000..46c1532 --- /dev/null +++ b/incari-client/files/app-web/browser-checks/server-join.steps @@ -0,0 +1,71 @@ +# The browser build joins a vanilla 26.3 server over ws://, through the dev bridge +# (tools/wsbridge on 127.0.0.1:8817), plays, changes dimension there and back, is transferred to +# the same server (disconnecting and reconnecting by itself), is kicked, and joins again through +# the multiplayer screen. Each check reads the page's console, the clipboard (F3+C copies the +# client's own position and dimension), or the server's answer over RCON. The page runs with +# ?server=ws://127.0.0.1:8817&name=IncariWeb; README.md ("Server join") has the setup and command. + +# A fresh 26.3 server has its whitelist on; and on a server that has run a while, night falls and +# mobs can kill the player mid-check. +rcon:whitelist off +rcon:difficulty peaceful +rcon:time set day + +# The first-run accessibility screen: Continue. Quick play connects after it. +sleep:4000 +click:0.5,0.945 +wait:.*Connecting to 127\.0\.0\.1, 8817.* + +# --- Joined: the server lists the player, and a system message reaches the client's chat --- +rconwait:list => IncariWeb +# The teleports below land in rock, lava or the air: in creative nothing there can kill the player, +# which would otherwise be saved dead and fail the next run's teleports. +rcon:gamemode creative IncariWeb +sleep:3000 +rcon:tellraw IncariWeb "incari-check-chat" +wait:.*\[CHAT\] incari-check-chat.* +shot:build/browser-checks/server-joined.png + +# --- To the Nether and back, as the client itself sees it --- +clipboard:- +rcon:execute in minecraft:the_nether run tp IncariWeb 0 100 0 +rconwait:data get entity IncariWeb Dimension => the_nether +sleep:4000 +key:F3+KeyC +waitfor:navigator.clipboard.readText().then(text => text.startsWith('/execute in minecraft:the_nether ')) +shot:build/browser-checks/server-nether.png +rcon:execute in minecraft:overworld run tp IncariWeb 0 -60 0 +rconwait:data get entity IncariWeb Dimension => overworld +sleep:4000 +key:F3+KeyC +waitfor:navigator.clipboard.readText().then(text => text.startsWith('/execute in minecraft:overworld ')) + +# --- Transfer: the server names a ws:// address; the client disconnects and reconnects itself --- +rcon:transfer "ws://127.0.0.1:8817" 25565 IncariWeb +wait:.*Client disconnected with reason: Transferred to another server.* +wait:.*Connecting to 127\.0\.0\.1, 8817.* +rconwait:list => IncariWeb +sleep:3000 +rcon:tellraw IncariWeb "incari-check-transferred" +wait:.*\[CHAT\] incari-check-transferred.* + +# --- Disconnect and reconnect: kicked, back to the server list, Direct Connection --- +rcon:kick IncariWeb incari-check-kick +wait:.*Client disconnected with reason: incari-check-kick.* +rconwait:list => There are 0 +sleep:1000 +shot:build/browser-checks/server-kicked.png +# "Back to Server List", then "Direct Connection" (the list itself is empty: the check's browser +# starts with a new profile, so there's no stored servers.dat). +click:0.5,0.598 +sleep:2000 +click:0.5,0.854 +sleep:1500 +type:ws://127.0.0.1:8817 +key:Enter +wait:.*Connecting to 127\.0\.0\.1, 8817.* +rconwait:list => IncariWeb +sleep:3000 +rcon:tellraw IncariWeb "incari-check-rejoined" +wait:.*\[CHAT\] incari-check-rejoined.* +shot:build/browser-checks/server-rejoined.png diff --git a/incari-client/files/app-web/browser-checks/share-guest.steps b/incari-client/files/app-web/browser-checks/share-guest.steps new file mode 100644 index 0000000..7452352 --- /dev/null +++ b/incari-client/files/app-web/browser-checks/share-guest.steps @@ -0,0 +1,14 @@ +# ADR 0062: a guest joining an Incari player's shared world (?shared=|, the code from +# share-host.steps' console): joined as it is, no Via; the world arrives and the guest plays in it. +sleep:4000 +click:0.5,0.945 +wait:.*Loaded \d+ advancements.* +sleep:20000 +shot:build/browser-checks/share-guest-joined.png +key:KeyT +sleep:800 +type:hello from the guest +key:Enter +wait:.*\[CHAT\] hello from the guest.* +sleep:2000 +shot:build/browser-checks/share-guest-chat.png diff --git a/incari-client/files/app-web/browser-checks/share-host.steps b/incari-client/files/app-web/browser-checks/share-host.steps new file mode 100644 index 0000000..587cbb6 --- /dev/null +++ b/incari-client/files/app-web/browser-checks/share-host.steps @@ -0,0 +1,10 @@ +# ADR 0062: the host of a shared world. Run beside share-guest.steps and the local relay +# (README.md, "Shared worlds, hosted"): the quick world is shared on the relay as soon as it's open +# (?share=), the code goes to the console, and a guest joins. +sleep:4000 +click:0.5,0.945 +wait:.*The world is shared on .* with the code .* +shot:build/browser-checks/share-host-shared.png +wait:.*\[CHAT\] Guest joined the game.* +sleep:90000 +shot:build/browser-checks/share-host-guest.png diff --git a/incari-client/files/app-web/browser-checks/singleplayer-lan.steps b/incari-client/files/app-web/browser-checks/singleplayer-lan.steps new file mode 100644 index 0000000..02fc7df --- /dev/null +++ b/incari-client/files/app-web/browser-checks/singleplayer-lan.steps @@ -0,0 +1,24 @@ +# ADR 0038: Open to LAN with singleplayer's server on the page. A page can't listen for +# connections, so the game says it couldn't host instead of failing. (With the server in a worker, +# the pause menu has no World Options yet: ADR 0039.) Positions are for the 1280x577 viewport. +# +# ./gradlew :app-web:browserCheck -Pbrowser.gpu=gl -Pbrowser.seconds=300 "-Pbrowser.query=name=Player&singleplayer=page" \ +# -Pbrowser.steps=@browser-checks/singleplayer-lan.steps + +sleep:4000 +click:0.5,0.945 +sleep:3000 +click:0.5,0.449 +sleep:4000 +click:0.38,0.945 +wait:.*logged in with entity id.* +sleep:8000 +# World Options, LAN on, Apply: back to the pause menu, and the game says it couldn't host. +key:Escape +sleep:1500 +click:0.583,0.561 +sleep:2000 +click:0.375,0.723 +sleep:500 +click:0.375,0.945 +wait:.*\[CHAT\] Unable to host local game.* diff --git a/incari-client/files/app-web/browser-checks/singleplayer.steps b/incari-client/files/app-web/browser-checks/singleplayer.steps new file mode 100644 index 0000000..99feaed --- /dev/null +++ b/incari-client/files/app-web/browser-checks/singleplayer.steps @@ -0,0 +1,90 @@ +# ADR 0038, ADR 0039: singleplayer, its server in a worker (or on the page with +# -Pbrowser.query=name=Player&singleplayer=page). Creates a world with the defaults, plays in it, +# turns Allow Commands on in World Options and runs a command, saves and quits; checks that every saved chunk inflates with the browser's own DecompressionStream; plays the world again; +# downloads it through Edit World's folder button, drops the download on the world list (a second +# copy is imported), and opens Delete. No server needed. Positions are for the 1280x577 viewport. +# +# ./gradlew :app-web:browserCheck -Pbrowser.gpu=gl -Pbrowser.seconds=400 -Pbrowser.steps=@browser-checks/singleplayer.steps + +downloads:build/browser-checks/downloads +sleep:4000 +# The first-run accessibility screen: Continue. Then Singleplayer; with no worlds yet it opens +# Create New World, and Create takes the defaults. +click:0.5,0.945 +sleep:3000 +click:0.5,0.449 +sleep:4000 +shot:build/browser-checks/singleplayer-create.png +click:0.38,0.945 +wait:.*logged in with entity id.* +sleep:8000 +shot:build/browser-checks/singleplayer-world.png + +# --- World Options: Allow Commands on, Apply; then a command works --- +key:Escape +sleep:1500 +click:0.583,0.561 +sleep:2000 +shot:build/browser-checks/singleplayer-world-options.png +click:0.376,0.414 +sleep:500 +click:0.375,0.945 +sleep:2000 +key:Escape +sleep:1000 +key:KeyT +sleep:800 +type:/time set day +key:Enter +wait:.*\[CHAT\] Set minecraft:overworld to time marker minecraft:day.* +sleep:1000 +key:Escape +sleep:1500 + +# --- Save and Quit to Title, then every saved chunk reads back whole --- +click:0.5,0.643 +wait:.*Saving chunks for level 'ServerLevel\[New World\]'/minecraft:the_nether.* +sleep:4000 +until:window.incariStorage.pending() === 0 +assert:(async () => { const root = await navigator.storage.getDirectory(); let d = root; for (const p of ["incari", "game", "saves", "New World", "dimensions", "minecraft", "overworld"]) d = await d.getDirectoryHandle(p); let ok = 0, bad = 0; for (const sub of ["region", "entities"]) { const s = await d.getDirectoryHandle(sub); for await (const [, h] of s.entries()) { const buf = await (await h.getFile()).arrayBuffer(); const v = new DataView(buf); for (let i = 0; i < 1024; i++) { const off = v.getUint32(i * 4); if (!off) continue; const pos = (off >>> 8) * 4096; const len = v.getUint32(pos); try { await new Response(new Blob([new Uint8Array(buf, pos + 5, len - 1)]).stream().pipeThrough(new DecompressionStream("deflate"))).arrayBuffer(); ok++; } catch (e) { bad++; } } } } console.log("[check] saved chunks: " + ok + " whole, " + bad + " broken"); return ok > 0 && bad === 0; })() + +# --- Play it again from the world list --- +click:0.5,0.449 +sleep:3000 +shot:build/browser-checks/singleplayer-list.png +click:0.5,0.235 +sleep:500 +click:0.375,0.854 +wait:.*logged in with entity id.* +sleep:5000 +key:Escape +sleep:1500 +click:0.5,0.643 +wait:.*Saving chunks for level 'ServerLevel\[New World\]'/minecraft:the_nether.* +sleep:4000 + +# --- Edit World, Open World Folder: the page downloads the world as a zip --- +click:0.5,0.449 +sleep:3000 +click:0.5,0.235 +sleep:500 +click:0.313,0.937 +sleep:2000 +click:0.5,0.436 +download:New World\.zip +sleep:1000 +key:Escape +sleep:2000 + +# --- The zip dropped on the world list comes in as a second world --- +drop:0.5,0.5,build/browser-checks/downloads/New World.zip +waitfor:window.incariStorage.list('/incari/game/saves/New World (1)').then(l => l.includes('/incari/game/saves/New World (1)/level.dat')) +sleep:1000 +shot:build/browser-checks/singleplayer-imported.png + +# --- Delete asks first --- +click:0.5,0.235 +sleep:500 +click:0.437,0.937 +sleep:2000 +shot:build/browser-checks/singleplayer-delete.png diff --git a/incari-client/files/app-web/browser-checks/soak.steps b/incari-client/files/app-web/browser-checks/soak.steps new file mode 100644 index 0000000..0297aac --- /dev/null +++ b/incari-client/files/app-web/browser-checks/soak.steps @@ -0,0 +1,900 @@ +# A 30-minute session on a vanilla server that keeps the client loading terrain, and the +# threading audit's gate: no frame in which the render thread spent 50 ms or more waiting (blocking +# calls on it; the page's frame monitor, platform-web's Dom.installFrameMonitor, adds up each frame's +# waits). Frames over 50 ms from work (meshing, packets), with or without a short wait in them, are +# reported, not failed: that's the benchmark's job. +# Every minute the player is sent to fresh terrain and turns full circle, and the mouse moves with +# each turn so the game never counts the player as idle (it throttles to 30 and then 10 fps); the +# page's counts are printed as it goes. Setup as for server-join.steps (README.md, "Server join"); run with +# +# INCARI_RCON_PASSWORD= ./gradlew :app-web:browserCheck -Pbrowser.gpu=gl \ +# "-Pbrowser.query=server=ws://127.0.0.1:8817&name=IncariWeb" -Pbrowser.rcon=127.0.0.1:25592 \ +# -Pbrowser.seconds=2100 -Pbrowser.steps=@browser-checks/soak.steps + +rcon:whitelist off +rcon:difficulty peaceful +rcon:time set day +rcon:gamerule doDaylightCycle false +rcon:gamerule doWeatherCycle false + +# The first-run accessibility screen: Continue. Quick play connects after it. +sleep:4000 +click:0.5,0.945 +wait:.*Connecting to 127\.0\.0\.1, 8817.* +rconwait:list => IncariWeb +sleep:5000 +# Counted from here: the join itself is loading, not play. +eval:(function() { var f = window.__incariFrames; f.frames = 0; f.waiting = 0; f.waitStalls = 0; f.worstWait = 0; f.slow = 0; f.slowWaiting = 0; f.worst = 0; f.worstWaiting = 0; return 'counting'; })() +# Minute 1 +rcon:spreadplayers 2000 2000 0 1 false IncariWeb +sleep:20000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +sleep:8000 +eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting']) +# Minute 2 +rcon:spreadplayers 2700 2000 0 1 false IncariWeb +sleep:20000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +sleep:8000 +eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting']) +# Minute 3 +rcon:spreadplayers 3400 2000 0 1 false IncariWeb +sleep:20000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +sleep:8000 +eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting']) +# Minute 4 +rcon:spreadplayers 4100 2000 0 1 false IncariWeb +sleep:20000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +sleep:8000 +eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting']) +# Minute 5 +rcon:spreadplayers 4800 2000 0 1 false IncariWeb +sleep:20000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +sleep:8000 +eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting']) +# Minute 6 +rcon:spreadplayers 5500 2000 0 1 false IncariWeb +sleep:20000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +sleep:8000 +eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting']) +# Minute 7 +rcon:spreadplayers 2000 2700 0 1 false IncariWeb +sleep:20000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +sleep:8000 +eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting']) +# Minute 8 +rcon:spreadplayers 2700 2700 0 1 false IncariWeb +sleep:20000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +sleep:8000 +eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting']) +# Minute 9 +rcon:spreadplayers 3400 2700 0 1 false IncariWeb +sleep:20000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +sleep:8000 +eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting']) +# Minute 10 +rcon:spreadplayers 4100 2700 0 1 false IncariWeb +sleep:20000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +sleep:8000 +eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting']) +# Minute 11 +rcon:spreadplayers 4800 2700 0 1 false IncariWeb +sleep:20000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +sleep:8000 +eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting']) +# Minute 12 +rcon:spreadplayers 5500 2700 0 1 false IncariWeb +sleep:20000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +sleep:8000 +eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting']) +# Minute 13 +rcon:spreadplayers 2000 3400 0 1 false IncariWeb +sleep:20000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +sleep:8000 +eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting']) +# Minute 14 +rcon:spreadplayers 2700 3400 0 1 false IncariWeb +sleep:20000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +sleep:8000 +eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting']) +# Minute 15 +rcon:spreadplayers 3400 3400 0 1 false IncariWeb +sleep:20000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +sleep:8000 +eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting']) +# Minute 16 +rcon:spreadplayers 4100 3400 0 1 false IncariWeb +sleep:20000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +sleep:8000 +eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting']) +# Minute 17 +rcon:spreadplayers 4800 3400 0 1 false IncariWeb +sleep:20000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +sleep:8000 +eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting']) +# Minute 18 +rcon:spreadplayers 5500 3400 0 1 false IncariWeb +sleep:20000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +sleep:8000 +eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting']) +# Minute 19 +rcon:spreadplayers 2000 4100 0 1 false IncariWeb +sleep:20000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +sleep:8000 +eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting']) +# Minute 20 +rcon:spreadplayers 2700 4100 0 1 false IncariWeb +sleep:20000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +sleep:8000 +eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting']) +# Minute 21 +rcon:spreadplayers 3400 4100 0 1 false IncariWeb +sleep:20000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +sleep:8000 +eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting']) +# Minute 22 +rcon:spreadplayers 4100 4100 0 1 false IncariWeb +sleep:20000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +sleep:8000 +eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting']) +# Minute 23 +rcon:spreadplayers 4800 4100 0 1 false IncariWeb +sleep:20000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +sleep:8000 +eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting']) +# Minute 24 +rcon:spreadplayers 5500 4100 0 1 false IncariWeb +sleep:20000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +sleep:8000 +eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting']) +# Minute 25 +rcon:spreadplayers 2000 4800 0 1 false IncariWeb +sleep:20000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +sleep:8000 +eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting']) +# Minute 26 +rcon:spreadplayers 2700 4800 0 1 false IncariWeb +sleep:20000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +sleep:8000 +eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting']) +# Minute 27 +rcon:spreadplayers 3400 4800 0 1 false IncariWeb +sleep:20000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +sleep:8000 +eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting']) +# Minute 28 +rcon:spreadplayers 4100 4800 0 1 false IncariWeb +sleep:20000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +sleep:8000 +eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting']) +# Minute 29 +rcon:spreadplayers 4800 4800 0 1 false IncariWeb +sleep:20000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +sleep:8000 +eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting']) +# Minute 30 +rcon:spreadplayers 5500 4800 0 1 false IncariWeb +sleep:20000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.4,0.5 +sleep:4000 +rcon:execute as IncariWeb at @s run tp @s ~ ~ ~ ~45 ~ +move:0.6,0.5 +sleep:4000 +sleep:8000 +eval:JSON.stringify(window.__incariFrames, ['frames', 'waiting', 'waitStalls', 'worstWait', 'slow', 'slowWaiting', 'worst', 'worstWaiting']) +shot:build/browser-checks/soak.png +# The gate: no frame in which the render thread waited 50 ms or more. +assert:window.__incariFrames.waitStalls === 0 diff --git a/incari-client/files/app-web/browser-checks/sound-retry.steps b/incari-client/files/app-web/browser-checks/sound-retry.steps new file mode 100644 index 0000000..4dc773d --- /dev/null +++ b/incari-client/files/app-web/browser-checks/sound-retry.steps @@ -0,0 +1,42 @@ +# F1 of the 2026-10-12 batch: sounds whose download fails at first still play. Every sound's first +# two fetches fail as a dropped connection would; the loader's retries get the third. In a quick +# world (-Pbrowser.query=name=Player&world=Retry&seed=1); no server needed. +# +# ./gradlew :app-web:browserCheck -Pbrowser.gpu=gl -Pbrowser.seconds=240 \ +# "-Pbrowser.query=name=Player&world=Retry&seed=1" -Pbrowser.steps=@browser-checks/sound-retry.steps + +sleep:4000 +eval:(() => { const of = window.fetch; const tries = new Map(); globalThis.fetchLog = []; window.fetch = (u, ...a) => { const url = String(u); if (!url.includes('objects')) return of(u, ...a); const n = (tries.get(url) || 0) + 1; tries.set(url, n); if (n <= 2) { fetchLog.push('fail ' + n); return Promise.reject(new TypeError('Failed to fetch')); } return of(u, ...a).then(r => { fetchLog.push(r.status + ' on try ' + n); return r; }); }; return 'failing each sound twice'; })() +# The first-run accessibility screen: Continue (also the gesture the audio waits for). +click:0.5,0.945 +wait:.*logged in with entity id.* +sleep:6000 +eval:globalThis.before = incariAudio.buffersStarted + +key:KeyT +sleep:800 +type:/fill ~-4 ~ ~-4 ~4 ~4 ~4 minecraft:air +key:Enter +sleep:800 +key:KeyT +sleep:800 +type:/fill ~-4 ~-3 ~-4 ~4 ~-1 ~4 minecraft:stone +key:Enter +sleep:800 +key:KeyT +sleep:800 +type:/gamemode creative +key:Enter +sleep:800 +key:KeyT +sleep:800 +type:/tp @s ~ ~ ~ 0 90 +key:Enter +sleep:1500 +click:0.5,0.5 +sleep:1500 +click:0.5,0.5 +sleep:1500 +click:0.5,0.5 +sleep:3000 +eval:'buffers started: ' + (incariAudio.buffersStarted - before) + ', fetches: ' + JSON.stringify(fetchLog) diff --git a/incari-client/files/app-web/browser-checks/storage.steps b/incari-client/files/app-web/browser-checks/storage.steps new file mode 100644 index 0000000..6685cec --- /dev/null +++ b/incari-client/files/app-web/browser-checks/storage.steps @@ -0,0 +1,106 @@ +# Settings, servers and resource packs survive a reload. Changes an option (FOV), adds a +# server and imports a resource pack (made by the check from scratch) through "Open Pack Folder"'s +# file picker, reloads the page, and checks that the page loaded all three from storage and the +# game uses them. Also: F2's screenshot is stored as a PNG. Positions are for the 1280x577 +# viewport headless Chromium gives a 1280x720 window. +# +# ./gradlew :app-web:browserCheck -Pbrowser.seconds=400 -Pbrowser.steps=@browser-checks/storage.steps + +# A new profile: nothing stored yet, and the jar comes from the network. +sleep:4000 +assert:window.incariStorage.read('/incari/game/servers.dat').then(t => t === null) +# The first-run accessibility screen: Continue. +click:0.5,0.945 +sleep:3000 +shot:build/browser-checks/storage-title-before.png + +# --- An option: FOV, on the Options screen, dragged right of Normal --- +click:0.42,0.782 +sleep:1500 +click:0.48,0.133 +sleep:500 +shot:build/browser-checks/storage-fov.png +# Done saves options.txt. +click:0.5,0.945 +sleep:1500 +waitfor:window.incariStorage.read('/incari/game/options.txt').then(t => t !== null && /\nfov:0\.[0-9]*[1-9]/.test(t)) + +# --- A resource pack: Options, Resource Packs, Open Pack Folder, pick the pack, Yes to copy it --- +pack:build/browser-checks/incari-check-pack.zip +click:0.42,0.782 +sleep:1500 +click:0.376,0.598 +sleep:2000 +choose:0.376,0.945,build/browser-checks/incari-check-pack.zip +sleep:2000 +shot:build/browser-checks/storage-pack-confirm.png +click:0.38,0.585 +sleep:2000 +shot:build/browser-checks/storage-pack-available.png +waitfor:window.incariStorage.read('/incari/game/resourcepacks/incari-check-pack.zip').then(t => t !== null && t.startsWith('PK')) +# Select it: its icon's arrow, at the top of the Available list. +move:0.19,0.277 +sleep:300 +click:0.19,0.277 +sleep:1000 +shot:build/browser-checks/storage-pack-selected.png +# Done reloads resources with the pack, and saves it in options.txt. +click:0.623,0.945 +wait:.*Reloading ResourceManager.*incari-check-pack.* +sleep:4000 +waitfor:window.incariStorage.read('/incari/game/options.txt').then(t => t !== null && t.includes('file/incari-check-pack.zip')) +key:Escape +sleep:1500 + +# --- A server: Multiplayer, Proceed on the safety screen, Add Server --- +click:0.5,0.534 +sleep:1500 +click:0.376,0.688 +sleep:1500 +click:0.662,0.854 +sleep:1500 +click:0.5,0.262 +key:Control+KeyA +type:Incari Check Server +click:0.5,0.4 +type:ws://127.0.0.1:18199 +sleep:300 +click:0.5,0.678 +sleep:2000 +shot:build/browser-checks/storage-servers-before.png +waitfor:window.incariStorage.read('/incari/game/servers.dat').then(t => t !== null && t.includes('Incari Check Server') && t.includes('ws://127.0.0.1:18199')) +key:Escape +sleep:1500 + +# --- A screenshot (F2), stored as a PNG under screenshots/ --- +key:F2 +sleep:2000 +waitfor:window.incariStorage.list('/incari/game/screenshots').then(p => p.length === 1 && p[0].endsWith('.png')) +assert:window.incariStorage.list('/incari/game/screenshots').then(p => window.incariStorage.read(p[0])).then(t => t.startsWith('\ufffdPNG')) + +# --- Everything is stored before the reload --- +waitfor:window.incariStorage.pending() === 0 +reload +wait:\[Incari\] Storage: opfs, [1-9][0-9]* files.* +wait:\[Incari\] Client jar: .* from storage.* +# The game started with the pack (resource reloads name the packs in use). +wait:.*Reloading ResourceManager.*incari-check-pack.* +wait:\[Incari\] Main loop running.* +sleep:4000 +# No accessibility screen this time: options.txt said it was done. The title screen shows the +# pack's name for the Singleplayer button. +shot:build/browser-checks/storage-title-after.png +assert:window.incariStorage.read('/incari/game/options.txt').then(t => /\nfov:0\.[0-9]*[1-9]/.test(t) && t.includes('file/incari-check-pack.zip')) +# Options shows the FOV that was set. +click:0.42,0.782 +sleep:1500 +shot:build/browser-checks/storage-fov-after.png +key:Escape +sleep:1500 +# The server list has the server. +click:0.5,0.534 +sleep:1500 +click:0.376,0.688 +sleep:2500 +shot:build/browser-checks/storage-servers-after.png +assert:window.incariStorage.read('/incari/game/servers.dat').then(t => t !== null && t.includes('Incari Check Server')) diff --git a/incari-client/files/app-web/browser-checks/version-join.steps b/incari-client/files/app-web/browser-checks/version-join.steps new file mode 100644 index 0000000..c18c168 --- /dev/null +++ b/incari-client/files/app-web/browser-checks/version-join.steps @@ -0,0 +1,43 @@ +# The browser build joins a server of another version through Via, over ws://: a vanilla +# 1.8.9, 1.12.2 or 1.20.4 server behind the dev bridge (tools/wsbridge, which speaks Eagler), or a +# real EaglerXServer in front of one. It pings nothing first: quick play's version check asks the +# server's MOTD. Checks read the page's console and the server's answers over RCON (the backend's). +# The page needs &via=auto: Via is off unless the join asks for it (ADR 0071). README.md ("Old +# servers") has the setup and commands. + +# On a server that has run a while, night falls and mobs can kill the player mid-check. (1.8 and +# 1.12 take a number; later versions a name. The other form fails harmlessly.) +rcon:difficulty 0 +rcon:difficulty peaceful +rcon:time set 1000 + +# The first-run accessibility screen: Continue. Quick play connects after it, through Via. +sleep:4000 +click:0.5,0.945 +wait:.*Joining ws://[^ ]+ as .* through Via.* + +# --- Joined: the server lists the player, and a system message reaches the client's chat --- +rconwait:list => IncariWeb +sleep:3000 +rcon:tellraw IncariWeb "incari-check-chat" +wait:.*\[CHAT\] incari-check-chat.* +shot:build/browser-checks/version-joined.png + +# --- Idle for 20 s: a 1.8 server wants a movement packet every tick, which Via sends --- +sleep:20000 +rconwait:list => IncariWeb +rcon:tellraw IncariWeb "incari-check-still-here" +wait:.*\[CHAT\] incari-check-still-here.* + +# --- Kicked, then back through a reload of the page (quick play again) --- +rcon:kick IncariWeb incari-check-kick +wait:.*Client disconnected with reason: incari-check-kick.* +sleep:1000 +reload: +# The accessibility screen was answered and saved: quick play connects straight away. +wait:.*Joining ws://[^ ]+ as .* through Via.* +rconwait:list => IncariWeb +sleep:3000 +rcon:tellraw IncariWeb "incari-check-rejoined" +wait:.*\[CHAT\] incari-check-rejoined.* +shot:build/browser-checks/version-rejoined.png diff --git a/incari-client/files/app-web/browser-checks/voice-listener.steps b/incari-client/files/app-web/browser-checks/voice-listener.steps new file mode 100644 index 0000000..9fbbd5c --- /dev/null +++ b/incari-client/files/app-web/browser-checks/voice-listener.steps @@ -0,0 +1,33 @@ +# Eagler voice chat between two browsers, the listener (this file with voice-talker.steps). Run both at once against EaglerXServer with its +# voice service on, as VoiceA (-Pbrowser.query=...&name=VoiceA) and VoiceB; README.md ("Voice +# chat") has the commands. Chromium's fake microphone plays a steady tone and grants the +# permission, so each page turns global voice on, VoiceA holds push to talk, and VoiceB hears it. + +rcon:difficulty 0 +rcon:time set 1000 + +# The first-run accessibility screen: Continue. Quick play joins the server. +sleep:4000 +click:0.5,0.945 +wait:.*Joining ws://[^ ]+ as .* through Via.* +wait:.*The server has voice chat.* +sleep:3000 + +# Pause menu: "Voice Chat...", then the channel button until it reads Global. +key:Escape +sleep:1000 +shot:build/browser-checks/voice-pause-b.png +click:0.5,0.539 +sleep:1000 +shot:build/browser-checks/voice-screen-b.png +click:0.375,0.173 +sleep:500 +shot:build/browser-checks/voice-global-b.png +key:Escape +sleep:500 +key:Escape +sleep:500 + +# Connected by now or soon (the log line may come before a wait could see it); then VoiceA talks. +wait:.*Voice: VoiceA is talking.* +shot:build/browser-checks/voice-hearing-b.png diff --git a/incari-client/files/app-web/browser-checks/voice-talker.steps b/incari-client/files/app-web/browser-checks/voice-talker.steps new file mode 100644 index 0000000..f3041fa --- /dev/null +++ b/incari-client/files/app-web/browser-checks/voice-talker.steps @@ -0,0 +1,39 @@ +# Eagler voice chat between two browsers, the talker (this file with voice-listener.steps, or +# the other way round). Run both at once against EaglerXServer with its +# voice service on, as VoiceA (-Pbrowser.query=...&name=VoiceA) and VoiceB; README.md ("Voice +# chat") has the commands. Chromium's fake microphone plays a steady tone and grants the +# permission, so each page turns global voice on, VoiceA holds push to talk, and VoiceB hears it. + +rcon:difficulty 0 +rcon:time set 1000 + +# The first-run accessibility screen: Continue. Quick play joins the server. +sleep:4000 +click:0.5,0.945 +wait:.*Joining ws://[^ ]+ as .* through Via.* +wait:.*The server has voice chat.* +sleep:3000 + +# Pause menu: "Voice Chat...", then the channel button until it reads Global. +key:Escape +sleep:1000 +shot:build/browser-checks/voice-pause-a.png +click:0.5,0.539 +sleep:1000 +shot:build/browser-checks/voice-screen-a.png +click:0.375,0.173 +sleep:500 +shot:build/browser-checks/voice-global-a.png +key:Escape +sleep:500 +key:Escape +sleep:500 + +# The two connect within seconds of the listener turning voice on (the log line may come before a +# wait could see it): give it that, then hold push to talk (B) for twenty seconds. +sleep:10000 +down:KeyB +sleep:20000 +shot:build/browser-checks/voice-talking-a.png +up:KeyB +sleep:20000 diff --git a/incari-client/files/app-web/browser-checks/waypoints.steps b/incari-client/files/app-web/browser-checks/waypoints.steps new file mode 100644 index 0000000..76381b6 --- /dev/null +++ b/incari-client/files/app-web/browser-checks/waypoints.steps @@ -0,0 +1,66 @@ +# ADR 0051: the minimap and waypoints in the page. Creates a world, turns Minimap and Waypoints on +# from the module menu, marks where the player stands with N and names it +# Base, walks back from it so its label, distance and beam show ahead, opens the list with U and +# the world map with M, and checks the world's waypoints and the explored map are stored in OPFS. No server needed. Positions are for the +# 1280x577 viewport (GUI scale 2, 640x288). +# +# ./gradlew :app-web:browserCheck -Pbrowser.gpu=gl -Pbrowser.seconds=300 -Pbrowser.steps=@browser-checks/waypoints.steps + +sleep:4000 +# The first-run accessibility screen: Continue. Then Singleplayer, Create New World with the defaults. +click:0.5,0.945 +sleep:3000 +click:0.2,0.43 +sleep:4000 +click:0.38,0.945 +wait:.*logged in with entity id.* +sleep:8000 + +# --- The module menu: Minimap's and Waypoints' switches (the right column's second and fourth cards) --- +key:ShiftRight +sleep:1500 +click:0.833,0.395 +sleep:300 +click:0.833,0.756 +sleep:300 +shot:build/browser-checks/waypoints-menu.png +key:Escape +sleep:4000 +shot:build/browser-checks/waypoints-minimap.png + +# --- N: a new waypoint where the player stands, named Base and added with Enter --- +key:KeyN +sleep:1500 +shot:build/browser-checks/waypoints-new.png +type:Base +key:Enter +sleep:800 + +# --- Back from it: its label, distance and beam ahead --- +down:KeyS +sleep:2500 +up:KeyS +sleep:1500 +shot:build/browser-checks/waypoints-ahead.png + +# --- U: the list --- +key:KeyU +sleep:1500 +shot:build/browser-checks/waypoints-list.png +key:Escape +sleep:2500 + +# --- M: the world map, Base on it; M again closes it --- +key:KeyM +sleep:2000 +shot:build/browser-checks/waypoints-worldmap.png +key:KeyM +sleep:1000 + +# --- The world's waypoints are stored --- +until:window.incariStorage.pending() === 0 +assert:(async () => { let d = await navigator.storage.getDirectory(); for (const p of ["incari", "game", "incari", "modules", "waypoints"]) d = await d.getDirectoryHandle(p); let found = ""; for await (const [name, handle] of d.entries()) { const text = await (await handle.getFile()).text(); console.log("[check] " + name + ": " + text); found += text; } return found.includes("\"name\":\"Base\""); })() +# --- And the explored map, after the map's half-minute save --- +sleep:31000 +until:window.incariStorage.pending() === 0 +assert:(async () => { let d = await navigator.storage.getDirectory(); for (const p of ["incari", "game", "incari", "map"]) d = await d.getDirectoryHandle(p); let count = 0; const walk = async (dir) => { for await (const [name, handle] of dir.entries()) { if (handle.kind === "directory") await walk(handle); else if (name.endsWith(".map")) count++; } }; await walk(d); console.log("[check] map regions: " + count); return count > 0; })() diff --git a/incari-client/files/app-web/build.gradle.kts b/incari-client/files/app-web/build.gradle.kts new file mode 100644 index 0000000..df072e9 --- /dev/null +++ b/incari-client/files/app-web/build.gradle.kts @@ -0,0 +1,794 @@ +import java.util.Properties + +plugins { + java +} + +// The browser build: the game compiled by TeaVM (WebAssembly GC) through platform-web. +// `./gradlew :app-web:teavm` writes build/teavm/, which is never committed or published. + +dependencies { + implementation(project(":client")) + implementation(project(":platform-web")) + // The WebGL2 graphics backend. + implementation(project(":render-webgl2")) + // Compiled into the browser build in place of the JDK parts TeaVM lacks. ClientJar also + // names the directory its class-path resources live in. + implementation(project(":web-classlib")) + // java.time, which TeaVM maps onto ThreeTen Backport. + runtimeOnly(libs.threetenbp) + compileOnly(libs.teavm.jso) + compileOnly(libs.teavm.jso.apis) + compileOnly(libs.teavm.interop) + + // MemoryParityTest: the game's memory users over LWJGL and over web-classlib, on a JVM. + testImplementation(platform(libs.junit.bom)) + testImplementation(libs.junit.jupiter) + testImplementation(libs.assertj) + testImplementation(libs.asm) + testImplementation(libs.asm.commons) + testRuntimeOnly(libs.junit.launcher) +} + +// The parity test runs the vanilla side on real LWJGL, so it needs this machine's natives. +val testNativeJars = run { + val root = rootProject.layout.projectDirectory.asFile + val version = Properties().apply { + rootProject.layout.projectDirectory.file("incari.properties").asFile.reader().use { load(it) } + }.getProperty("minecraft.version") + providers.fileContents(rootProject.layout.projectDirectory.file("work/cache/versions/$version/natives.txt")) + .asText.map { text -> text.lines().filter { it.isNotBlank() }.map { root.resolve(it.trim()) } } + .orElse(emptyList()) +} + +tasks.test { + classpath += files(testNativeJars) + maxHeapSize = "2g" + // Game classes write logs/ into the working directory; keep that in build/. + val runDir = layout.buildDirectory.dir("test-run").get().asFile + workingDir = runDir + doFirst { runDir.mkdirs() } + jvmArgs( + "--enable-native-access=ALL-UNNAMED", + "-Dorg.lwjgl.system.SharedLibraryExtractPath=" + + rootProject.layout.projectDirectory.dir("work/natives/lwjgl").asFile.path, + ) + testLogging { showStandardStreams = true } +} + +val webbuildTool: Configuration = configurations.create("webbuildTool") +val shaderTool: Configuration = configurations.create("shaderTool") +val spriteTool: Configuration = configurations.create("spriteTool") + +dependencies { + webbuildTool(project(":tools:webbuild")) + shaderTool(project(":tools:shaders")) + spriteTool(project(":tools:sprites")) +} + +val repoRoot = rootProject.layout.projectDirectory + +// The client jar `./incari setup` downloaded. The dev server hands it to the page, which unpacks the +// game's resources from it (the build compiles classes only); it is never copied into the build. +val minecraftVersion = providers.fileContents(repoRoot.file("incari.properties")).asText.map { text -> + Properties().apply { load(text.reader()) }.getProperty("minecraft.version") +} +val clientJar = minecraftVersion.map { repoRoot.file("work/cache/versions/$it/client.jar").asFile.path } + +// The asset index `./incari assets` downloaded, and its objects (ADR 0013): the page lists the +// sounds from the index and fetches each one the first time it plays. Mojang's files, served from +// work/ by the dev server, never copied into the build. Without them the page runs silent. +val assetServerArgs: Provider> = minecraftVersion.map { version -> + val versionJson = repoRoot.file("work/cache/versions/$version/$version.json").asFile + if (!versionJson.isFile) { + emptyList() + } else { + @Suppress("UNCHECKED_CAST") + val index = (groovy.json.JsonSlurper().parse(versionJson) as Map)["assetIndex"] as Map + listOf( + "--file", "asset-index.json=" + repoRoot.file("work/cache/assets/indexes/${index["id"]}.json").asFile.path, + "--dir", "assets/objects=" + repoRoot.dir("work/cache/assets/objects").asFile.path, + ) + } +} + +// The game's shaders translated to GLSL ES 3.00 for the WebGL2 backend (tools/shaders). Translated +// Mojang files: build output beside the page, never inside build/teavm/ (so they don't invalidate the +// ten-minute compile) and never committed or published. The dev server serves them at /shaders.json. +val shaderManifest = layout.buildDirectory.file("web-shaders/shaders.json") + +tasks.register("shaders") { + group = "build" + description = "Translates the game's shaders for WebGL2 into build/web-shaders/shaders.json." + classpath = shaderTool + mainClass = "incari.tools.shaders.Main" + javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) } + val jar = clientJar.get() + val version = minecraftVersion.get() + // CI installs glslang and must check with it; locally it's used when it's installed. + val requireGlslang = providers.environmentVariable("CI").isPresent || + providers.gradleProperty("shaders.requireGlslang").isPresent + // A local: a lambda capturing the script can't be stored in the configuration cache. + val manifest = shaderManifest + inputs.file(jar) + inputs.files(shaderTool) + outputs.dir(manifest.map { it.asFile.parentFile }) + jvmArgs( + "--enable-native-access=ALL-UNNAMED", + "-Dorg.lwjgl.system.SharedLibraryExtractPath=${repoRoot.dir("work/natives/lwjgl").asFile}", + ) + argumentProviders.add(CommandLineArgumentProvider { + listOf("--client-jar", jar, "--minecraft", version, "--out", manifest.get().asFile.path) + + (if (requireGlslang) listOf("--require-glslang") else emptyList()) + }) +} + +// The vanilla sprites decoded, with their mip levels, by the game's own code (tools/sprites, +// ADR 0026): the asset pack carries them, and the page makes a vanilla sprite from them instead of +// decoding its PNG. Decoded Mojang textures: build output, never committed or published. +val spriteFile = layout.buildDirectory.file("web-sprites/sprites.bin") + +tasks.register("sprites") { + group = "build" + description = "Decodes the vanilla sprites and their mip levels into build/web-sprites/sprites.bin." + classpath = spriteTool + mainClass = "incari.tools.sprites.Main" + javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) } + val jar = clientJar.get() + val file = spriteFile + inputs.file(jar) + inputs.files(spriteTool) + outputs.file(file) + // The game's classes write logs/ into the working directory; keep that in build/. + val runDir = layout.buildDirectory.dir("web-sprites/run").get().asFile + workingDir = runDir + doFirst { runDir.mkdirs() } + jvmArgs( + "--enable-native-access=ALL-UNNAMED", + "-Dorg.lwjgl.system.SharedLibraryExtractPath=${repoRoot.dir("work/natives/lwjgl").asFile}", + ) + argumentProviders.add(CommandLineArgumentProvider { listOf("--out", file.get().asFile.path) }) +} + +// The game has two builds (ADR 0036), both WebAssembly GC: Fast (JSPI) in build/teavm-fast/ and +// Compatible (TeaVM's coroutines) in build/teavm/. `-Pteavm.fast` makes the teavm task compile Fast, +// and the checks and the benchmark run it; without it, Compatible. The page offers whichever are built. +val fastBuild = providers.gradleProperty("teavm.fast").isPresent +val gameBuildDir = if (fastBuild) "teavm-fast" else "teavm" +/** The build the checks and the benchmark ask the page for (PageQuery): fast or compatible. */ +val gameBuild = if (fastBuild) "fast" else "compatible" + +tasks.register("teavm") { + group = "build" + description = "Compiles the Compatible build with TeaVM into build/teavm/ (-Pteavm.fast: Fast, into build/teavm-fast/)." + classpath = webbuildTool + mainClass = "incari.tools.webbuild.Main" + javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) } + maxHeapSize = "20g" + val libraries = repoRoot.dir("work/cache/libraries").asFile + // Incari's classes and the game as :client compiled it; the tool adds the Mojang libraries + // tools/survey/rules.txt keeps. Mojang's other jars (LWJGL, JNA...) stay out on purpose. + val appClasspath = sourceSets.main.get().runtimeClasspath.filter { !it.startsWith(libraries) } + // As an input, the classpath also makes Gradle build the jars on it first. + inputs.files(appClasspath) + // For experiments: `-Pteavm.main= -Pteavm.classpath=` compiles a small program + // against the same class library in seconds, instead of the game in minutes. + val mainClass = providers.gradleProperty("teavm.main").orElse("incari.app.web.WebMain") + val extraClasspath = providers.gradleProperty("teavm.classpath").orElse("") + // `-Pteavm.release`: TeaVM's ADVANCED optimizations, obfuscated, no debug information. + // `-Pteavm.names` (with release): Java names kept in the module, for readable CPU profiles. + // Binaryen's wasm-opt over the module (ADR 0034, 0043): on by default for the Fast release build + // (under a minute; `-Pteavm.noWasmOpt` leaves it out), and for the Compatible one only with + // `-Pteavm.wasmOpt` (a quarter of an hour and 10 GB more, not measured with ADR 0043's flags). + val release = providers.gradleProperty("teavm.release").isPresent + val names = providers.gradleProperty("teavm.names").isPresent + val wasmOpt = release && !providers.gradleProperty("teavm.noWasmOpt").isPresent && + (fastBuild || providers.gradleProperty("teavm.wasmOpt").isPresent) + inputs.property("wasmOpt", wasmOpt) + // `-Pteavm.fast`: the Fast build, which suspends through JSPI instead of coroutines + // (tools/webbuild's JspiTransformer, ADR 0036), into build/teavm-fast/. + val jspi = fastBuild + inputs.property("jspi", jspi) + inputs.property("release", release) + inputs.property("names", names) + // Experiments build into their own directory, so they never replace the game's build. + val output = layout.buildDirectory.dir( + providers.gradleProperty("teavm.main").map { "teavm-experiment" } + .orElse(gameBuildDir)) + // A development page that loads the module; `./gradlew :app-web:serve` serves the directory. + val page = layout.projectDirectory.file("src/main/web/index.html") + inputs.file(page) + inputs.property("mainClass", mainClass) + inputs.property("extraClasspath", extraClasspath) + // The experiment's classes themselves, so editing a probe recompiles it. + inputs.files(extraClasspath.map { path -> if (path.isEmpty()) emptyList() else listOf(File(path)) }) + outputs.dir(output) + val verbose = providers.gradleProperty("teavm.verbose").map { true }.orElse(false) + argumentProviders.add(CommandLineArgumentProvider { + listOf( + "--main", mainClass.get(), + "--classpath", (appClasspath.files.map { it.path } + extraClasspath.get()) + .filter { it.isNotEmpty() }.joinToString(File.pathSeparator), + "--out", output.get().asFile.path, + "--page", page.asFile.path, + ) + (if (verbose.get()) listOf("--verbose") else emptyList()) + + (if (release) listOf("--release") else emptyList()) + + (if (names) listOf("--names") else emptyList()) + + (if (wasmOpt) listOf("--wasm-opt") else emptyList()) + + (if (jspi) listOf("--jspi") else emptyList()) + }) + systemProperty("incari.cwd", repoRoot.asFile.path) + // `-Pteavm.explainAsync=,...`: explain in async.txt why methods suspend. + systemProperty("incari.explainAsync", providers.gradleProperty("teavm.explainAsync").orElse("").get()) + // `-Pteavm.throwCensus`: count every throw by site and thread, logged every 10 s (ADR 0033). + val throwCensus = providers.gradleProperty("teavm.throwCensus").isPresent + inputs.property("throwCensus", throwCensus) + systemProperty("incari.throwCensus", throwCensus.toString()) + // `-Pteavm.noJsoIntrinsics`: ints to JavaScript through TeaVM's import again (tools/webbuild's + // JsoIntrinsics), to compare. + val jsoIntrinsics = !providers.gradleProperty("teavm.noJsoIntrinsics").isPresent + inputs.property("jsoIntrinsics", jsoIntrinsics) + systemProperty("incari.jsoIntrinsics", jsoIntrinsics.toString()) +} + +// ---- The mesher workers' program ------------------------------------------------------------ +// Incari's terrain mesher on its own (incari.app.web.mesher.MesherWorker and the :mesher module, no +// game code), compiled by TeaVM into build/teavm-mesher/mesher.wasm with its loader beside it. The +// page's mesher workers load it (ADR 0023). Seconds to compile, not minutes. +val mesherOutput = layout.buildDirectory.dir("teavm-mesher") + +val teavmMesher = tasks.register("teavmMesher") { + group = "build" + description = "Compiles the mesher workers' program with TeaVM into build/teavm-mesher/." + classpath = webbuildTool + mainClass = "incari.tools.webbuild.Main" + javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) } + maxHeapSize = "4g" + val libraries = repoRoot.dir("work/cache/libraries").asFile + val appClasspath = sourceSets.main.get().runtimeClasspath.filter { !it.startsWith(libraries) } + inputs.files(appClasspath) + val release = providers.gradleProperty("teavm.release").isPresent + inputs.property("release", release) + val output = mesherOutput + outputs.dir(output) + argumentProviders.add(CommandLineArgumentProvider { + listOf( + "--main", "incari.app.web.mesher.MesherWorker", + "--classpath", appClasspath.files.joinToString(File.pathSeparator) { it.path }, + "--out", output.get().asFile.path, + "--name", "mesher", + ) + (if (release) listOf("--release") else emptyList()) + }) + systemProperty("incari.cwd", repoRoot.asFile.path) +} + +// ---- The loader page, the asset pack and the build manifest --------------------------------- +// The page's TypeScript (src/main/ts) with the types stripped by Node, the asset pack (build-time data +// the page mounts read-only: the translated shaders, so it's Mojang content and never published), and +// build.json (every file's size and hash, which the loader and its service worker version files by). +// All land in build/page/; the dev server serves them beside build/teavm/. ADR 0014. +val pageDir = layout.buildDirectory.dir("page") + +// Strips the types from each .ts file (Node's own stripping: the sources use only erasable syntax, as +// tsconfig.json enforces) and points relative imports at the .js files. +val stripTypesScript = """ + import { stripTypeScriptTypes } from "node:module"; + import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; + import { join } from "node:path"; + const [source, out] = process.argv.slice(-2); + rmSync(out, { recursive: true, force: true }); + mkdirSync(out, { recursive: true }); + for (const name of readdirSync(source).filter((n) => n.endsWith(".ts"))) { + const code = stripTypeScriptTypes(readFileSync(join(source, name), "utf8"), { mode: "strip" }) + .replace(/(from\s+["']\.\/[^"']+)\.ts(["'])/g, "${'$'}1.js${'$'}2"); + writeFileSync(join(out, name.replace(/\.ts${'$'}/, ".js")), code); + } +""".trimIndent() + +val pageScripts = tasks.register("pageScripts") { + group = "build" + description = "Strips the types from the page's TypeScript into build/page/scripts/." + val sources = layout.projectDirectory.dir("src/main/ts") + val out = pageDir.get().dir("scripts").asFile + inputs.dir(sources) + inputs.property("script", stripTypesScript) + outputs.dir(out) + executable = "node" + args("--no-warnings", "--input-type=module", "-e", stripTypesScript, sources.asFile.path, out.path) +} + +val packManifest = layout.buildDirectory.file("pack/pack.json") +val writePackManifest = tasks.register("packManifest") { + val version = minecraftVersion.get() + val file = packManifest + inputs.property("version", version) + outputs.file(file) + doLast { file.get().asFile.writeText("{\"format\": 1, \"game\": \"$version\"}\n") } +} + +// Via's mapping data (ADR 0017), which it reads from the class path: the pack carries it +// under classpath/, which the page adds to the class path's roots. +val viaJars = configurations.runtimeClasspath.map { classpath -> + classpath.filter { it.name.startsWith("viaversion-common-") || it.name.startsWith("viabackwards-common-") } +} + +tasks.register("assetPack") { + group = "build" + description = "Packs the build-time data the page mounts (translated shaders, decoded sprites, Via's data, Incari's pack) into build/page/incari.pack." + dependsOn("shaders", "sprites", writePackManifest) + from(packManifest) + from(shaderManifest) + from(spriteFile) + from(viaJars.map { jars -> jars.map { zipTree(it) } }) { + include("assets/viaversion/data/**", "assets/viabackwards/data/**") + into("classpath") + } + // Incari's own resource pack (its font), which the client reads from the class path. + from(rootProject.file("client/src/main/resources")) { + include("incari-pack/**") + into("classpath") + } + archiveFileName = "incari.pack" + destinationDirectory = pageDir + isPreserveFileTimestamps = false + isReproducibleFileOrder = true +} + +// The game's builds by the names the page fetches them by (tools/webbuild BuildManifest.BUILDS): +// Compatible's module as incari.wasm, Fast's as incari-fast.wasm, with their debugging files, and +// TeaVM's loader (one for both) from the build being compiled. Whichever are built are offered. +val gameModuleFiles: List = run { + val compatibleDir = layout.buildDirectory.dir("teavm").get().asFile + val fastDir = layout.buildDirectory.dir("teavm-fast").get().asFile + val suffixes = listOf("", "-deobfuscator.wasm", ".teadbg") + listOf("incari.wasm-runtime.js=${layout.buildDirectory.dir(gameBuildDir).get().asFile.resolve("incari.wasm-runtime.js")}") + + suffixes.map { "incari.wasm$it=${compatibleDir.resolve("incari.wasm$it")}" } + + suffixes.map { "incari-fast.wasm$it=${fastDir.resolve("incari.wasm$it")}" } +} + +// What the page loads, by the name it loads it by: the builds' files, the mesher, and the asset pack. +val buildFiles: List = run { + val mesherDir = layout.buildDirectory.dir("teavm-mesher").get().asFile + gameModuleFiles + + listOf("mesher.wasm", "mesher.wasm-runtime.js").map { "$it=${mesherDir.resolve(it)}" } + + "incari.pack=${pageDir.get().file("incari.pack").asFile}" +} + +// The experimental Rust build (ADR 0068): Horizon's browser port, its own page and files, which +// `./incari build` writes here (tools/build Horizon). Offered when it's there. +val rustDir = layout.buildDirectory.dir("rust").get().asFile + +tasks.register("buildManifest") { + group = "build" + description = "Writes build/page/build.json: the build's files with their sizes and hashes." + dependsOn("assetPack", teavmMesher) + // After a compile in the same run, not beside it: hashing a module TeaVM is still writing gave + // the page a manifest for the last build, and a cold start that never reached its first frame. + mustRunAfter("teavm") + classpath = webbuildTool + mainClass = "incari.tools.webbuild.BuildManifest" + javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) } + val out = pageDir.get().file("build.json").asFile + val version = minecraftVersion.get() + val files = buildFiles + val rust = rustDir + // Always: it hashes whatever build is there, which Gradle doesn't track between the tasks. + outputs.upToDateWhen { false } + outputs.file(out) + argumentProviders.add(CommandLineArgumentProvider { + listOf("--out", out.path, "--game", version, "--rust", rust.path) + files.flatMap { listOf("--file", it) } + }) +} + +// The loader page and its scripts, served by name over whatever the build's directory holds (the page +// there is a copy from the last compile), with both builds' modules by name. An experiment's build +// gets the page but no manifest, pack or other build. +fun pageServerArgs(experiment: Boolean): List { + val scripts = pageDir.get().dir("scripts").asFile + val page = layout.projectDirectory.file("src/main/web/index.html").asFile + val names = listOf("boot", "loader", "features", "jspi", "wakeups", "cache-policy", "sw", "game-worker") + return listOf("--file", "index.html=$page") + + names.flatMap { listOf("--file", "$it.js=${scripts.resolve("$it.js")}") } + + (if (experiment) emptyList() else listOf( + "--file", "mesher.wasm=${mesherOutput.get().file("mesher.wasm").asFile}", + "--file", "mesher.wasm-runtime.js=${mesherOutput.get().file("mesher.wasm-runtime.js").asFile}", + "--file", "build.json=${pageDir.get().file("build.json").asFile}", + "--file", "incari.pack=${pageDir.get().file("incari.pack").asFile}") + + gameModuleFiles.flatMap { listOf("--file", it) } + + listOf("--dir", "rust=${rustDir.path}")) +} + +tasks.register("serve") { + group = "application" + description = "Serves the game's builds on http://localhost:8080/ for development (never publish a build)." + dependsOn("shaders", pageScripts, "buildManifest") + classpath = webbuildTool + mainClass = "incari.tools.webbuild.Serve" + javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) } + val output = layout.buildDirectory.dir(gameBuildDir) + val port = providers.gradleProperty("port").orElse("8080") + // Resolved now: clientJar's mapping captures the build script, which the configuration cache can't store. + val jar = clientJar.get() + val manifest = shaderManifest + val assets = assetServerArgs.get() + val page = pageServerArgs(false) + argumentProviders.add(CommandLineArgumentProvider { + listOf(output.get().asFile.path, "--port", port.get(), + "--file", "client.jar=$jar", "--file", "shaders.json=" + manifest.get().asFile.path) + assets + page + }) +} + +// ---- The web folder -------------------------------------------------------------------------- +// `./gradlew :app-web:webFolder -Pteavm.release` writes what `serve` serves into one folder any static +// web server can serve (tools/webbuild WebFolder, ADR 0028), with its own build.json, an .htaccess and +// a README.txt that says it must not be shared. `./incari build` runs it. Options: `-Pweb.out=` +// (default build/web/), `-Pweb.builds=fast,compatible` (the builds to put in, both by default; ADR +// 0036: each must be compiled, Fast with -Pteavm.fast, and both release builds; `rust` adds +// build/rust/, ADR 0068), `-Pweb.noSounds` +// (leave the asset index out: ~460 MB of sounds, languages and the Unicode font), `-Pweb.skipBuild` (compile nothing first; otherwise the one +// build -Pteavm.fast picks is compiled). It holds Mojang's code and files: never published. +tasks.register("webFolder") { + group = "distribution" + description = "Writes the browser builds as one folder for a static web server (never publish it)." + if (!providers.gradleProperty("web.skipBuild").isPresent) { + dependsOn("teavm") + } + dependsOn("assetPack", teavmMesher, pageScripts) + classpath = webbuildTool + mainClass = "incari.tools.webbuild.WebFolder" + javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) } + val out = providers.gradleProperty("web.out").map { File(it).absolutePath } + .orElse(layout.buildDirectory.dir("web").get().asFile.path) + val builds = providers.gradleProperty("web.builds").orElse("fast,compatible").get() + .split(",").map { it.trim() }.filter { it.isNotEmpty() } + builds.forEach { + require(it == "fast" || it == "compatible" || it == "rust") { + "-Pweb.builds takes fast, compatible and rust, not '$it'" + } + } + val sounds = !providers.gradleProperty("web.noSounds").isPresent + val soundFiles = when { + providers.gradleProperty("web.noSoundFiles").isPresent -> "no" + providers.gradleProperty("web.smallSounds").isPresent -> "small" + providers.gradleProperty("web.coreSounds").isPresent -> "core" + else -> "yes" + } + val version = minecraftVersion.get() + val jar = clientJar.get() + // The index and objects directory assetServerArgs serves, as WebFolder's two options. + val assets = assetServerArgs.get().filterIndexed { i, _ -> i % 2 == 1 } + .map { it.substringAfter('=') } + val compatible = layout.buildDirectory.dir("teavm").get().asFile + val fast = layout.buildDirectory.dir("teavm-fast").get().asFile + val mesher = mesherOutput.get().asFile + val rust = rustDir + val page = layout.projectDirectory.file("src/main/web/index.html").asFile + val scripts = pageDir.get().dir("scripts").asFile + val pack = pageDir.get().file("incari.pack").asFile + // Always: it copies whatever build is there, which Gradle doesn't track between the tasks. + outputs.upToDateWhen { false } + argumentProviders.add(CommandLineArgumentProvider { + listOf( + "--out", out.get(), + "--game", version, + "--mesher", mesher.path, + "--page", page.path, + "--scripts", scripts.path, + "--pack", pack.path, + "--client-jar", jar, + ) + (if ("fast" in builds) listOf("--fast", fast.path) else emptyList()) + + (if ("compatible" in builds) listOf("--compatible", compatible.path) else emptyList()) + + (if ("rust" in builds) listOf("--rust", rust.path) else emptyList()) + + (if (sounds && assets.size == 2) listOf("--asset-index", assets[0], "--asset-objects", assets[1]) + else emptyList()) + + listOf("--sound-files", soundFiles) + }) +} + +// `./gradlew :app-web:webFolder :app-web:singleFile -Pteavm.release -Pweb.smallSounds -Pweb.html=` +// packs the folder webFolder wrote (-Pweb.out) into one HTML file that plays from the disk (tools/webbuild +// SingleFile, ADR 0057); `./incari build --html` runs it. -Pweb.smallSounds keeps the languages, the +// Unicode font and every sound but the music, encoded smaller with ffmpeg (~38 MB of 377; +// tools/webbuild SmallSounds); -Pweb.coreSounds ~10 MB of common sounds as they are (CoreSounds); +// -Pweb.noSoundFiles none of the sounds. Like the folder, never published. +tasks.register("singleFile") { + group = "distribution" + description = "Packs the web folder into one HTML file that plays from the disk (never publish it)." + dependsOn(pageScripts) + mustRunAfter("webFolder") + classpath = webbuildTool + mainClass = "incari.tools.webbuild.SingleFile" + javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) } + val folder = providers.gradleProperty("web.out").map { File(it).absolutePath } + .orElse(layout.buildDirectory.dir("web").get().asFile.path) + val html = providers.gradleProperty("web.html").map { File(it).absolutePath } + .orElse(layout.buildDirectory.file("incari.html").get().asFile.path) + val script = pageDir.get().dir("scripts").file("offline.js").asFile + outputs.upToDateWhen { false } + argumentProviders.add(CommandLineArgumentProvider { + listOf("--folder", folder.get(), "--out", html.get(), "--script", script.path) + }) +} + +tasks.register("browserCheck") { + group = "verification" + description = "Runs build/teavm/ in headless Chromium until the game loop's heartbeat shows." + // `-Pbrowser.html=`: a single-file build (singleFile, ADR 0057) instead, opened from the + // disk with nothing compiled or served; the other options work as for the build. + val html = providers.gradleProperty("browser.html").map { File(it).absolutePath } + if (!html.isPresent) { + dependsOn("teavm", "shaders", pageScripts) + } + val experiment = providers.gradleProperty("teavm.main").isPresent + if (!experiment && !html.isPresent) { + dependsOn("buildManifest") + } + classpath = webbuildTool + mainClass = "incari.tools.webbuild.BrowserCheck" + // The build the page runs (PageQuery); none for an experiment's, which has one module. + systemProperty("incari.build", if (providers.gradleProperty("teavm.main").isPresent) "" else gameBuild) + javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) } + val output = layout.buildDirectory.dir( + providers.gradleProperty("teavm.main").map { "teavm-experiment" }.orElse(gameBuildDir)) + // `-Pbrowser.expect= -Pbrowser.count=` for experiments (see the teavm task). + val expect = providers.gradleProperty("browser.expect") + val count = providers.gradleProperty("browser.count") + val seconds = providers.gradleProperty("browser.seconds") + // `-Pbrowser.query=renderer=headless` and the like: page options (see WebMain). + val query = providers.gradleProperty("browser.query") + // `-Pbrowser.steps="shot:build/title.png;click:0.5,0.45;sleep:2000;shot:build/next.png"`: what to do + // once the game runs, through the DevTools protocol (BrowserCheck.runStep lists the steps). A `;` + // starts a new step only before a step's name, so `eval:` JavaScript may contain them. + // `-Pbrowser.steps=@browser-checks/text-input.steps` reads them from a file, a step per line. + val steps = providers.gradleProperty("browser.steps") + val projectDir = layout.projectDirectory + val stepNames ="sleep|wait|shot|move|click|drag|hold|type|eval|init|key|down|up|assert|waitfor|holds|until|resize|clipboard|compose|insert|drop|rcon|rconwait|reload|choose|downloads|download|pack|profile" + // `-Pbrowser.rcon=127.0.0.1:25592`: the game server's remote console, for `rcon:` steps; + // the password comes from INCARI_RCON_PASSWORD. + val rcon = providers.gradleProperty("browser.rcon") + // `-Pbrowser.gpu=gl` (or vulkan): WebGL on this machine's GPU instead of SwiftShader, for + // timing frames; `webgpu`: Vulkan with WebGPU on the GPU too (probes/WebGpuCallProbe). + val gpu = providers.gradleProperty("browser.gpu") + val jar = clientJar.get() + val manifest = shaderManifest + val assets = assetServerArgs.get() + val page = pageServerArgs(experiment) + argumentProviders.add(CommandLineArgumentProvider { + (if (html.isPresent) listOf(html.get()) else listOf(output.get().asFile.path, + "--file", "client.jar=$jar", "--file", "shaders.json=" + manifest.get().asFile.path) + assets + page) + + (if (query.isPresent) listOf("--query", query.get()) else emptyList()) + + (if (!steps.isPresent) emptyList() + else if (steps.get().startsWith("@")) listOf("--steps-file", projectDir.file(steps.get().substring(1)).asFile.path) + else steps.get().split(Regex(";(?=($stepNames):)")).filter { it.isNotBlank() }.flatMap { listOf("--step", it) }) + + (if (seconds.isPresent) listOf("--seconds", seconds.get()) else emptyList()) + + (if (rcon.isPresent) listOf("--rcon", rcon.get()) else emptyList()) + + (if (gpu.isPresent) listOf("--gpu", gpu.get()) else emptyList()) + + (if (expect.isPresent) listOf("--expect", expect.get()) else emptyList()) + + (if (count.isPresent) listOf("--count", count.get()) else emptyList()) + }) +} + +// ---- Screenshot diffs against the desktop ---------------------------------------------------- +// `./gradlew :app-web:screenshotDiff` renders the scenes in screenshot-scenes/scenes.txt with the +// desktop game (Mojang's OpenGL backend) and with the browser build (WebGL2, in headless Chromium +// on this machine's GPU), both joined to a fresh vanilla server, and fails if a pair is less alike +// (SSIM) than the file's threshold, or if the page logs a WebGL error. The images are renders of +// Mojang's assets: they go to build/screenshots/ and are never committed. Needs a display and a GPU +// (the desktop game opens a window). Options: `-Pscreenshots.only=terrain,sky`, +// `-Pscreenshots.gpu=gl|vulkan|swiftshader` (default gl: ANGLE on the desktop's own driver), +// `-Pscreenshots.reuseDesktop` (keep the desktop images already rendered), `-Pscreenshots.skipBuild` +// (use build/teavm/ as it is instead of compiling first), `-Pscreenshots.port=18210` (six ports up +// from it: server, RCON, bridge, desktop agent, page, DevTools). +tasks.register("screenshotDiff") { + group = "verification" + description = "Renders fixed scenes on the desktop (OpenGL) and in Chromium (WebGL2) and compares them." + if (!providers.gradleProperty("screenshots.skipBuild").isPresent) { + dependsOn("teavm") + } + dependsOn("shaders", ":app-desktop:sceneLaunch", pageScripts, "buildManifest") + classpath = webbuildTool + mainClass = "incari.tools.webbuild.ScreenshotDiff" + // The build the page runs (PageQuery, ADR 0036). + systemProperty("incari.build", gameBuild) + javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) } + val scenes = layout.projectDirectory.dir("screenshot-scenes") + val output = layout.buildDirectory.dir(gameBuildDir) + val out = layout.buildDirectory.dir("screenshots") + val launch = project(":app-desktop").layout.buildDirectory.file("scene-launch.txt") + val versionDir = minecraftVersion.map { repoRoot.dir("work/cache/versions/$it").asFile.path }.get() + val version = minecraftVersion.get() + val jar = clientJar.get() + val manifest = shaderManifest + val only = providers.gradleProperty("screenshots.only") + // `-Pscreenshots.query=sprites=off`: extra page options for the browser's run, to compare. + val screenshotQuery = providers.gradleProperty("screenshots.query") + val gpu = providers.gradleProperty("screenshots.gpu").orElse("gl") + val port = providers.gradleProperty("screenshots.port").orElse("18210") + val reuseDesktop = providers.gradleProperty("screenshots.reuseDesktop").isPresent + val page = pageServerArgs(false) + // Always runs: its inputs include a GPU, a server and two games. + outputs.upToDateWhen { false } + argumentProviders.add(CommandLineArgumentProvider { + listOf( + "--scenes", scenes.file("scenes.txt").asFile.path, + "--options", scenes.file("options.txt").asFile.path, + "--server-properties", scenes.file("server.properties").asFile.path, + "--out", out.get().asFile.path, + "--build", output.get().asFile.path, + "--file", "client.jar=$jar", + "--file", "shaders.json=" + manifest.get().asFile.path, + "--desktop-launch", launch.get().asFile.path, + "--version-json", "$versionDir/$version.json", + "--cache", versionDir, + "--gpu", gpu.get(), + "--port", port.get(), + ) + page + (if (only.isPresent) listOf("--only", only.get()) else emptyList()) + + (if (screenshotQuery.isPresent) listOf("--query", screenshotQuery.get()) else emptyList()) + + (if (reuseDesktop) listOf("--reuse-desktop") else emptyList()) + }) +} + +// ---- The benchmark --------------------------------------------------------------------------- +// `./gradlew :app-web:benchmark` plays benchmark/benchmark.txt's scenarios (a fly-through over fresh +// terrain, a fight in an arena) in the browser build against a fresh vanilla world, times the loads +// (cold and warm start to the title screen, the join), and reports what the page's profiler +// measured: frame rate and 1% low, tick, extract, render submit and GPU time, draw calls, the mesh +// queue, memory and GC pauses. The report goes to build/benchmark/ (report.md, report.json) and, in +// CI, to the job summary. It fails if a figure regressed past its rule against this machine's +// baseline (benchmark/baseline.properties). Needs a GPU for meaningful figures. Options: +// `-Pbenchmark.machine=` (default: the host name), `-Pbenchmark.updateBaseline` (record this +// machine's figures instead of comparing), `-Pbenchmark.only=flythrough`, `-Pbenchmark.query=multidraw=off` +// (extra page options), `-Pbenchmark.gpu=gl|vulkan|swiftshader` (default gl), `-Pbenchmark.headed` (a +// Chromium window instead of headless), `-Pbenchmark.connect=: -Pbenchmark.pageHost=
` +// (a Chrome reachable over DevTools, a Chromebook's: docs/benchmark.md), `-Pbenchmark.skipBuild` +// (use build/teavm/ as it is), `-Pbenchmark.port=18310` (five ports up from it: server, RCON, bridge, +// page, DevTools), `-Pbenchmark.history=` (default ~/.incari/benchmark-history.jsonl: the runs the +// report's trend charts come from, kept on this machine only), `-Pbenchmark.cpuThrottle=` (the +// page's CPU that many times slower: a Chromebook stand-in, under its own machine name), +// `-Pbenchmark.singleplayer` (benchmark/singleplayer.txt in a world the page creates and runs itself, +// ADR 0039: no server here; its own baseline, singleplayer-baseline.properties, and history). Run +// :app-web:checkDownloadSize first +// to have the download size in the report. +tasks.register("benchmark") { + group = "verification" + description = "Plays the benchmark's scenarios in the browser build and holds the figures to the baseline." + if (!providers.gradleProperty("benchmark.skipBuild").isPresent) { + dependsOn("teavm") + } + dependsOn("shaders", pageScripts, "buildManifest") + classpath = webbuildTool + mainClass = "incari.tools.webbuild.Benchmark" + // The build the page runs (PageQuery, ADR 0036). + systemProperty("incari.build", gameBuild) + javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) } + val dir = layout.projectDirectory.dir("benchmark") + val output = layout.buildDirectory.dir(gameBuildDir) + val out = layout.buildDirectory.dir("benchmark") + val downloadReport = layout.buildDirectory.file("reports/download-size.json") + val versionDir = minecraftVersion.map { repoRoot.dir("work/cache/versions/$it").asFile.path }.get() + val version = minecraftVersion.get() + val jar = clientJar.get() + val manifest = shaderManifest + val assets = assetServerArgs.get() + val page = pageServerArgs(false) + val machine = providers.gradleProperty("benchmark.machine") + val update = providers.gradleProperty("benchmark.updateBaseline").isPresent + val only = providers.gradleProperty("benchmark.only") + val query = providers.gradleProperty("benchmark.query") + val gpu = providers.gradleProperty("benchmark.gpu").orElse("gl") + val headed = providers.gradleProperty("benchmark.headed").isPresent + // `-Pbenchmark.cpuThrottle=4`: Chrome runs the page's CPU four times slower, a stand-in for a + // Chromebook's CPU (ADR 0027); record it under a machine name of its own. + val cpuThrottle = providers.gradleProperty("benchmark.cpuThrottle") + // `-Pbenchmark.gcTrace`: each scenario's collector events, phases included, in time order + // (build/benchmark/-.gc.txt; ADR 0027). + val gcTrace = providers.gradleProperty("benchmark.gcTrace").isPresent + // `-Pbenchmark.profile`: a CPU profile of each measured stretch, build/benchmark/-.cpuprofile. + val profile = providers.gradleProperty("benchmark.profile").isPresent + // `-Pbenchmark.heapProfile`: the heap sampler's live objects at the title screen and after each + // scenario, build/benchmark/.heapprofile. + val heapProfile = providers.gradleProperty("benchmark.heapProfile").isPresent + // `-Pbenchmark.heapSnapshot`: heap snapshots at the same points, with their sizes by type. + val heapSnapshot = providers.gradleProperty("benchmark.heapSnapshot").isPresent + // `-Pbenchmark.desktopJfr`: the desktop game plays the scenarios instead of the page, each + // measured stretch recorded by the Flight Recorder with its allocations by site. + val desktopJfr = providers.gradleProperty("benchmark.desktopJfr").isPresent + if (desktopJfr) { + dependsOn(":app-desktop:sceneLaunch") + } + val desktopLaunch = project(":app-desktop").layout.buildDirectory.file("scene-launch.txt") + val connect = providers.gradleProperty("benchmark.connect") + val pageHost = providers.gradleProperty("benchmark.pageHost") + val port = providers.gradleProperty("benchmark.port").orElse("18310") + // `-Pbenchmark.singleplayer`: singleplayer's scenarios, figures and baseline instead (ADR 0039). + val singleplayer = providers.gradleProperty("benchmark.singleplayer").isPresent + // `-Pbenchmark.script=hudeditor.txt`: another script in benchmark/ (with -Pbenchmark.singleplayer + // for one that plays in the page's own world), measured but kept out of the usual history. + val script = providers.gradleProperty("benchmark.script") + val history = providers.gradleProperty("benchmark.history") + .orElse( + System.getProperty("user.home") + "/.incari/benchmark-" + + (if (singleplayer) "singleplayer-" else "") + "history.jsonl", + ) + // Always runs: its inputs include a GPU, a server and a browser. + outputs.upToDateWhen { false } + argumentProviders.add(CommandLineArgumentProvider { + listOf( + "--script", + dir.file(script.getOrElse(if (singleplayer) "singleplayer.txt" else "benchmark.txt")).asFile.path, + "--options", dir.file("options.txt").asFile.path, + "--server-properties", dir.file("server.properties").asFile.path, + "--baseline", + dir.file(if (singleplayer) "singleplayer-baseline.properties" else "baseline.properties").asFile.path, + "--budgets", dir.file("budgets.properties").asFile.path, + "--out", out.get().asFile.path, + "--build", output.get().asFile.path, + "--file", "client.jar=$jar", + "--file", "shaders.json=" + manifest.get().asFile.path, + "--version-json", "$versionDir/$version.json", + "--cache", versionDir, + "--download-report", downloadReport.get().asFile.path, + "--history", history.get(), + "--gpu", gpu.get(), + "--port", port.get(), + ) + assets + page + + (if (machine.isPresent) listOf("--machine", machine.get()) else emptyList()) + + (if (update) listOf("--update-baseline") else emptyList()) + + (if (only.isPresent) listOf("--only", only.get()) else emptyList()) + + (if (query.isPresent) listOf("--query", query.get()) else emptyList()) + + (if (headed) listOf("--headed") else emptyList()) + + (if (profile) listOf("--profile") else emptyList()) + + (if (heapProfile) listOf("--heap-profile") else emptyList()) + + (if (heapSnapshot) listOf("--heap-snapshot") else emptyList()) + + (if (desktopJfr) listOf("--desktop-launch", desktopLaunch.get().asFile.path) else emptyList()) + + (if (connect.isPresent) listOf("--connect", connect.get()) else emptyList()) + + (if (pageHost.isPresent) listOf("--page-host", pageHost.get()) else emptyList()) + + (if (cpuThrottle.isPresent) listOf("--cpu-throttle", cpuThrottle.get()) else emptyList()) + + (if (gcTrace) listOf("--gc-trace") else emptyList()) + + (if (singleplayer) listOf("--singleplayer") else emptyList()) + }) +} + +// ---- Download-size budget -------------------------------------------------------------------- +// `./gradlew :app-web:checkDownloadSize` measures what a player downloads (the build output and +// the files the dev server serves beside it) against download-budget.properties, raw, gzip and +// brotli, and fails when a file is over budget or unclassified. It writes +// build/reports/download-size.json for charting. `-PdownloadSize.skipBuild` measures the build +// already in build/teavm/ instead of compiling first (the compile takes about ten minutes); +// `-PdownloadSize.noBrotli` skips brotli, whose highest quality takes a minute or two. +tasks.register("checkDownloadSize") { + group = "verification" + description = "Checks the browser build's download size against download-budget.properties." + val skipBuild = providers.gradleProperty("downloadSize.skipBuild").isPresent + if (!skipBuild) { + dependsOn("teavm") + // The build-time shader manifest, once that task exists. + dependsOn(tasks.matching { it.name == "shaders" }) + } + dependsOn(pageScripts, "buildManifest") + classpath = webbuildTool + mainClass = "incari.tools.webbuild.DownloadSize" + javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) } + val budget = layout.projectDirectory.file("download-budget.properties") + val output = layout.buildDirectory.dir(gameBuildDir) + val shaders = layout.buildDirectory.file("web-shaders/shaders.json") + val report = layout.buildDirectory.file("reports/download-size.json") + val noBrotli = providers.gradleProperty("downloadSize.noBrotli").isPresent + // Resolved now: clientJar's mapping captures the build script, which the configuration cache + // can't store inside a task. + val vendorJar = clientJar.get() + // The loader page: its scripts, the build manifest and the asset pack. + val scripts = pageDir.get().dir("scripts").asFile + val pageFiles = listOf("boot", "loader", "features", "jspi", "wakeups", "cache-policy", "sw", "game-worker").map { "$it.js=${scripts.resolve("$it.js")}" } + + listOf("build.json=${pageDir.get().file("build.json").asFile}", "incari.pack=${pageDir.get().file("incari.pack").asFile}") + argumentProviders.add(CommandLineArgumentProvider { + listOf( + "--budget", budget.asFile.path, + "--dir", output.get().asFile.path, + // Files the page fetches from outside build/teavm/: =. + "--file", "shaders.json=" + shaders.get().asFile.path, + "--file", "client.jar=" + vendorJar, + "--report", report.get().asFile.path, + ) + pageFiles.flatMap { listOf("--file", it) } + (if (noBrotli) listOf("--no-brotli") else emptyList()) + }) +} diff --git a/incari-client/files/app-web/download-budget.properties b/incari-client/files/app-web/download-budget.properties new file mode 100644 index 0000000..e1a6b9c --- /dev/null +++ b/incari-client/files/app-web/download-budget.properties @@ -0,0 +1,82 @@ +# What a player downloads to start the browser build, checked by `./gradlew :app-web:checkDownloadSize` +# (tools/webbuild DownloadSize). Raising a number is fine when the pull request says why; the point +# is that growth is noticed. +# +# Every file in app-web/build/teavm/, and each extra file the page fetches, must be classified here, +# or the check fails: nothing ships unmeasured. +# download the page fetches it at start: measured and budgeted +# debug only a development build has it; measured, not budgeted +# report a compile report; the page never fetches it +# vendor Mojang's file, fetched by the page but not shipped by Incari: measured, not budgeted + +file.incari.wasm=download +file.incari.wasm-runtime.js=download +file.index.html=download +# The build-time shader manifest (built by :app-web:shaders; the dev server serves it next to the page). +# The page reads it from the asset pack; an experiment's build without a pack still +# fetches it, so it's measured, not counted twice. +file.shaders.json=debug +# The loader: its scripts (src/main/ts, types stripped), the build manifest, and the asset pack +# (build-time data: the translated shaders, in a zip). +file.boot.js=download +file.loader.js=download +file.features.js=download +file.jspi.js=download +file.wakeups.js=download +file.game-worker.js=download +file.cache-policy.js=download +file.sw.js=download +file.build.json=download +file.incari.pack=download + +# TeaVM's stack deobfuscator and the debug information it reads. The development page fetches both +# at start (index.html enables `stackDeobfuscator`), but a release build (webbuild --release) makes +# neither, so they aren't part of what a player downloads. +file.incari.wasm-deobfuscator.wasm=debug +file.incari.wasm.teadbg=debug + +file.*.txt=report + +# The game's own jar, which the page unpacks for its resources (ClientJar). Mojang's file: reported +# so its weight is visible, never counted as Incari's. +file.client.jar=vendor + +# Limits in bytes. The budget is in gzip (level 9, compressed once at deploy time): every browser +# and static host handles it. Brotli (quality 11) is smaller and reported next to it, but a host may +# not serve it. The module's raw size is limited too: the Chromebook holds and compiles it uncompressed. +# +# The limits are the development build's size (`:app-web:teavm`: TeaVM's SIMPLE optimization, +# unobfuscated, so the module carries a 70 MB `name` section) plus a little headroom. Accidental +# growth (a survey rule that pulls in a library, a class-library change that drags in a subsystem) +# tends to be bigger than that, so a limit is raised deliberately. Measured 2026-09-29, with Via and +# the Eagler stage: development build 193.86 MB raw, 38.65 MB gzip; release build (-Pteavm.release) +# 66.33 MB raw, 20.06 MB gzip, 12.56 MB brotli. Via's translation code is most of the growth. +max.gzip.total=40_300_000 +max.gzip.incari.wasm=40_000_000 +max.raw.incari.wasm=200_000_000 +# TeaVM's loader; changes only with a TeaVM upgrade (8.8 kB gzip measured). +max.gzip.incari.wasm-runtime.js=10_000 +# The page, with its loading screen's images inline (the backdrop, the mark and the icon, base64: +# about 26 kB that gzip can't shrink). Measured 21.8 kB gzip (2026-10-20). +max.gzip.index.html=25_000 +# The translated shaders: 309 stages, 1107 kB raw, 43.5 kB gzip (2026-09-28, ADR 0012). They ship in +# the asset pack (below), whose limit carries this one. +# The loader's scripts are a few kilobytes each; the asset pack carries the shaders (deflated, +# so about what shaders.json gzips to) and a manifest. +max.gzip.boot.js=6_000 +max.gzip.loader.js=4_000 +max.gzip.features.js=2_000 +# Measured 1.6, 1.1 and 2.6 kB gzip (2026-10-19). +max.gzip.jspi.js=3_000 +max.gzip.wakeups.js=2_000 +max.gzip.game-worker.js=4_000 +max.gzip.cache-policy.js=2_000 +max.gzip.sw.js=3_000 +max.gzip.build.json=2_000 +# Via's mapping data rides in the pack (classpath/): 1.25 MB of NBT and JSON, about 270 kB +# compressed. Measured 318.5 kB gzip with the shaders. +# The vanilla sprites decoded (ADR 0026) with their mip levels (sprites.bin, 3142 sprites, 7.4 +# MB raw, about 1.06 MB deflated), so a start skips decoding their PNGs. Measured 1.39 MB with the rest. +# Incari's own pack rides in it too (classpath/incari-pack/): GUI textures and six fonts, 379 kB +# packed. Measured 1.73 MB in all (2026-10-20). +max.gzip.incari.pack=1_900_000 diff --git a/incari-client/files/app-web/probes/ArrayDequeProbe.java b/incari-client/files/app-web/probes/ArrayDequeProbe.java new file mode 100644 index 0000000..8204fd2 --- /dev/null +++ b/incari-client/files/app-web/probes/ArrayDequeProbe.java @@ -0,0 +1,61 @@ +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +/** + * Regression probe for tools/teavm-patches' TArrayDeque fix: removing elements through an + * {@code ArrayDeque}'s iterator, as the game's particle groups do every tick. TeaVM's iterator + * skipped the element after one it removed and then returned null past the end, so the first + * particle to expire in a world crashed the game. Checks every removal pattern of up to ten + * elements, with the deque's contents wrapped around its array at several offsets. Prints + * "probe passed" when every deque holds what's left in order. + */ +public final class ArrayDequeProbe { + + private ArrayDequeProbe() {} + + public static void main(String[] args) { + String failure = null; + for (int size = 1; size <= 10 && failure == null; size++) { + for (int removed = 0; removed < 1 << size && failure == null; removed++) { + for (int offset = 0; offset < 5 && failure == null; offset++) { + failure = check(size, removed, offset); + } + } + } + System.out.println(failure == null ? "probe passed" : "probe failed: " + failure); + } + + /** Null if removing the elements whose bits are set in {@code removed} works, else what went wrong. */ + private static String check(int size, int removed, int offset) { + ArrayDeque deque = new ArrayDeque<>(8); + for (int i = 0; i < offset; i++) { + deque.add(-1); + } + for (int i = 0; i < offset; i++) { + deque.poll(); + } + List expected = new ArrayList<>(); + for (int i = 0; i < size; i++) { + deque.add(i); + if ((removed & 1 << i) == 0) { + expected.add(i); + } + } + List seen = new ArrayList<>(); + for (Iterator iterator = deque.iterator(); iterator.hasNext(); ) { + Integer value = iterator.next(); + seen.add(value); + if (value != null && (removed & 1 << value) != 0) { + iterator.remove(); + } + } + List left = new ArrayList<>(deque); + if (seen.size() != size || seen.contains(null) || !left.equals(expected)) { + return "size " + size + ", removing " + Integer.toBinaryString(removed) + ", offset " + offset + + ": iterated " + seen + ", left " + left; + } + return null; + } +} diff --git a/incari-client/files/app-web/probes/ArrayInstanceOfProbe.java b/incari-client/files/app-web/probes/ArrayInstanceOfProbe.java new file mode 100644 index 0000000..88779f1 --- /dev/null +++ b/incari-client/files/app-web/probes/ArrayInstanceOfProbe.java @@ -0,0 +1,33 @@ +import com.viaversion.viaversion.api.minecraft.item.HashedStructuredItem; +import com.viaversion.viaversion.api.minecraft.item.Item; +import com.viaversion.viaversion.api.minecraft.item.StructuredItem; + +/** + * Regression probe for Via's StructuredItemRewriter: it tells a data component's value + * apart with {@code value instanceof Item[]}. Prints "probe passed" when arrays of other element + * types (and an interface array of another interface) don't answer true, and real item arrays do. + */ +public final class ArrayInstanceOfProbe { + + interface Other {} + + private ArrayInstanceOfProbe() {} + + public static void main(String[] args) { + Object items = new StructuredItem[] {StructuredItem.empty()}; + Object itemIface = new Item[] {StructuredItem.empty()}; + Object hashed = new HashedStructuredItem[] {HashedStructuredItem.empty()}; + Object others = new Other[] {new Other() {}}; + Object strings = new String[] {"a"}; + Object objects = new Object[] {"a"}; + Object nested = new StructuredItem[][] {{StructuredItem.empty()}}; + Object ints = new int[1]; + Object intsNested = new int[1][1]; + String more = "" + (nested instanceof Item[][]) + (nested instanceof Item[]) + (nested instanceof Other[][]) + + (ints instanceof int[]) + (ints instanceof Object[]) + (intsNested instanceof int[][]) + + (intsNested instanceof Item[][]) + (strings instanceof Object[]) + (null instanceof Item[]); + String result = "" + (items instanceof Item[]) + (itemIface instanceof Item[]) + (hashed instanceof Item[]) + + (others instanceof Item[]) + (strings instanceof Item[]) + (objects instanceof Item[]); + System.out.println((result + more).equals("truetruefalsefalsefalsefalse" + "truefalsefalsetruefalsetruefalsetruefalse") ? "probe passed" : "probe failed: " + result + " " + more); + } +} diff --git a/incari-client/files/app-web/probes/ByteCopyProbe.java b/incari-client/files/app-web/probes/ByteCopyProbe.java new file mode 100644 index 0000000..00e8de8 --- /dev/null +++ b/incari-client/files/app-web/probes/ByteCopyProbe.java @@ -0,0 +1,99 @@ +import java.nio.ByteBuffer; +import org.teavm.jso.JSBody; +import org.teavm.jso.typedarrays.ArrayBuffer; +import org.teavm.jso.typedarrays.Int8Array; + +/** + * Measures how bytes cross between Java arrays and JavaScript buffers in the WebAssembly GC build: + * TeaVM's {@code Int8Array.copyFromJavaArray} / {@code copyToJavaArray}, against a route through a + * direct buffer in linear memory, which JavaScript can view and slice. Every message between the + * page and singleplayer's server worker (packets, file changes) crosses this way. Prints the times + * and "probe passed" when both routes agree on the bytes. + */ +public final class ByteCopyProbe { + + private ByteCopyProbe() {} + + public static void main(String[] args) { + int size = 1 << 20; + byte[] source = new byte[size]; + for (int i = 0; i < size; i++) { + source[i] = (byte) (i * 31 + (i >>> 8)); + } + ByteBuffer direct = ByteBuffer.allocateDirect(size); + int rounds = 20; + // Warm up both routes. + for (int i = 0; i < 3; i++) { + Int8Array.copyFromJavaArray(source); + viaLinear(source, direct); + } + + double start = now(); + Int8Array teavm = null; + for (int i = 0; i < rounds; i++) { + teavm = Int8Array.copyFromJavaArray(source); + } + double teavmOut = (now() - start) / rounds; + + start = now(); + ArrayBuffer linear = null; + for (int i = 0; i < rounds; i++) { + linear = viaLinear(source, direct); + } + double linearOut = (now() - start) / rounds; + + start = now(); + byte[] back = null; + for (int i = 0; i < rounds; i++) { + back = teavm.copyToJavaArray(); + } + double teavmIn = (now() - start) / rounds; + + start = now(); + byte[] backLinear = null; + for (int i = 0; i < rounds; i++) { + backLinear = fromLinear(linear, direct); + } + double linearIn = (now() - start) / rounds; + + boolean same = java.util.Arrays.equals(back, source) && java.util.Arrays.equals(backLinear, source) + && same(teavm.getBuffer(), linear); + System.out.println("ByteCopyProbe: 1 MiB to JavaScript: copyFromJavaArray " + teavmOut + + " ms, through linear memory " + linearOut + " ms; back: copyToJavaArray " + teavmIn + + " ms, through linear memory " + linearIn + " ms"); + System.out.println(same ? "probe passed" : "probe failed: the bytes differ"); + } + + private static ArrayBuffer viaLinear(byte[] source, ByteBuffer direct) { + direct.clear(); + direct.put(source, 0, source.length); + return sliceOf(Int8Array.fromJavaBuffer(direct), source.length); + } + + private static byte[] fromLinear(ArrayBuffer buffer, ByteBuffer direct) { + int length = buffer.getByteLength(); + setInto(Int8Array.fromJavaBuffer(direct), buffer); + byte[] out = new byte[length]; + direct.get(0, out, 0, length); + return out; + } + + @JSBody( + params = {"view", "length"}, + script = "return view.buffer.slice(view.byteOffset, view.byteOffset + length);") + private static native ArrayBuffer sliceOf(Int8Array view, int length); + + @JSBody( + params = {"view", "buffer"}, + script = "view.set(new Int8Array(buffer));") + private static native void setInto(Int8Array view, ArrayBuffer buffer); + + @JSBody( + params = {"a", "b"}, + script = "var x = new Int8Array(a), y = new Int8Array(b); if (x.length !== y.length) return false;" + + "for (var i = 0; i < x.length; i++) if (x[i] !== y[i]) return false; return true;") + private static native boolean same(ArrayBuffer a, ArrayBuffer b); + + @JSBody(script = "return performance.now();") + private static native double now(); +} diff --git a/incari-client/files/app-web/probes/ChannelClassProbe.java b/incari-client/files/app-web/probes/ChannelClassProbe.java new file mode 100644 index 0000000..cd50b7e --- /dev/null +++ b/incari-client/files/app-web/probes/ChannelClassProbe.java @@ -0,0 +1,35 @@ +import io.netty.bootstrap.Bootstrap; +import io.netty.channel.local.LocalChannel; + +/** + * {@code Bootstrap.channel(Class)} in the browser build: it works for a channel class whose + * constructor tools/webbuild's ReflectionDeclarations declares, and throws for one it doesn't, as + * it did for PlatformSocketChannel in the server list's legacy ping (which crashed the game). + */ +public final class ChannelClassProbe { + + private ChannelClassProbe() {} + + /** Public, with a public no-arg constructor, like PlatformSocketChannel; not declared. */ + public static final class Undeclared extends LocalChannel { + public Undeclared() {} + } + + public static void main(String[] args) { + System.setProperty("io.netty.noUnsafe", "true"); + try { + new Bootstrap().channel(LocalChannel.class); + System.out.println("channel(Class) accepted a declared class"); + } catch (Throwable t) { + System.out.println("probe failed: channel(Class) threw for a declared class: " + t); + return; + } + try { + new Bootstrap().channel(Undeclared.class); + System.out.println("probe failed: channel(Class) accepted an undeclared class"); + } catch (Throwable t) { + System.out.println("channel(Class) threw " + t); + System.out.println("probe passed"); + } + } +} diff --git a/incari-client/files/app-web/probes/CoroutineCostProbe.java b/incari-client/files/app-web/probes/CoroutineCostProbe.java new file mode 100644 index 0000000..10fb276 --- /dev/null +++ b/incari-client/files/app-web/probes/CoroutineCostProbe.java @@ -0,0 +1,413 @@ +/** + * Measures what TeaVM's coroutine transformation costs ordinary code in the browser build: the same + * workload compiled twice, once as plain functions and once as coroutines, timed in one module. + * + *

The workload looks like the game's hot paths: a loop over objects calling through interfaces + * with several implementations (as block, shape and entity code does), and a small open-addressing + * table whose lookups call the keys' {@code hashCode} and {@code equals} (as every {@code Map.get} + * does). In the game those virtual calls are suspension points because one implementation somewhere + * can block (ADR 0027), so the coroutine copy puts one blocking implementation into each call site's + * reach, never called. Everything else is the same code, duplicated by hand: shared code would merge + * the two copies in TeaVM's flow analysis. Prints nanoseconds per item for each copy, and "probe + * passed". + * + *

Each copy has one extra implementation at each call that the loops never call: blocking in + * the coroutine copy, harmless in the plain one, so both call sites are equally polymorphic. + * + *

What it found (2026-10-05, release build, Chrome on the desktop): with coroutines the + * coroutine copy takes 8.3 to 8.7 ns an item against 5.5 to 5.9 ns, about 1.5 times as long; in the + * Fast build ({@code -Pteavm.fast}, no coroutines) the two take the same, 5.3 to 5.7 ns. Only the + * callers ({@code coroutineWork}, {@code CTable.get}) are coroutines here; the shapes and keys stay + * plain. + * That's about 0.7 ns for each call through a suspension point, from the coroutine's prologue, the + * check after each call, and locals kept alive and nullable for the save path. + */ +public final class CoroutineCostProbe { + + private static final int ITEMS = 200_000; + private static final int ROUNDS = 7; + + /** Never true; lets the coroutine copy's blocking implementations suspend. */ + static volatile boolean suspend; + + static volatile long sink; + + static void maybeSleep() { + if (suspend) { + try { + Thread.sleep(1); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } + } + + // ----- Plain copy ----- + + interface PShape { + double value(int i, PVec v); + } + + static final class PVec { + double x; + double y; + double z; + + PVec(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; + } + } + + static final class PBox implements PShape { + final double size; + + PBox(double size) { + this.size = size; + } + + @Override + public double value(int i, PVec v) { + return v.x * size + v.y - (i & 3); + } + } + + static final class PSlab implements PShape { + @Override + public double value(int i, PVec v) { + return v.z * 0.5 + (i & 7); + } + } + + static final class PStair implements PShape { + final PShape inner; + + PStair(PShape inner) { + this.inner = inner; + } + + @Override + public double value(int i, PVec v) { + return inner.value(i + 1, v) * 0.25 + v.y; + } + } + + static class PKey { + final int a; + final int b; + + PKey(int a, int b) { + this.a = a; + this.b = b; + } + + @Override + public int hashCode() { + return a * 31 + b; + } + + @Override + public boolean equals(Object o) { + return o instanceof PKey k && k.a == a && k.b == b; + } + } + + /** As CBlocking, without the blocking: the same number of implementations at each call. */ + static final class PExtra implements PShape { + @Override + public double value(int i, PVec v) { + sink++; + return 0; + } + } + + /** As CBlockingKey, without the blocking. */ + static final class PExtraKey extends PKey { + PExtraKey() { + super(-1, -1); + } + + @Override + public int hashCode() { + sink++; + return 7; + } + + @Override + public boolean equals(Object o) { + sink++; + return false; + } + } + + static final class PKey2 extends PKey { + PKey2(int a, int b) { + super(a, b); + } + + @Override + public int hashCode() { + return a * 17 ^ b; + } + } + + static final class PTable { + final Object[] keys = new Object[1024]; + final int[] values = new int[1024]; + + void put(Object key, int value) { + int slot = key.hashCode() & 1023; + while (keys[slot] != null && !keys[slot].equals(key)) { + slot = (slot + 1) & 1023; + } + keys[slot] = key; + values[slot] = value; + } + + int get(Object key) { + int slot = key.hashCode() & 1023; + while (keys[slot] != null) { + if (keys[slot].equals(key)) { + return values[slot]; + } + slot = (slot + 1) & 1023; + } + return -1; + } + } + + static double plainWork(PShape[] shapes, PVec[] vecs, PTable table, Object[] keys) { + double acc = 0; + for (int i = 0; i < ITEMS; i++) { + PVec v = vecs[i & 63]; + acc += shapes[i & 7].value(i, v); + acc += table.get(keys[i & 255]); + } + return acc; + } + + // ----- Coroutine copy: the same, with one blocking implementation in reach ----- + + interface CShape { + double value(int i, CVec v); + } + + static final class CVec { + double x; + double y; + double z; + + CVec(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; + } + } + + static final class CBox implements CShape { + final double size; + + CBox(double size) { + this.size = size; + } + + @Override + public double value(int i, CVec v) { + return v.x * size + v.y - (i & 3); + } + } + + static final class CSlab implements CShape { + @Override + public double value(int i, CVec v) { + return v.z * 0.5 + (i & 7); + } + } + + static final class CStair implements CShape { + final CShape inner; + + CStair(CShape inner) { + this.inner = inner; + } + + @Override + public double value(int i, CVec v) { + return inner.value(i + 1, v) * 0.25 + v.y; + } + } + + /** Never in the timed loop's array slots it reads; only makes the calls suspension points. */ + static final class CBlocking implements CShape { + @Override + public double value(int i, CVec v) { + maybeSleep(); + return 0; + } + } + + static class CKey { + final int a; + final int b; + + CKey(int a, int b) { + this.a = a; + this.b = b; + } + + @Override + public int hashCode() { + return a * 31 + b; + } + + @Override + public boolean equals(Object o) { + return o instanceof CKey k && k.a == a && k.b == b; + } + } + + static final class CKey2 extends CKey { + CKey2(int a, int b) { + super(a, b); + } + + @Override + public int hashCode() { + return a * 17 ^ b; + } + } + + /** As the game's one blocking toString makes every Object method a suspension point. */ + static final class CBlockingKey extends CKey { + CBlockingKey() { + super(-1, -1); + } + + @Override + public int hashCode() { + maybeSleep(); + return 7; + } + + @Override + public boolean equals(Object o) { + maybeSleep(); + return false; + } + } + + static final class CTable { + final Object[] keys = new Object[1024]; + final int[] values = new int[1024]; + + void put(Object key, int value) { + int slot = key.hashCode() & 1023; + while (keys[slot] != null && !keys[slot].equals(key)) { + slot = (slot + 1) & 1023; + } + keys[slot] = key; + values[slot] = value; + } + + int get(Object key) { + int slot = key.hashCode() & 1023; + while (keys[slot] != null) { + if (keys[slot].equals(key)) { + return values[slot]; + } + slot = (slot + 1) & 1023; + } + return -1; + } + } + + static double coroutineWork(CShape[] shapes, CVec[] vecs, CTable table, Object[] keys) { + double acc = 0; + for (int i = 0; i < ITEMS; i++) { + CVec v = vecs[i & 63]; + acc += shapes[i & 7].value(i, v); + acc += table.get(keys[i & 255]); + } + return acc; + } + + public static void main(String[] args) throws InterruptedException { + // Threads must exist for TeaVM to compile anything as a coroutine. + Thread other = new Thread(() -> sink++); + other.start(); + other.join(); + + PShape[] pShapes = new PShape[9]; + CShape[] cShapes = new CShape[9]; + for (int i = 0; i < 8; i++) { + pShapes[i] = switch (i % 3) { + case 0 -> new PBox(i); + case 1 -> new PSlab(); + default -> new PStair(new PBox(i + 1)); + }; + cShapes[i] = switch (i % 3) { + case 0 -> new CBox(i); + case 1 -> new CSlab(); + default -> new CStair(new CBox(i + 1)); + }; + } + cShapes[8] = new CBlocking(); + pShapes[8] = new PExtra(); + PVec[] pVecs = new PVec[64]; + CVec[] cVecs = new CVec[64]; + for (int i = 0; i < 64; i++) { + pVecs[i] = new PVec(i, i * 0.5, i * 0.25); + cVecs[i] = new CVec(i, i * 0.5, i * 0.25); + } + PTable pTable = new PTable(); + CTable cTable = new CTable(); + Object[] pKeys = new Object[257]; + Object[] cKeys = new Object[257]; + for (int i = 0; i < 256; i++) { + pKeys[i] = (i & 1) == 0 ? new PKey(i, i >> 2) : new PKey2(i, i >> 2); + cKeys[i] = (i & 1) == 0 ? new CKey(i, i >> 2) : new CKey2(i, i >> 2); + pTable.put(pKeys[i], i); + cTable.put(cKeys[i], i); + } + cKeys[256] = new CBlockingKey(); + pKeys[256] = new PExtraKey(); + // The blocking ones reach the same call sites, as in the game, but are never called in the + // timed loops (they index & 7 and & 255). + if (suspend) { + cTable.put(cKeys[256], 0); + sink += (long) cShapes[8].value(0, cVecs[0]); + pTable.put(pKeys[256], 0); + sink += (long) pShapes[8].value(0, pVecs[0]); + } + + for (int round = 0; round < ROUNDS; round++) { + // Alternate which copy runs first, so neither gains from going second. + double a; + double b; + long plain; + long coroutine; + if ((round & 1) == 0) { + long t0 = System.nanoTime(); + a = plainWork(pShapes, pVecs, pTable, pKeys); + long t1 = System.nanoTime(); + b = coroutineWork(cShapes, cVecs, cTable, cKeys); + plain = t1 - t0; + coroutine = System.nanoTime() - t1; + } else { + long t0 = System.nanoTime(); + b = coroutineWork(cShapes, cVecs, cTable, cKeys); + long t1 = System.nanoTime(); + a = plainWork(pShapes, pVecs, pTable, pKeys); + coroutine = t1 - t0; + plain = System.nanoTime() - t1; + } + sink += (long) (a + b); + System.out.println("round " + round + ": plain " + String.format("%.2f", plain / (double) ITEMS) + + " ns/item, coroutine " + String.format("%.2f", coroutine / (double) ITEMS) + + " ns/item, ratio " + String.format("%.2f", coroutine / (double) plain) + + (a == b ? "" : " (results differ!)")); + } + System.out.println("probe passed"); + } +} diff --git a/incari-client/files/app-web/probes/DeflateProbe.java b/incari-client/files/app-web/probes/DeflateProbe.java new file mode 100644 index 0000000..125e16f --- /dev/null +++ b/incari-client/files/app-web/probes/DeflateProbe.java @@ -0,0 +1,100 @@ +import java.io.BufferedOutputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Arrays; +import java.util.Random; +import java.util.zip.DeflaterOutputStream; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; +import java.util.zip.InflaterInputStream; + +/** + * Round-trips data through the browser build's deflate and inflate streams, written the way the + * game writes chunks and NBT files (a DataOutputStream over a BufferedOutputStream over the + * compressor: single bytes, short and long runs). TeaVM's own DeflaterOutputStream failed partway + * through with zlib's "no progress" (-5), and singleplayer's saved chunks didn't read back. Half + * the trials read back the way a chunk scan does, skipping runs between reads: TeaVM's + * InflaterInputStream.skip overwrote its own compressed input. + */ +public class DeflateProbe { + private static final int TRIALS = 60; + + public static void main(String[] args) throws Exception { + Random random = new Random(26); + int failures = 0; + for (int trial = 0; trial < TRIALS; trial++) { + int size = 1 + random.nextInt(trial % 10 == 0 ? 500_000 : 60_000); + byte[] data = new byte[size]; + for (int i = 0; i < size; i++) { + data[i] = (byte) (random.nextInt(5) == 0 ? random.nextInt(256) : i % 37); + } + boolean gzip = trial % 3 == 0; + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + OutputStream compressor = gzip ? new GZIPOutputStream(bytes) : new DeflaterOutputStream(bytes); + try (DataOutputStream out = new DataOutputStream(new BufferedOutputStream(compressor))) { + int position = 0; + while (position < size) { + int kind = random.nextInt(4); + if (kind == 0) { + out.writeByte(data[position++]); + } else { + int length = Math.min(size - position, 1 + random.nextInt(kind == 1 ? 16 : 20_000)); + out.write(data, position, length); + position += length; + } + if (random.nextInt(50) == 0) { + out.flush(); + } + } + } + byte[] back; + try (InputStream in = gzip + ? new GZIPInputStream(new ByteArrayInputStream(bytes.toByteArray())) + : new InflaterInputStream(new ByteArrayInputStream(bytes.toByteArray()))) { + ByteArrayOutputStream collected = new ByteArrayOutputStream(); + byte[] buffer = new byte[1 + random.nextInt(8192)]; + boolean skipping = trial % 2 == 1; + int n; + while (true) { + if (skipping && random.nextBoolean()) { + // Skipped bytes are compared as zeros: the expected data gets the same. + int length = random.nextInt(3000); + long skipped = in.skip(length); + int start = collected.size(); + for (long k = 0; k < skipped; k++) { + collected.write(0); + } + Arrays.fill(data, Math.min(start, data.length), Math.min(start + (int) skipped, data.length), (byte) 0); + if (skipped < length) { + break; + } + continue; + } + if ((n = in.read(buffer)) <= 0) { + break; + } + collected.write(buffer, 0, n); + } + back = collected.toByteArray(); + } catch (Exception e) { + failures++; + System.out.println("trial " + trial + " (" + size + " bytes, gzip " + gzip + ") failed to read: " + e); + continue; + } + if (!Arrays.equals(back, data)) { + failures++; + System.out.println("trial " + trial + " (" + size + " bytes, gzip " + gzip + ") came back as " + back.length + + " different bytes"); + } + } + if (failures == 0) { + System.out.println(TRIALS + " deflate round trips came back whole"); + System.out.println("probe passed"); + } else { + System.out.println("probe failed: " + failures + " of " + TRIALS + " round trips"); + } + } +} diff --git a/incari-client/files/app-web/probes/DirectAllocationProbe.java b/incari-client/files/app-web/probes/DirectAllocationProbe.java new file mode 100644 index 0000000..cf714e4 --- /dev/null +++ b/incari-client/files/app-web/probes/DirectAllocationProbe.java @@ -0,0 +1,33 @@ +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.List; + +/** + * Regression probe for tools/teavm-patches' Heap fix: direct buffers of a whole number of + * 64 KiB pages, allocated once the heap's last record is in use. TeaVM grew the heap by exactly the + * request, which left the new free record a header too small, and threw OutOfMemoryError with the + * memory far from full: the game's 256x256 colour maps failed to load as soon as the heap's layout + * put an allocated record last. Keeps every buffer (half a gigabyte), so each one lands at the end + * of the heap. Prints "probe passed" when they all fit. + */ +public final class DirectAllocationProbe { + + private DirectAllocationProbe() {} + + public static void main(String[] args) { + List kept = new ArrayList<>(); + try { + // Each odd-sized buffer grows the heap by whole pages and leaves the rest of the last + // page free, a remainder 8 bytes different each time, so one of them fits exactly and + // leaves the last record allocated; the page-sized buffer after it then needs the fix. + for (int k = 0; k < 4096; k++) { + kept.add(ByteBuffer.allocateDirect(65536 - 8 * (k + 1))); + kept.add(ByteBuffer.allocateDirect(65536)); + } + } catch (OutOfMemoryError e) { + System.out.println("probe failed: OutOfMemoryError after " + kept.size() + " buffers"); + return; + } + System.out.println("probe passed"); + } +} diff --git a/incari-client/files/app-web/probes/EventLoopHopProbe.java b/incari-client/files/app-web/probes/EventLoopHopProbe.java new file mode 100644 index 0000000..dfdee4a --- /dev/null +++ b/incari-client/files/app-web/probes/EventLoopHopProbe.java @@ -0,0 +1,178 @@ +import io.netty.channel.EventLoop; +import io.netty.channel.MultiThreadIoEventLoopGroup; +import io.netty.channel.local.LocalIoHandler; +import java.util.Arrays; +import org.teavm.interop.Async; +import org.teavm.interop.AsyncCallback; +import org.teavm.jso.JSBody; +import org.teavm.jso.JSFunctor; +import org.teavm.jso.JSObject; + +/** + * Measures how long a task the page's main thread hands to a Netty local event loop (as the + * browser's connections run on) waits before it runs, when the main thread then works for a while + * and waits for the next animation frame, as the game does each frame. Prints the wait's median, + * 95th percentile and max in ms, the frame interval for scale, and "probe passed". + * + *

What it found (2026-11-15, headless Chrome, Compatible build): the task ran as soon as the main + * thread stopped for the frame, 6.2 ms after it was handed over with 6 ms of work in between, every + * time. The hop to the loop costs no frame of its own. + */ +public final class EventLoopHopProbe { + + private EventLoopHopProbe() {} + + static volatile double ranAt; + + public static void main(String[] args) throws Exception { + // As app-web's LibraryDefaults sets them. + System.setProperty("io.netty.allocator.type", "unpooled"); + System.setProperty("io.netty.noUnsafe", "true"); + System.setProperty("io.netty.leakDetection.level", "disabled"); + System.setProperty("io.netty.machineId", "00:00:00:00:00:00:00:01"); + System.setProperty("io.netty.processId", "1"); + MultiThreadIoEventLoopGroup group = new MultiThreadIoEventLoopGroup( + 1, (java.util.concurrent.ThreadFactory) r -> new Thread(r, "Probe IO"), LocalIoHandler.newFactory()); + EventLoop loop = group.next(); + loop.submit(() -> {}).sync(); + // Other threads parked as the game's are (more event loops, timers), each in LockSupport. + MultiThreadIoEventLoopGroup others = new MultiThreadIoEventLoopGroup( + 0, (java.util.concurrent.ThreadFactory) r -> new Thread(r, "Probe other"), LocalIoHandler.newFactory()); + int parked = 0; + for (io.netty.util.concurrent.EventExecutor other : others) { + other.submit(() -> {}).sync(); + parked++; + } + System.out.println("EventLoopHopProbe: " + parked + " other loops parked, " + + Runtime.getRuntime().availableProcessors() + " processors"); + int frames = 240; + for (int pass = 0; pass < 3; pass++) { + boolean slots = pass >= 1; + setSlotEnd(pass == 2 ? 1000 / 60.0 + 1 : 1000 / 60.0 - 2); + // Pass 1 adds the background pool's idle slot as the page has it: after each frame, a + // message that keeps the page busy until 2 ms before the next frame is due. + setIdleSlots(slots); + double[] waits = new double[frames]; + double[] ran = new double[frames]; + Arrays.fill(ran, -1); + for (int i = 0; i < frames; i++) { + nextFrame(); + int index = i; + double handedAt = now(); + waits[i] = handedAt; + loop.execute(() -> ran[index] = now()); + // The frame's own work: a few ms on the main thread, no yielding. + busy(6); + } + for (int i = 0; i < 30; i++) { + nextFrame(); + } + setIdleSlots(false); + for (int i = 0; i < frames; i++) { + waits[i] = ran[i] < 0 ? 1e9 : ran[i] - waits[i]; + } + Arrays.sort(waits); + System.out.println("EventLoopHopProbe: " + (pass == 0 ? "no idle slots" : pass == 1 ? "idle slots ending 2 ms before the frame" : "idle slots running 1 ms past the frame") + + ", hand-off to run, ms: median " + waits[frames / 2] + " p95 " + waits[frames * 95 / 100] + + " max " + waits[frames - 1]); + } + // As the game since its network wake: the main thread waits for a frame or a message, a + // page callback (a stand-in for the socket's onmessage) wakes it, and it hands the message + // to the loop from there before waiting again. + setIdleSlots(true); + setSlotEnd(1000 / 60.0 - 2); + double[] woken = new double[frames]; + double[] wokenRan = new double[frames]; + Arrays.fill(wokenRan, -1); + int handed = 0; + startMessages(); + while (handed < frames) { + if (!frameOrMessage()) { + int index = handed++; + woken[index] = now(); + loop.execute(() -> wokenRan[index] = now()); + } else { + busy(6); + } + } + stopMessages(); + for (int i = 0; i < 30; i++) { + nextFrame(); + } + setIdleSlots(false); + for (int i = 0; i < frames; i++) { + woken[i] = wokenRan[i] < 0 ? 1e9 : wokenRan[i] - woken[i]; + } + Arrays.sort(woken); + System.out.println("EventLoopHopProbe: handed over from a wake by a page callback, ms: median " + + woken[frames / 2] + " p95 " + woken[frames * 95 / 100] + " max " + woken[frames - 1]); + group.shutdownGracefully(); + others.shutdownGracefully(); + System.out.println("probe passed"); + } + + private static void busy(double millis) { + double end = now() + millis; + while (now() < end) { + // spin + } + } + + @Async + private static native Boolean nextFrame(); + + private static void nextFrame(AsyncCallback callback) { + requestFrame(() -> callback.complete(true)); + } + + @Async + private static native Boolean frameOrMessage(); + + private static void frameOrMessage(AsyncCallback callback) { + waitFrameOrMessage(frame -> callback.complete(frame)); + } + + @JSFunctor + interface FrameOrMessage extends JSObject { + void run(boolean frame); + } + + @JSBody( + params = "callback", + script = "var w = window.__hopWait || (window.__hopWait = { waiter: null, pending: false });" + + "w.waiter = callback; if (!w.pending) { w.pending = true; requestAnimationFrame(function() {" + + " w.pending = false; var c = w.waiter; w.waiter = null; if (c) c(true); }); }") + private static native void waitFrameOrMessage(FrameOrMessage callback); + + @JSBody( + script = "window.__hopTimer = setInterval(function() { var w = window.__hopWait;" + + " if (w && w.waiter) { var c = w.waiter; w.waiter = null; c(false); } }, 7);") + private static native void startMessages(); + + @JSBody(script = "clearInterval(window.__hopTimer);") + private static native void stopMessages(); + + @JSFunctor + interface Frame extends JSObject { + void run(); + } + + @JSBody(params = "frame", script = "requestAnimationFrame(function() { frame(); });") + private static native void requestFrame(Frame frame); + + @JSBody( + params = "on", + script = "window.__hopSlots = on; if (!on || window.__hopSlotsStarted) return; window.__hopSlotsStarted = true;" + + "var ch = new MessageChannel(); var last = 0;" + + "ch.port1.onmessage = function() { var end = last + (window.__hopSlotEnd || 14);" + + " while (performance.now() < end) {} };" + + "function frame(t) { if (window.__hopSlots) { last = t; ch.port2.postMessage(0); } requestAnimationFrame(frame); }" + + "requestAnimationFrame(frame);") + private static native void setIdleSlots(boolean on); + + @JSBody(params = "millis", script = "window.__hopSlotEnd = millis;") + private static native void setSlotEnd(double millis); + + @JSBody(script = "return performance.now();") + private static native double now(); +} diff --git a/incari-client/files/app-web/probes/EventLoopProbe.java b/incari-client/files/app-web/probes/EventLoopProbe.java new file mode 100644 index 0000000..0aa0905 --- /dev/null +++ b/incari-client/files/app-web/probes/EventLoopProbe.java @@ -0,0 +1,69 @@ +import io.netty.bootstrap.Bootstrap; +import io.netty.bootstrap.ServerBootstrap; +import io.netty.channel.Channel; +import io.netty.channel.ChannelInitializer; +import io.netty.channel.EventLoopGroup; +import io.netty.channel.MultiThreadIoEventLoopGroup; +import io.netty.channel.local.LocalAddress; +import io.netty.channel.local.LocalChannel; +import io.netty.channel.local.LocalIoHandler; +import io.netty.channel.local.LocalServerChannel; + +/** + * Whether Netty's event loop knows its own thread in the browser build: {@code inEventLoop()} from + * a task on the loop, and a channel connected through a {@code ChannelInitializer}, as singleplayer's + * server end does. Netty asserts both ({@code DefaultChannelPipeline.invokeHandlerAddedIfNeeded}), + * so a false there fails every connection with an AssertionError. + */ +public final class EventLoopProbe { + + private EventLoopProbe() {} + + public static void main(String[] args) throws Exception { + // As app-web's LibraryDefaults sets them. + System.setProperty("io.netty.allocator.type", "unpooled"); + System.setProperty("io.netty.noUnsafe", "true"); + System.setProperty("io.netty.leakDetection.level", "disabled"); + System.setProperty("io.netty.machineId", "00:00:00:00:00:00:00:01"); + System.setProperty("io.netty.processId", "1"); + boolean assertions = false; + assert assertions = true; + System.out.println("assertions enabled: " + assertions); + + EventLoopGroup group = new MultiThreadIoEventLoopGroup(1, (java.util.concurrent.ThreadFactory) r -> new Thread(r, "Probe IO"), LocalIoHandler.newFactory()); + var loop = group.next(); + System.out.println("inEventLoop from main: " + loop.inEventLoop()); + boolean[] inside = new boolean[1]; + loop.submit(() -> inside[0] = loop.inEventLoop()).sync(); + System.out.println("inEventLoop from a task: " + inside[0]); + + LocalAddress address = new LocalAddress("probe"); + new ServerBootstrap() + .group(group) + .channel(LocalServerChannel.class) + .childHandler(new ChannelInitializer() { + @Override + protected void initChannel(Channel channel) {} + }) + .bind(address) + .sync(); + try { + Channel channel = new Bootstrap() + .group(group) + .channel(LocalChannel.class) + .handler(new ChannelInitializer() { + @Override + protected void initChannel(Channel channel) { + System.out.println("initChannel ran, inEventLoop " + channel.eventLoop().inEventLoop()); + } + }) + .connect(address) + .sync() + .channel(); + System.out.println("connected: " + channel.isActive()); + System.out.println("probe passed"); + } catch (Throwable e) { + System.out.println("probe failed: " + e); + } + } +} diff --git a/incari-client/files/app-web/probes/FetchFailureProbe.java b/incari-client/files/app-web/probes/FetchFailureProbe.java new file mode 100644 index 0000000..64b4606 --- /dev/null +++ b/incari-client/files/app-web/probes/FetchFailureProbe.java @@ -0,0 +1,71 @@ +import java.io.IOException; +import org.teavm.interop.Async; +import org.teavm.interop.AsyncCallback; +import org.teavm.jso.JSBody; +import org.teavm.jso.JSFunctor; +import org.teavm.jso.JSObject; + +/** + * A failed download, reported to a suspended coroutine from a promise's rejection handler: the + * caller catches it and carries on, and the page doesn't crash. + * + *

Reporting it through {@code AsyncCallback.error} crashes the page: TeaVM's WebAssembly GC + * runtime resumes the caller, which catches the exception, and then also rethrows it out of the + * JavaScript callback, where it's an unhandled rejection. The page crashed this way on a missing + * asset index (in the screenshot harness). So {@code incari.app.web.Fetch} and + * {@code WebAudioDecoder} complete with a value that says it failed and throw in Java, as this + * probe does; set {@link #USE_ERROR} to see TeaVM's behavior. + */ +public final class FetchFailureProbe { + + /** True to report the failure through {@code AsyncCallback.error}, which crashes the page. */ + private static final boolean USE_ERROR = false; + + @JSFunctor + interface Failed extends JSObject { + void failed(String message); + } + + @JSBody( + params = {"failed"}, + script = "Promise.reject(new Error('HTTP 404')).then(null, function(e) { failed(String(e)); });") + private static native void start(Failed failed); + + @Async + private static native String fetch() throws IOException; + + private static void fetch(AsyncCallback callback) { + start(message -> { + if (USE_ERROR) { + callback.error(new IOException("Couldn't fetch: " + message)); + } else { + callback.complete("failed: " + message); + } + }); + } + + private static void fetchOrThrow() throws IOException { + String outcome = fetch(); + if (outcome.startsWith("failed: ")) { + throw new IOException("Couldn't fetch: " + outcome.substring("failed: ".length())); + } + } + + public static void main(String[] args) throws InterruptedException { + try { + fetchOrThrow(); + System.out.println("probe failed: no exception"); + return; + } catch (IOException e) { + System.out.println("caught " + e.getMessage()); + } + try { + fetchOrThrow(); + } catch (IOException e) { + System.out.println("caught again " + e.getMessage()); + } + // A crash would come as the page's unhandled rejection, after the callback returns. + Thread.sleep(2000); + System.out.println("probe passed"); + } +} diff --git a/incari-client/files/app-web/probes/FileReadProbe.java b/incari-client/files/app-web/probes/FileReadProbe.java new file mode 100644 index 0000000..2a8a43e --- /dev/null +++ b/incari-client/files/app-web/probes/FileReadProbe.java @@ -0,0 +1,44 @@ +import java.io.DataInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.RandomAccessFile; + +/** + * Regression probe for web-classlib's FileInputStreamAdditions, and for RandomAccessFile's own + * read() since TeaVM 0.16.0: TeaVM's single-byte {@code read()} returned bytes signed, so a byte of + * 0x80 or more read as the end of the file, and the game's {@code NbtIo.read(Path)} (a + * DataInputStream straight over the file) lost {@code servers.dat}. Prints "probe passed" when every + * byte reads back unsigned. + */ +public final class FileReadProbe { + + private FileReadProbe() {} + + public static void main(String[] args) throws IOException { + File file = new File("/probe.dat"); + try (FileOutputStream out = new FileOutputStream(file)) { + out.write(new byte[] {0x0A, (byte) 0xC8, (byte) 0xFF, 0x00, 0x01}); + } + StringBuilder problems = new StringBuilder(); + try (DataInputStream in = new DataInputStream(new FileInputStream(file))) { + int first = in.readUnsignedByte(); + int second = in.readUnsignedShort(); + short third = in.readShort(); + if (first != 0x0A || second != 0xC8FF || third != 1) { + problems.append(" stream: ").append(first).append(',').append(second).append(',').append(third); + } + if (in.read() != -1) { + problems.append(" stream end"); + } + } + try (RandomAccessFile raf = new RandomAccessFile(file, "r")) { + raf.seek(1); + if (raf.read() != 0xC8 || raf.readUnsignedByte() != 0xFF) { + problems.append(" random access"); + } + } + System.out.println(problems.isEmpty() ? "probe passed" : "probe failed:" + problems); + } +} diff --git a/incari-client/files/app-web/probes/ImmutableCollectionsProbe.java b/incari-client/files/app-web/probes/ImmutableCollectionsProbe.java new file mode 100644 index 0000000..aa5f22e --- /dev/null +++ b/incari-client/files/app-web/probes/ImmutableCollectionsProbe.java @@ -0,0 +1,108 @@ +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Regression probe for tools/teavm-patches' TTemplateCollections hashing (ADR 0034): the sets and + * maps {@code Set.of}, {@code Set.copyOf}, {@code Map.of} and {@code Map.ofEntries} make for more + * than two elements. Lookups now probe a table of indices; this checks they answer as a + * {@code HashSet} or {@code HashMap} would, for hits and misses, with colliding hashes, for every + * size up to 40, and that duplicates still throw (of) or are dropped (copyOf). Prints + * "probe passed" when every answer agrees. + */ +public final class ImmutableCollectionsProbe { + + private ImmutableCollectionsProbe() {} + + /** A key whose hash is chosen, so keys can collide. */ + private record Key(int id, int hash) { + @Override + public boolean equals(Object o) { + return o instanceof Key k && k.id == id; + } + + @Override + public int hashCode() { + return hash; + } + } + + public static void main(String[] args) { + String failure = null; + for (int size = 0; size <= 40 && failure == null; size++) { + for (int spread = 1; spread <= 3 && failure == null; spread++) { + failure = check(size, spread); + } + } + if (failure == null) { + failure = duplicates(); + } + System.out.println(failure == null ? "probe passed" : "probe failed: " + failure); + } + + /** Keys 0..size-1 whose hashes are id / spread (several share one when spread > 1). */ + private static String check(int size, int spread) { + List keys = new ArrayList<>(); + for (int i = 0; i < size; i++) { + keys.add(new Key(i, i / spread)); + } + Set copied = Set.copyOf(keys); + Set of = Set.of(keys.toArray(new Key[0])); + @SuppressWarnings("unchecked") + Map.Entry[] entries = new Map.Entry[size]; + for (int i = 0; i < size; i++) { + entries[i] = Map.entry(keys.get(i), i * 10); + } + Map map = Map.ofEntries(entries); + Map mapCopy = Map.copyOf(new HashMap<>(map)); + Set reference = new HashSet<>(keys); + if (copied.size() != size || of.size() != size || map.size() != size || mapCopy.size() != size) { + return "size " + size + " spread " + spread + ": sizes " + copied.size() + ", " + of.size() + ", " + map.size(); + } + if (!new HashSet<>(copied).equals(reference) || !new HashSet<>(of).equals(reference) + || !new HashSet<>(map.keySet()).equals(reference)) { + return "size " + size + " spread " + spread + ": iteration"; + } + // Hits, and misses: ids past the end, some with a hash a present key has. + for (int id = 0; id < size + 20; id++) { + Key probe = new Key(id, id / spread); + boolean present = id < size; + Integer value = present ? id * 10 : null; + if (copied.contains(probe) != present || of.contains(probe) != present + || map.containsKey(probe) != present || mapCopy.containsKey(probe) != present + || !java.util.Objects.equals(map.get(probe), value) + || !java.util.Objects.equals(mapCopy.get(probe), value) + || map.entrySet().contains(Map.entry(probe, id * 10)) != present + || (present && map.entrySet().contains(Map.entry(probe, -1)))) { + return "size " + size + " spread " + spread + ": lookup of " + id; + } + } + if (copied.contains("not a key") || map.containsKey("not a key") || map.get("not a key") != null) { + return "size " + size + ": a key of another type"; + } + return null; + } + + private static String duplicates() { + try { + Set.of(new Key(1, 0), new Key(2, 0), new Key(1, 0)); + return "Set.of accepted a duplicate"; + } catch (IllegalArgumentException expected) { + // As the JDK's. + } + try { + Map.of(new Key(1, 0), 1, new Key(2, 0), 2, new Key(1, 0), 3); + return "Map.of accepted a duplicate key"; + } catch (IllegalArgumentException expected) { + // As the JDK's. + } + Set copied = Set.copyOf(List.of(new Key(1, 0), new Key(2, 0), new Key(1, 0), new Key(3, 7))); + if (copied.size() != 3 || !copied.contains(new Key(3, 7)) || copied.contains(new Key(4, 7))) { + return "Set.copyOf kept " + copied.size() + " of a list with a duplicate"; + } + return null; + } +} diff --git a/incari-client/files/app-web/probes/InflatePacketProbe.java b/incari-client/files/app-web/probes/InflatePacketProbe.java new file mode 100644 index 0000000..4c45bfd --- /dev/null +++ b/incari-client/files/app-web/probes/InflatePacketProbe.java @@ -0,0 +1,135 @@ +import java.nio.ByteBuffer; +import java.util.Random; +import java.util.zip.DataFormatException; +import java.util.zip.Deflater; +import java.util.zip.Inflater; + +/** + * Measures inflating packets the way the game's decoder does (one inflater, input and output as + * buffers, a reset after each) in the browser build, against the route before web-classlib's + * Inflater: a new zlib stream per packet (what TeaVM's reset did) and new input and output arrays + * per call (InflaterAdditions). A server's mix of sizes over the compression threshold. Prints + * microseconds per packet and "probe passed" when both routes read the packets back whole. + * + *

What it found (2026-11-15, headless Chrome, Compatible build, best of six alternated + * rounds): inflating, 14.2 us a packet with a new stream and arrays each, 11.2 us reset in place; + * deflating, 74.5 us and 60.4 us. + */ +public final class InflatePacketProbe { + + private InflatePacketProbe() {} + + public static void main(String[] args) throws DataFormatException { + Random random = new Random(26); + int packets = 2000; + byte[][] plain = new byte[packets][]; + byte[][] compressed = new byte[packets][]; + Deflater deflater = new Deflater(); + byte[] buffer = new byte[8192]; + for (int i = 0; i < packets; i++) { + // Mostly entity and block updates just over the threshold, some chunks. + int size = i % 25 == 0 ? 20_000 + random.nextInt(60_000) : 256 + random.nextInt(1500); + byte[] data = new byte[size]; + for (int j = 0; j < size; j++) { + data[j] = (byte) ((j / 37) % 4 == 0 ? random.nextInt(256) : (j & 7)); + } + plain[i] = data; + deflater.setInput(data); + deflater.finish(); + java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream(); + while (!deflater.finished()) { + out.write(buffer, 0, deflater.deflate(buffer)); + } + deflater.reset(); + compressed[i] = out.toByteArray(); + } + boolean same = true; + for (int round = 0; round < 2; round++) { + same &= asBefore(plain, compressed) && asNow(plain, compressed); + } + // Alternated, best of each, so neither route gains from running second. + double before = Double.MAX_VALUE; + double after = Double.MAX_VALUE; + double deflateNew = Double.MAX_VALUE; + double deflateReset = Double.MAX_VALUE; + for (int round = 0; round < 6; round++) { + double start = now(); + same &= asBefore(plain, compressed); + before = Math.min(before, (now() - start) * 1000 / packets); + start = now(); + same &= asNow(plain, compressed); + after = Math.min(after, (now() - start) * 1000 / packets); + start = now(); + deflateEach(plain, true); + deflateNew = Math.min(deflateNew, (now() - start) * 1000 / packets); + start = now(); + deflateEach(plain, false); + deflateReset = Math.min(deflateReset, (now() - start) * 1000 / packets); + } + System.out.println("InflatePacketProbe: inflate per packet: a new stream and arrays each " + before + + " us, reset in place " + after + " us; deflate per packet: a new stream each " + deflateNew + + " us, reset in place " + deflateReset + " us"); + System.out.println(same ? "probe passed" : "probe failed: a packet didn't read back"); + } + + /** As before: a new stream per packet, input and output copied through new arrays. */ + private static boolean asBefore(byte[][] plain, byte[][] compressed) throws DataFormatException { + boolean same = true; + for (int i = 0; i < plain.length; i++) { + Inflater inflater = new Inflater(); + ByteBuffer input = ByteBuffer.wrap(compressed[i]); + byte[] in = new byte[input.remaining()]; + input.get(in); + inflater.setInput(in); + ByteBuffer output = ByteBuffer.allocateDirect(plain[i].length); + byte[] out = new byte[output.remaining()]; + int written = inflater.inflate(out); + output.put(out, 0, written); + inflater.end(); + same &= written == plain[i].length && check(output, plain[i]); + } + return same; + } + + /** As the game's decoder now runs: one inflater, the buffer forms, a reset after each. */ + private static boolean asNow(byte[][] plain, byte[][] compressed) throws DataFormatException { + boolean same = true; + Inflater inflater = new Inflater(); + for (int i = 0; i < plain.length; i++) { + inflater.setInput(ByteBuffer.wrap(compressed[i])); + ByteBuffer output = ByteBuffer.allocateDirect(plain[i].length); + int written = inflater.inflate(output); + inflater.reset(); + same &= written == plain[i].length && check(output, plain[i]); + } + inflater.end(); + return same; + } + + /** As the game's encoder: input array, a kept output array, then a reset (or a new stream, as before). */ + private static void deflateEach(byte[][] plain, boolean newEach) { + byte[] buffer = new byte[8192]; + Deflater deflater = new Deflater(); + for (byte[] data : plain) { + if (newEach) { + deflater.end(); + deflater = new Deflater(); + } + deflater.setInput(data, 0, data.length); + deflater.finish(); + while (!deflater.finished()) { + deflater.deflate(buffer); + } + deflater.reset(); + } + deflater.end(); + } + + private static boolean check(ByteBuffer output, byte[] expected) { + int n = expected.length; + return output.get(0) == expected[0] && output.get(n / 2) == expected[n / 2] && output.get(n - 1) == expected[n - 1]; + } + + @org.teavm.jso.JSBody(script = "return performance.now();") + private static native double now(); +} diff --git a/incari-client/files/app-web/probes/InitOrderProbe.java b/incari-client/files/app-web/probes/InitOrderProbe.java new file mode 100644 index 0000000..5ea027a --- /dev/null +++ b/incari-client/files/app-web/probes/InitOrderProbe.java @@ -0,0 +1,56 @@ +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Regression probe for tools/teavm-patches' ClassInitializerInsertionTransformer fix: a + * class's static initializer runs after its superclass's (JLS 12.4.2). TeaVM ran a subclass's first + * when the first use was {@code new Sub()}. The game numbers entity data by class this way + * ({@code SynchedEntityData.defineId} counts on from the superclass's last id), so creating the + * player on joining a server failed with "Duplicate id value for 0!". Prints "probe passed" when + * ids count up from the root class, as on the JVM. + */ +public final class InitOrderProbe { + + static final List ORDER = new ArrayList<>(); + static final Map, Integer> LAST_IDS = new HashMap<>(); + + private InitOrderProbe() {} + + /** The next id for {@code type}, after its own or its nearest superclass's last one. */ + static int define(Class type) { + Integer last = LAST_IDS.get(type); + Class current = type; + while (last == null && (current = current.getSuperclass()) != Object.class) { + last = LAST_IDS.get(current); + } + int id = last == null ? 0 : last + 1; + LAST_IDS.put(type, id); + ORDER.add(type.getSimpleName() + "=" + id); + return id; + } + + static class Root { + static final int FIRST = define(Root.class); + static final int SECOND = define(Root.class); + } + + static class Middle extends Root { + static final int THIRD = define(Middle.class); + } + + /** No initializer of its own between two classes that have one. */ + static class Plain extends Middle {} + + static final class Leaf extends Plain { + static final int FOURTH = define(Leaf.class); + } + + public static void main(String[] args) { + new Leaf(); + String expected = "[Root=0, Root=1, Middle=2, Leaf=3]"; + String actual = ORDER.toString(); + System.out.println(actual.equals(expected) ? "probe passed" : "probe failed: " + actual); + } +} diff --git a/incari-client/files/app-web/probes/InterruptedWaitProbe.java b/incari-client/files/app-web/probes/InterruptedWaitProbe.java new file mode 100644 index 0000000..2354826 --- /dev/null +++ b/incari-client/files/app-web/probes/InterruptedWaitProbe.java @@ -0,0 +1,52 @@ +import java.util.concurrent.locks.LockSupport; + +/** + * Regression probe for tools/teavm-patches' TObject fix: a thread interrupted in + * {@code wait()} holds the monitor again when the InterruptedException arrives, so it leaves its + * {@code synchronized} block normally. TeaVM threw without the monitor, and the block's exit threw + * IllegalMonitorStateException: the game's sound thread, parked through web-classlib's + * {@code LockSupport} and interrupted when the sound engine stops (joining a world), crashed the + * game this way. Prints "probe passed" when both a plain wait and a park end cleanly. + */ +public final class InterruptedWaitProbe { + + private static final Object LOCK = new Object(); + private static volatile String waitResult = "not run"; + private static volatile String parkResult = "not run"; + + private InterruptedWaitProbe() {} + + public static void main(String[] args) throws InterruptedException { + Thread waiter = new Thread(() -> { + try { + synchronized (LOCK) { + try { + LOCK.wait(); + waitResult = "woke without an interrupt"; + } catch (InterruptedException e) { + waitResult = Thread.holdsLock(LOCK) ? "ok" : "interrupted without the monitor"; + } + } + } catch (IllegalMonitorStateException e) { + waitResult = "IllegalMonitorStateException leaving the block"; + } + }); + Thread parker = new Thread(() -> { + try { + LockSupport.park(); + parkResult = Thread.currentThread().isInterrupted() ? "ok" : "returned without the interrupt"; + } catch (IllegalMonitorStateException e) { + parkResult = "IllegalMonitorStateException in park"; + } + }); + waiter.start(); + parker.start(); + Thread.sleep(50); + waiter.interrupt(); + parker.interrupt(); + waiter.join(); + parker.join(); + boolean passed = waitResult.equals("ok") && parkResult.equals("ok"); + System.out.println(passed ? "probe passed" : "probe failed: wait " + waitResult + ", park " + parkResult); + } +} diff --git a/incari-client/files/app-web/probes/JspiProbe.java b/incari-client/files/app-web/probes/JspiProbe.java new file mode 100644 index 0000000..e8f1854 --- /dev/null +++ b/incari-client/files/app-web/probes/JspiProbe.java @@ -0,0 +1,124 @@ +/** + * Checks that Java threads behave the same in the Fast build (fibers on JSPI, {@code -Pteavm.fast}) + * as with TeaVM's coroutines in the Compatible build: sleeping, waiting and notifying, joining, + * exceptions thrown after a thread resumed and caught across the frames that waited, and + * {@code Thread.currentThread()} after each wait. Times a wait/notify ping-pong between two threads, the cost of a thread switch. Prints + * "probe passed" or "probe failed: ...". Run it in both builds. + */ +public final class JspiProbe { + + private static final int PING_PONGS = 2000; + + static final Object LOCK = new Object(); + static int turn; + static volatile String failure; + + static void check(boolean condition, String what) { + if (!condition && failure == null) { + failure = what; + } + } + + static int sleepThenThrow(int depth) throws InterruptedException { + if (depth == 0) { + Thread.sleep(1); + throw new IllegalStateException("after the sleep"); + } + return sleepThenThrow(depth - 1) + 1; + } + + public static void main(String[] args) throws InterruptedException { + Thread main = Thread.currentThread(); + + long t0 = System.currentTimeMillis(); + Thread.sleep(20); + long slept = System.currentTimeMillis() - t0; + check(slept >= 15, "slept only " + slept + " ms"); + check(Thread.currentThread() == main, "the main thread changed over a sleep"); + + try { + sleepThenThrow(20); + check(false, "no exception after the sleep"); + } catch (IllegalStateException e) { + check("after the sleep".equals(e.getMessage()), "wrong exception: " + e); + } + check(Thread.currentThread() == main, "the main thread changed over a throw"); + + // Three threads, each sleeping and counting, joined. + int[] counts = new int[3]; + Thread[] workers = new Thread[3]; + for (int i = 0; i < 3; i++) { + int index = i; + workers[i] = new Thread(() -> { + Thread self = Thread.currentThread(); + for (int n = 0; n < 5; n++) { + try { + Thread.sleep(1 + index); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + check(Thread.currentThread() == self, "worker " + index + " resumed as another thread"); + counts[index]++; + } + }, "worker-" + i); + workers[i].start(); + } + for (Thread worker : workers) { + worker.join(); + } + check(Thread.currentThread() == main, "the main thread changed over joins"); + for (int i = 0; i < 3; i++) { + check(counts[i] == 5, "worker " + i + " counted " + counts[i]); + } + + // Ping-pong: two threads hand a turn back and forth through wait/notify. + Thread pong = new Thread(() -> { + for (int n = 0; n < PING_PONGS; n++) { + synchronized (LOCK) { + while (turn != 1) { + try { + LOCK.wait(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } + turn = 0; + LOCK.notifyAll(); + } + } + }, "pong"); + pong.start(); + long p0 = System.nanoTime(); + for (int n = 0; n < PING_PONGS; n++) { + synchronized (LOCK) { + turn = 1; + LOCK.notifyAll(); + while (turn != 0) { + LOCK.wait(); + } + } + } + long p1 = System.nanoTime(); + pong.join(); + check(Thread.currentThread() == main, "the main thread changed over the ping-pong"); + System.out.println("ping-pong: " + String.format("%.1f", (p1 - p0) / 1000.0 / PING_PONGS / 2) + + " us a switch over " + PING_PONGS + " round trips"); + + // An uncaught exception in a thread goes to its handler, and the program goes on. + Throwable[] uncaught = new Throwable[1]; + Thread thrower = new Thread(() -> { + try { + Thread.sleep(1); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + throw new IllegalArgumentException("uncaught"); + }); + thrower.setUncaughtExceptionHandler((t, e) -> uncaught[0] = e); + thrower.start(); + thrower.join(); + check(uncaught[0] instanceof IllegalArgumentException, "uncaught exception not handled: " + uncaught[0]); + + System.out.println(failure == null ? "probe passed" : "probe failed: " + failure); + } +} diff --git a/incari-client/files/app-web/probes/MathProbe.java b/incari-client/files/app-web/probes/MathProbe.java new file mode 100644 index 0000000..5f243ba --- /dev/null +++ b/incari-client/files/app-web/probes/MathProbe.java @@ -0,0 +1,60 @@ +/** + * Probe for tools/webbuild's {@code MathIntrinsics}: {@code Math.floor}, {@code ceil} and + * {@code sqrt} compiled to WebAssembly's own instructions give Java's answers, signed zeros, + * infinities and NaN included. Prints "probe passed" when every case matches its bits (any NaN + * matches any NaN). + */ +public final class MathProbe { + + private MathProbe() {} + + private static final double[] INPUTS = { + 0.0, -0.0, 0.5, -0.5, 1.5, -1.5, 2.0, -2.0, 1e300, -1e300, 4503599627370495.5, -4503599627370495.5, + Double.MIN_VALUE, -Double.MIN_VALUE, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NaN, 2.0, + 1e-300, 0.1 + }; + + // Java's answers for INPUTS, in order: floor, ceil, sqrt. + private static final double[][] EXPECTED = { + {0.0, 0.0, 0.0}, + {-0.0, -0.0, -0.0}, + {0.0, 1.0, 0.7071067811865476}, + {-1.0, -0.0, Double.NaN}, + {1.0, 2.0, 1.224744871391589}, + {-2.0, -1.0, Double.NaN}, + {2.0, 2.0, 1.4142135623730951}, + {-2.0, -2.0, Double.NaN}, + {1e300, 1e300, 1e150}, + {-1e300, -1e300, Double.NaN}, + {4503599627370495.0, 4503599627370496.0, 6.710886399999999e7}, + {-4503599627370496.0, -4503599627370495.0, Double.NaN}, + {0.0, 1.0, 2.2227587494850775e-162}, + {-1.0, -0.0, Double.NaN}, + {Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY}, + {Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NaN}, + {Double.NaN, Double.NaN, Double.NaN}, + {2.0, 2.0, 1.4142135623730951}, + {0.0, 1.0, 1e-150}, + {0.0, 1.0, 0.31622776601683794}, + }; + + public static void main(String[] args) { + int failures = 0; + for (int i = 0; i < INPUTS.length; i++) { + double x = INPUTS[i]; + double[] got = {Math.floor(x), Math.ceil(x), Math.sqrt(x)}; + for (int k = 0; k < 3; k++) { + if (!same(got[k], EXPECTED[i][k])) { + failures++; + System.out.println("probe mismatch: " + new String[] {"floor", "ceil", "sqrt"}[k] + "(" + x + + ") = " + got[k] + ", expected " + EXPECTED[i][k]); + } + } + } + System.out.println(failures == 0 ? "probe passed" : "probe failed: " + failures + " mismatches"); + } + + private static boolean same(double a, double b) { + return Double.isNaN(a) ? Double.isNaN(b) : Double.doubleToRawLongBits(a) == Double.doubleToRawLongBits(b); + } +} diff --git a/incari-client/files/app-web/probes/MessageTypeProbe.java b/incari-client/files/app-web/probes/MessageTypeProbe.java new file mode 100644 index 0000000..a0e5661 --- /dev/null +++ b/incari-client/files/app-web/probes/MessageTypeProbe.java @@ -0,0 +1,33 @@ +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.MessageToByteEncoder; + +/** + * Regression probe for tools/webbuild's TypeCaptures: a Netty encoder decides which + * messages it takes from its superclass's type argument, read by reflection. The browser build + * kept no generic superclasses for Netty's handlers, so every encoder took every message: the + * game's {@code PacketEncoder} ({@code MessageToByteEncoder>}) was handed its pipeline's + * configuration messages and failed with a ClassCastException. Prints "probe passed" when an + * encoder of the same shape takes its own messages and passes others by. + */ +public final class MessageTypeProbe { + + /** A generic message, like the game's {@code Packet}. */ + interface Box {} + + static final class StringBox implements Box {} + + static final class BoxEncoder extends MessageToByteEncoder> { + @Override + protected void encode(ChannelHandlerContext ctx, Box message, ByteBuf out) {} + } + + private MessageTypeProbe() {} + + public static void main(String[] args) throws Exception { + BoxEncoder encoder = new BoxEncoder<>(); + boolean takesBox = encoder.acceptOutboundMessage(new StringBox()); + boolean takesOther = encoder.acceptOutboundMessage("not a box"); + System.out.println(takesBox && !takesOther ? "probe passed" : "probe failed: " + takesBox + ", " + takesOther); + } +} diff --git a/incari-client/files/app-web/probes/ModuleProbe.java b/incari-client/files/app-web/probes/ModuleProbe.java new file mode 100644 index 0000000..146033c --- /dev/null +++ b/incari-client/files/app-web/probes/ModuleProbe.java @@ -0,0 +1,15 @@ +/** + * Regression probe for web-classlib's {@code Module} and {@code ModuleLayer}: the check the + * game's {@code JvmProfiler} makes in its static initializer, which the first packet sent reaches. + * Without them the survey's rules turned the calls into nulls and the initializer threw, so the + * handshake never left. Prints "probe passed" when the check runs and finds no {@code jdk.jfr}. + */ +public final class ModuleProbe { + + private ModuleProbe() {} + + public static void main(String[] args) { + boolean jfr = Runtime.class.getModule().getLayer().findModule("jdk.jfr").isPresent(); + System.out.println(!jfr ? "probe passed" : "probe failed: jdk.jfr found"); + } +} diff --git a/incari-client/files/app-web/probes/PacketHandoffProbe.java b/incari-client/files/app-web/probes/PacketHandoffProbe.java new file mode 100644 index 0000000..03ce2e6 --- /dev/null +++ b/incari-client/files/app-web/probes/PacketHandoffProbe.java @@ -0,0 +1,246 @@ +import java.util.ArrayDeque; +import java.util.concurrent.ConcurrentLinkedQueue; + +/** + * Measures what handing a packet to the game's thread costs in the browser build (the lead in ADR + * 0032's "Not done"). The game decodes each packet on the network's thread and calls its handler + * there; the handler's first line ({@code PacketUtils.ensureRunningOnSameThread}) queues the packet + * for the game's thread and throws a shared, stack-less {@code RunningOnDifferentThreadException}, + * which {@code Connection.channelRead0} catches. In the page's profiles that function's own time was + * 2.5% of combat's samples, and the profile can't say whether it's the throw or the queueing. + * + *

Times, per packet, each part on its own, through three calls as in the game (the handoff's + * check, the packet's {@code handle}, the connection's dispatch), the calls made through + * interfaces with two implementations each so they stay calls: the call path alone; the thread + * check; the queueing (an {@code ArrayDeque}, and a {@code ConcurrentLinkedQueue} as the game's + * {@code PacketProcessor} has); the throw and catch; and all of it, as the game does it. Each also + * through frames compiled as coroutines (most of the game's packet handlers are: a call that could + * suspend, never made); from the stack's bottom and 30 calls up; on the page's main thread, in a + * thread that slept first, and in one that never suspended. Prints the figures and "probe passed". + * + *

What it found (2026-10-03, Chrome on the desktop, development and release builds alike): the + * throw and catch is most of the handoff, 65 to 100 ns on the page's main thread, and 640 to + * 860 ns on any other thread, slept or not, against 5 to 15 ns for the calls and 20 to 30 ns for + * either queue. The stack's depth doesn't matter. The game's network runs on another thread, so + * every packet pays the dear throw. + */ +public final class PacketHandoffProbe { + + private static final int PACKETS = 50_000; + private static final int ROUNDS = 5; + + /** As the game's exception: shared, no stack trace. */ + static final class Handoff extends RuntimeException { + static final Handoff INSTANCE = new Handoff(); + + private Handoff() { + setStackTrace(new StackTraceElement[0]); + } + + @Override + public synchronized Throwable fillInStackTrace() { + setStackTrace(new StackTraceElement[0]); + return this; + } + } + + record Queued(Object listener, Object packet) {} + + /** + * What the handoff does: 0 nothing, 1 check, 2 queue (an ArrayDeque), 3 queue (a + * ConcurrentLinkedQueue, as the game's PacketProcessor), 4 throw, 5 check + queue + throw as the + * game (the concurrent queue). + */ + static int mode; + + /** Never true; makes the coroutine variants' methods able to suspend. */ + static volatile boolean suspend; + + static final ArrayDeque QUEUE = new ArrayDeque<>(); + static final ConcurrentLinkedQueue CONCURRENT = new ConcurrentLinkedQueue<>(); + static Thread gameThread; + static volatile long sink; + + interface Handler { + void handle(Object packet); + } + + interface Dispatch { + void read(Handler handler, Object packet); + } + + static void handoff(Object listener, Object packet) { + switch (mode) { + case 1 -> { + if (Thread.currentThread() == gameThread) { + sink++; + } + } + case 2 -> QUEUE.add(new Queued(listener, packet)); + case 3 -> CONCURRENT.add(new Queued(listener, packet)); + case 4 -> throw Handoff.INSTANCE; + case 5 -> { + if (Thread.currentThread() != gameThread) { + CONCURRENT.add(new Queued(listener, packet)); + throw Handoff.INSTANCE; + } + } + default -> {} + } + } + + static void maybeSuspend() { + if (suspend) { + Thread.yield(); + } + } + + static final class PlainHandler implements Handler { + @Override + public void handle(Object packet) { + handoff(this, packet); + sink += packet.hashCode(); + } + } + + static final class OtherHandler implements Handler { + @Override + public void handle(Object packet) { + sink -= packet.hashCode(); + } + } + + static final class CoroutineHandler implements Handler { + @Override + public void handle(Object packet) { + maybeSuspend(); + handoff(this, packet); + maybeSuspend(); + sink += packet.hashCode(); + } + } + + static final class PlainDispatch implements Dispatch { + @Override + public void read(Handler handler, Object packet) { + try { + handler.handle(packet); + } catch (Handoff e) { + sink++; + } + } + } + + static final class OtherDispatch implements Dispatch { + @Override + public void read(Handler handler, Object packet) { + sink--; + } + } + + static final class CoroutineDispatch implements Dispatch { + @Override + public void read(Handler handler, Object packet) { + maybeSuspend(); + try { + handler.handle(packet); + } catch (Handoff e) { + sink++; + } + maybeSuspend(); + } + } + + private PacketHandoffProbe() {} + + public static void main(String[] args) { + // The game's thread is another: the check fails, as on the network's thread. + gameThread = new Thread(() -> {}); + StringBuilder report = new StringBuilder("PacketHandoffProbe, ns a packet (best of " + ROUNDS + "):\n"); + // From the stack's bottom, and from deep in it, as the game's network pipeline is. + for (int depth : new int[] {0, 30}) { + report.append(deep(depth, depth)); + } + // Depth -1: a thread that slept first; -2: a thread that never suspended. + // And in a thread that has suspended and resumed, as the network's event loop has: it + // waits for each message. + StringBuilder resumed = new StringBuilder(); + Thread network = new Thread(() -> { + try { + Thread.sleep(5); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + resumed.append(measure(-1)); + }); + network.start(); + try { + network.join(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + report.append(resumed); + // A thread that never suspended, to tell the thread from the suspension. + StringBuilder fresh = new StringBuilder(); + Thread plain = new Thread(() -> fresh.append(measure(-2))); + plain.start(); + try { + plain.join(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + report.append(fresh); + System.out.println(report); + System.out.println("probe passed"); + } + + /** Measures {@code depth} calls down the stack. */ + static String deep(int remaining, int depth) { + if (remaining > 0) { + String result = deep(remaining - 1, depth); + sink += result.length(); + return result; + } + return measure(depth); + } + + static String measure(int depth) { + Object packet = new Object(); + Handler[] handlers = {new PlainHandler(), new OtherHandler(), new CoroutineHandler()}; + Dispatch[] dispatches = {new PlainDispatch(), new OtherDispatch(), new CoroutineDispatch()}; + String[] modes = {"call path only", "thread check", "ArrayDeque add", "concurrent add", "throw and catch", "as the game (all)"}; + StringBuilder report = new StringBuilder(); + for (int variant = 0; variant < 2; variant++) { + Handler handler = handlers[variant == 0 ? 0 : 2]; + Dispatch dispatch = dispatches[variant == 0 ? 0 : 2]; + // The other implementations, called once, so neither interface has a single target. + dispatches[1].read(handlers[1], packet); + handlers[1].handle(packet); + for (int m = 0; m < modes.length; m++) { + mode = m; + double best = Double.MAX_VALUE; + for (int round = 0; round < ROUNDS + 1; round++) { + QUEUE.clear(); + CONCURRENT.clear(); + long start = System.nanoTime(); + for (int i = 0; i < PACKETS; i++) { + dispatch.read(handler, packet); + if ((i & 1023) == 0) { + QUEUE.clear(); + // As the game's thread drains it each frame. + while (CONCURRENT.poll() != null) {} + } + } + double ns = (System.nanoTime() - start) / (double) PACKETS; + if (round > 0) { + best = Math.min(best, ns); + } + } + report.append(String.format( + " depth %3d %-10s %-18s %8.1f%n", + depth, variant == 0 ? "plain" : "coroutine", modes[m], best)); + } + } + return report.toString(); + } +} diff --git a/incari-client/files/app-web/probes/README.md b/incari-client/files/app-web/probes/README.md new file mode 100644 index 0000000..72270a9 --- /dev/null +++ b/incari-client/files/app-web/probes/README.md @@ -0,0 +1,49 @@ +# Probes + +Small programs compiled alone with TeaVM against the browser build's class library and run in +headless Chromium, in seconds rather than the full build's ten minutes (`app-web/README.md`, +Experiments). Regression probes guard a fix in `tools/teavm-patches`, `tools/webbuild` or +`web-classlib` and print "probe passed". Measurements print the cost an ADR relied on; checks confirm a behaviour the build depends on. + +```sh +app-web/probes/run.sh [Gradle options] # for example -Pteavm.fast, -Pbrowser.gpu=webgpu +``` + +| Probe | Kind | What it checks | +| --- | --- | --- | +| `ArrayDequeProbe` | Regression | tools/teavm-patches' TArrayDeque fix | +| `ArrayInstanceOfProbe` | Regression | Via's StructuredItemRewriter | +| `ByteCopyProbe` | Measurement | How bytes cross between Java arrays and JavaScript buffers | +| `ChannelClassProbe` | Check | `Bootstrap.channel(Class)` throws for a channel class ReflectionDeclarations doesn't declare | +| `CoroutineCostProbe` | Measurement | What TeaVM's coroutine transformation costs ordinary code (ADR 0036) | +| `DeflateProbe` | Check | The build's deflate and inflate streams, used as the game writes chunks and NBT | +| `DirectAllocationProbe` | Regression | Heap growth (a tools/teavm-patches fix until TeaVM 0.16.0 had it) | +| `EventLoopProbe` | Regression | Netty's event loop and a channel's pipeline setup under TeaVM (its assertions hold; the catalog's Netty must be the game's) | +| `EventLoopHopProbe` | Measurement | How long a task handed to a Netty local event loop waits when the main thread then ends its frame | +| `FetchFailureProbe` | Check | A failed download reported to a suspended coroutine is caught, and the page doesn't crash | +| `FileReadProbe` | Regression | web-classlib's FileInputStreamAdditions, and `RandomAccessFile.read` (fixed in TeaVM 0.16.0) | +| `ImmutableCollectionsProbe` | Regression | tools/teavm-patches' TTemplateCollections hashing (ADR 0034) | +| `InflatePacketProbe` | Measurement | Inflating and deflating packets with a reset in place, against a new zlib stream each (ADR 0075) | +| `InitOrderProbe` | Regression | tools/teavm-patches' ClassInitializerInsertionTransformer fix | +| `InterruptedWaitProbe` | Regression | tools/teavm-patches' TObject fix | +| `JspiProbe` | Check | Java threads behave the same in the Fast build (JSPI) as in the Compatible build | +| `MathProbe` | Check | tools/webbuild's `MathIntrinsics`: `Math.floor`, `ceil` and `sqrt` as WebAssembly instructions | +| `MessageTypeProbe` | Regression | tools/webbuild's TypeCaptures | +| `ModuleProbe` | Regression | web-classlib's `Module` and `ModuleLayer` | +| `PacketHandoffProbe` | Measurement | What handing a packet to the game's thread costs (ADR 0033) | +| `ReloadLeakProbe` | Check | Memory held across page reloads in one tab (read with a CDP script) | +| `SharableProbe` | Regression | tools/webbuild's RemovalTransformer | +| `SocketDeliveryProbe` | Measurement | What handing one WebSocket message from the page's queue to Java costs | +| `StorageProbe` | Regression | platform-web's file system (ADR 0011) under TeaVM's own java.io and java.nio.file | +| `SuppressedProbe` | Regression | Suppressed exceptions (a tools/teavm-patches fix until TeaVM 0.16.0 had it) | +| `SuspendingReflectionProbe` | Regression | tools/teavm-patches' CoroutineTransformation fix for non-nullable locals | +| `SuspendingTernaryProbe` | Regression | A suspending `c ? a : b` (a tools/teavm-patches fix until TeaVM 0.16.0 had it) | +| `ThreadLocalProbe` | Check | web-classlib's `ThreadLocal` across thread switches | +| `ThrowCensusProbe` | Check | The throw census, `-Pteavm.throwCensus` (ADR 0033) | +| `ViaPipelineUtilProbe` | Regression | web-classlib's substitute for Via's `PipelineUtil` | +| `ViaTypeTokenProbe` | Regression | TypeCaptures' entry for Via's bundled Gson | +| `WaitRoutingProbe` | Regression | tools/webbuild's MonitorElision routing every `Object.wait` through web-classlib's `Waits` | +| `WeakQueueProbe` | Check | References polled from a ReferenceQueue keep their own class's methods | +| `WebGpuCallProbe` | Measurement | What one WebGPU call costs from Java (`docs/webgpu-backend.md`) | +| `WrapIntProbe` | Check | `int`s reach JavaScript as the same Numbers (tools/webbuild's `JsoIntrinsics`) | +| `ZipFileProbe` | Regression | tools/teavm-patches' TZipFile fix | diff --git a/incari-client/files/app-web/probes/ReloadLeakProbe.java b/incari-client/files/app-web/probes/ReloadLeakProbe.java new file mode 100644 index 0000000..16b044a --- /dev/null +++ b/incari-client/files/app-web/probes/ReloadLeakProbe.java @@ -0,0 +1,39 @@ +/** + * Holds 50 MB and parks a thread on a monitor for good, then prints "probe ready". Loaded several + * times in one tab (tools: a CDP script reloading it and reading the heap after a collection), it + * shows whether a reloaded page's module, its objects and its suspended threads are freed. With + * the Fast build (JSPI, {@code -Pteavm.fast}) a thread parked forever is a suspended engine stack. + * + *

What it found (2026-10-05, Chromium 151 and 153): the coroutine build's heap stayed under + * 2 MB over five loads (its parked thread holds nothing the engine sees), the JSPI build's grew + * 50 MB a load: V8 never frees a suspended stack, so every earlier page stayed whole. Ending the + * fibers on {@code pagehide} (jspi.ts) keeps it at the one live page's 51 MB. + */ +public final class ReloadLeakProbe { + + static final Object LOCK = new Object(); + static byte[][] held; + + public static void main(String[] args) throws InterruptedException { + held = new byte[50][]; + for (int i = 0; i < held.length; i++) { + held[i] = new byte[1 << 20]; + held[i][i] = (byte) i; + } + Thread parked = new Thread(() -> { + synchronized (LOCK) { + while (true) { + try { + LOCK.wait(); + } catch (InterruptedException e) { + return; + } + } + } + }, "parked"); + parked.setDaemon(true); + parked.start(); + Thread.sleep(50); + System.out.println("probe ready " + held[7][7]); + } +} diff --git a/incari-client/files/app-web/probes/SharableProbe.java b/incari-client/files/app-web/probes/SharableProbe.java new file mode 100644 index 0000000..fb75523 --- /dev/null +++ b/incari-client/files/app-web/probes/SharableProbe.java @@ -0,0 +1,28 @@ +import io.netty.channel.ChannelHandler; +import io.netty.channel.ChannelHandlerAdapter; +import io.netty.channel.ChannelInboundHandlerAdapter; + +/** + * Regression probe for tools/webbuild's RemovalTransformer: Netty's {@code @Sharable} check + * reads the annotation at run time, through a class TeaVM generates for it + * ({@code ChannelHandler$Sharable$$_impl}). The removal step took that class for a missing one, + * since it doesn't exist until after transformers run, and replaced it with a throwing reference + * under the catch-all Netty rule: adding any handler to a pipeline threw. Prints "probe passed" + * when a sharable handler reads as sharable and another doesn't. + */ +public final class SharableProbe { + + @ChannelHandler.Sharable + static final class Shared extends ChannelInboundHandlerAdapter {} + + static final class NotShared extends ChannelInboundHandlerAdapter {} + + private SharableProbe() {} + + public static void main(String[] args) { + ChannelHandlerAdapter shared = new Shared(); + ChannelHandlerAdapter notShared = new NotShared(); + boolean passed = shared.isSharable() && !notShared.isSharable(); + System.out.println(passed ? "probe passed" : "probe failed: " + shared.isSharable() + ", " + notShared.isSharable()); + } +} diff --git a/incari-client/files/app-web/probes/SocketDeliveryProbe.java b/incari-client/files/app-web/probes/SocketDeliveryProbe.java new file mode 100644 index 0000000..679ff8d --- /dev/null +++ b/incari-client/files/app-web/probes/SocketDeliveryProbe.java @@ -0,0 +1,136 @@ +import java.nio.ByteBuffer; +import org.teavm.jso.JSBody; +import org.teavm.jso.JSObject; +import org.teavm.jso.typedarrays.ArrayBuffer; +import org.teavm.jso.typedarrays.Int8Array; + +/** + * Measures what delivering one WebSocket message from the page's queue to Java costs in the + * WebAssembly GC build (platform-web's {@code WebSocketNetwork}), for a server's mix of packet + * sizes: the route as it was (each entry's type read as a string, its time, its buffer wrapped in a + * new Int8Array, then copied) against an entry's type as a number and the copy made from a view the + * page built when the message came. Prints microseconds per message and "probe passed" when all + * routes read the same bytes. + */ +public final class SocketDeliveryProbe { + + private SocketDeliveryProbe() {} + + public static void main(String[] args) { + int messages = 20_000; + JSObject queue = fill(messages); + long expected = 0; + for (int round = 0; round < 3; round++) { + expected = asBefore(queue, messages); + numbered(queue, messages); + } + int rounds = 10; + double start = now(); + long before = 0; + for (int i = 0; i < rounds; i++) { + before = asBefore(queue, messages); + } + double beforeMicros = (now() - start) * 1000 / rounds / messages; + start = now(); + long after = 0; + for (int i = 0; i < rounds; i++) { + after = numbered(queue, messages); + } + double afterMicros = (now() - start) * 1000 / rounds / messages; + start = now(); + long copyOnly = 0; + for (int i = 0; i < rounds; i++) { + copyOnly = copyOnly(queue, messages); + } + double copyMicros = (now() - start) * 1000 / rounds / messages; + System.out.println("SocketDeliveryProbe: per message (mean " + meanSize(queue, messages) + " B): as before " + + beforeMicros + " us, numbered types and kept views " + afterMicros + " us, the copy alone " + + copyMicros + " us"); + boolean same = expected == before && before == after && after == copyOnly; + System.out.println(same ? "probe passed" : "probe failed: the routes read different bytes"); + } + + private static long asBefore(JSObject queue, int count) { + long sum = 0; + double now = now(); + double longest = 0; + for (int i = 0; i < count; i++) { + longest = Math.max(longest, now - queuedTime(queue, i)); + switch (queuedType(queue, i)) { + case "message" -> { + byte[] message = new Int8Array(queuedData(queue, i)).copyToJavaArray(); + sum += checksum(ByteBuffer.wrap(message)); + } + default -> {} + } + } + return sum + (longest < 0 ? 1 : 0); + } + + private static long numbered(JSObject queue, int count) { + long sum = 0; + double now = now(); + double longest = 0; + for (int i = 0; i < count; i++) { + longest = Math.max(longest, now - queuedTime(queue, i)); + if (kind(queue, i) == 1) { + byte[] message = view(queue, i).copyToJavaArray(); + sum += checksum(ByteBuffer.wrap(message)); + } + } + return sum + (longest < 0 ? 1 : 0); + } + + private static long copyOnly(JSObject queue, int count) { + long sum = 0; + for (int i = 0; i < count; i++) { + byte[] message = view(queue, i).copyToJavaArray(); + sum += checksum(ByteBuffer.wrap(message)); + } + return sum; + } + + private static long checksum(ByteBuffer buffer) { + int n = buffer.remaining(); + return n == 0 ? 0 : n * 31L + buffer.get(0) + buffer.get(n - 1); + } + + private static int meanSize(JSObject queue, int count) { + long total = 0; + for (int i = 0; i < count; i++) { + total += view(queue, i).getLength(); + } + return (int) (total / count); + } + + // A server's mix: mostly small (movement, entity motion), some medium, a few chunks. + @JSBody( + params = "count", + script = "var q = [], t = [], n = [], v = []; var seed = 26;" + + "function rnd() { seed = (seed * 1103515245 + 12345) & 0x7fffffff; return seed / 0x7fffffff; }" + + "for (var i = 0; i < count; i++) { var r = rnd();" + + " var size = r < 0.8 ? 8 + (rnd() * 40 | 0) : r < 0.97 ? 100 + (rnd() * 900 | 0) : 4000 + (rnd() * 20000 | 0);" + + " var b = new ArrayBuffer(size); var a = new Int8Array(b);" + + " for (var j = 0; j < size; j += 7) a[j] = (i + j) & 127;" + + " q.push(['message', b]); t.push(performance.now()); n.push(1); v.push(a); }" + + "return {q: q, t: t, n: n, v: v};") + private static native JSObject fill(int count); + + @JSBody(params = {"s", "i"}, script = "return s.q[i][0];") + private static native String queuedType(JSObject s, int i); + + @JSBody(params = {"s", "i"}, script = "return s.q[i][1];") + private static native ArrayBuffer queuedData(JSObject s, int i); + + @JSBody(params = {"s", "i"}, script = "return s.t[i];") + private static native double queuedTime(JSObject s, int i); + + @JSBody(params = {"s", "i"}, script = "return s.n[i];") + private static native int kind(JSObject s, int i); + + @JSBody(params = {"s", "i"}, script = "return s.v[i];") + private static native Int8Array view(JSObject s, int i); + + @JSBody(script = "return performance.now();") + private static native double now(); +} diff --git a/incari-client/files/app-web/probes/StorageProbe.java b/incari-client/files/app-web/probes/StorageProbe.java new file mode 100644 index 0000000..73ddfac --- /dev/null +++ b/incari-client/files/app-web/probes/StorageProbe.java @@ -0,0 +1,94 @@ +import incari.platform.web.storage.WebFileSystem; +import java.io.DataInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.RandomAccessFile; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.util.List; +import java.util.stream.Stream; + +/** + * Regression probe for platform-web's file system (ADR 0011) under TeaVM's own java.io and + * java.nio.file: installs it, as WebMain does, and uses files the ways the game does (directories + * made with Files.createDirectories, the server list's temporary file and rename, a channel opened + * with CREATE, RandomAccessFile keeping its bytes, listing and walking), then flushes to the + * storage worker. Run it twice: the second run also finds what the first stored. Prints + * "probe passed" when everything reads back as written. + */ +public final class StorageProbe { + + private StorageProbe() {} + + public static void main(String[] args) throws IOException { + WebFileSystem files = WebFileSystem.install(List.of("/incari/dropped")); + StringBuilder problems = new StringBuilder(); + Path game = Path.of("/incari/game"); + + Path marker = game.resolve("probe-runs.txt"); + int runs = Files.exists(marker) ? Integer.parseInt(Files.readString(marker).trim()) : 0; + System.out.println("[probe] earlier runs stored: " + runs + " (backend " + files.backend() + ")"); + + Path downloads = game.resolve("downloads"); + Files.createDirectories(downloads); + if (!Files.isDirectory(downloads) || Files.exists(Path.of("/incari/game/incari"))) { + problems.append(" createDirectories"); + } + try (FileChannel log = FileChannel.open( + downloads.resolve("log.json"), StandardOpenOption.CREATE, StandardOpenOption.WRITE)) { + log.write(ByteBuffer.wrap("{}\n".getBytes(StandardCharsets.UTF_8))); + } + + // ServerList.save: a temporary file, then Util.safeReplaceFile's renames. + Path temporary = Files.createTempFile(game, "servers", ".dat"); + Files.write(temporary, new byte[] {0x0A, (byte) 0xC8, (byte) 0xFF, 0}); + Path servers = game.resolve("servers.dat"); + if (Files.exists(servers)) { + Files.move(servers, game.resolve("servers.dat_old"), StandardCopyOption.REPLACE_EXISTING); + } + Files.move(temporary, servers, StandardCopyOption.REPLACE_EXISTING); + try (InputStream in = Files.newInputStream(servers); + DataInputStream data = new DataInputStream(in)) { + if (data.readUnsignedByte() != 0x0A || data.readUnsignedShort() != 0xC8FF) { + problems.append(" servers.dat"); + } + } + + File region = game.resolve("r.0.0.mca").toFile(); + // TeaVM's RandomAccessFile doesn't create a missing file in "rw" mode, as the JDK's does; + // the game opens its region files through FileChannel, which does (web-classlib). + region.createNewFile(); + try (RandomAccessFile raf = new RandomAccessFile(region, "rw")) { + raf.write("0123456789".getBytes(StandardCharsets.US_ASCII)); + } + try (RandomAccessFile raf = new RandomAccessFile(region, "rw")) { + raf.seek(4); + raf.write('x'); + } + if (!Files.readString(region.toPath()).equals("0123x56789")) { + problems.append(" random access: ").append(Files.readString(region.toPath())); + } + + Files.writeString(game.resolve("options.txt"), "fov:1.0\n"); + try (Stream walk = Files.walk(game)) { + long count = walk.count(); + if (count < 6) { + problems.append(" walk ").append(count); + } + } + if (!new File("/incari/classpath").exists() && new File("/tmp").isDirectory()) { + // Nothing mounted in a probe; /tmp is there. + } else if (!new File("/tmp").isDirectory()) { + problems.append(" /tmp"); + } + Files.writeString(marker, Integer.toString(runs + 1)); + files.flush(); + System.out.println(problems.isEmpty() ? "probe passed" : "probe failed:" + problems); + } +} diff --git a/incari-client/files/app-web/probes/SuppressedProbe.java b/incari-client/files/app-web/probes/SuppressedProbe.java new file mode 100644 index 0000000..26ec1dd --- /dev/null +++ b/incari-client/files/app-web/probes/SuppressedProbe.java @@ -0,0 +1,20 @@ +/** + * Regression probe for tools/teavm-patches' TThrowable fix: {@code getSuppressed} and + * {@code addSuppressed} on a fresh exception. TeaVM's class library left the suppressed array + * null, so both threw NullPointerException; Netty's {@code DefaultPromise.syncUninterruptibly} + * calls {@code getSuppressed} on every failure it rethrows, which hid why a connection failed. + * Prints "probe passed" when an exception starts with none and keeps the one added. + */ +public final class SuppressedProbe { + + private SuppressedProbe() {} + + public static void main(String[] args) { + RuntimeException failure = new RuntimeException("failure"); + int before = failure.getSuppressed().length; + failure.addSuppressed(new IllegalStateException("suppressed")); + Throwable[] after = failure.getSuppressed(); + boolean passed = before == 0 && after.length == 1 && after[0].getMessage().equals("suppressed"); + System.out.println(passed ? "probe passed" : "probe failed: " + before + ", " + after.length); + } +} diff --git a/incari-client/files/app-web/probes/SuspendingReflectionProbe.java b/incari-client/files/app-web/probes/SuspendingReflectionProbe.java new file mode 100644 index 0000000..a27abe5 --- /dev/null +++ b/incari-client/files/app-web/probes/SuspendingReflectionProbe.java @@ -0,0 +1,74 @@ +import io.netty.util.ReferenceCounted; +import java.lang.reflect.Method; + +/** + * Regression probe for tools/teavm-patches' CoroutineTransformation fix for non-nullable locals + *: a method called through reflection that takes two or more arguments and suspends. TeaVM + * generates a caller for it that keeps the argument array's data in a non-nullable local, and the + * coroutine transformation's save and restore code read that local where WebAssembly doesn't count + * it as set: the module failed to validate ("uninitialized local"). + * + *

The method is the one that showed it, Netty's {@code ReferenceCountUtil.touch(Object, Object)}, + * which the browser build's reflection policy (tools/webbuild ReflectionDeclarations) already + * declares. It calls {@link ReferenceCounted#touch(Object)}, which suspends here, as it can in the + * game's build, so its reflection caller is a coroutine. Prints "probe passed" when the call + * reaches the object and returns it. + */ +public final class SuspendingReflectionProbe { + + /** A reference-counted object whose {@code touch} suspends. */ + static final class Touched implements ReferenceCounted { + String hint = ""; + + @Override + public ReferenceCounted touch(Object hint) { + try { + Thread.sleep(1); + } catch (InterruptedException e) { + throw new IllegalStateException(e); + } + this.hint = String.valueOf(hint); + return this; + } + + @Override + public ReferenceCounted touch() { + return touch(null); + } + + @Override + public int refCnt() { + return 1; + } + + @Override + public ReferenceCounted retain() { + return this; + } + + @Override + public ReferenceCounted retain(int increment) { + return this; + } + + @Override + public boolean release() { + return false; + } + + @Override + public boolean release(int decrement) { + return false; + } + } + + private SuspendingReflectionProbe() {} + + public static void main(String[] args) throws ReflectiveOperationException { + Method touch = Class.forName("io.netty.util.ReferenceCountUtil").getMethod("touch", Object.class, Object.class); + Touched message = new Touched(); + Object result = touch.invoke(null, message, "hint"); + boolean passed = result == message && message.hint.equals("hint"); + System.out.println(passed ? "probe passed" : "probe failed: " + result + ", hint " + message.hint); + } +} diff --git a/incari-client/files/app-web/probes/SuspendingTernaryProbe.java b/incari-client/files/app-web/probes/SuspendingTernaryProbe.java new file mode 100644 index 0000000..37758c5 --- /dev/null +++ b/incari-client/files/app-web/probes/SuspendingTernaryProbe.java @@ -0,0 +1,126 @@ +import java.util.ArrayList; +import java.util.List; + +/** + * Regression probe for tools/teavm-patches' CoroutineTransformation fix: a conditional + * expression whose one branch suspends, left on the operand stack as an argument of a call that + * suspends too. The two branches build different subclasses of the declared result type, the else + * branch's being the narrower one. Before the fix, the coroutine transformation typed the restore + * block after the conditional with the else branch's class, and the module failed to validate + * ("type error in branch"): the shape of the game's {@code Connection.configureSerialization} + * with Netty's pipeline. Prints "probe passed" when the handlers arrive in order. + */ +public final class SuspendingTernaryProbe { + + interface Handler { + String id(); + } + + abstract static class Base implements Handler {} + + static class Wide extends Base { + @Override + public String id() { + return "wide"; + } + } + + static final class Narrow extends Wide { + @Override + public String id() { + return "narrow"; + } + } + + /** A handler whose constructor suspends, so the conditional that makes it does too. */ + static final class Suspending extends Base { + private final int value; + + Suspending(int value) { + this.value = value; + pause(); + } + + @Override + public String id() { + return "suspending" + value; + } + } + + /** An interface call that suspends, with the conditional's value among its arguments. */ + interface Pipeline { + Pipeline add(String name, Handler handler); + + Pipeline add(Handler... handlers); + } + + static final class ListPipeline implements Pipeline { + final List names = new ArrayList<>(); + + @Override + public Pipeline add(String name, Handler handler) { + pause(); + names.add(name + "=" + handler.id()); + return this; + } + + @Override + public Pipeline add(Handler... handlers) { + for (Handler handler : handlers) { + add("anonymous", handler); + } + return this; + } + } + + enum Flow { + IN, + OUT; + + Flow opposite() { + return this == IN ? OUT : IN; + } + } + + private static final Integer INITIAL = 7; + + private SuspendingTernaryProbe() {} + + private static void pause() { + try { + Thread.sleep(1); + } catch (InterruptedException e) { + throw new IllegalStateException(e); + } + } + + private static String name(boolean configure) { + return configure ? "configured" : "unconfigured"; + } + + private static Handler framing(boolean local) { + return local ? new Wide() : new Narrow(); + } + + static void configure(Pipeline pipeline, Flow inbound, boolean local) { + Flow outbound = inbound.opposite(); + boolean configureInbound = inbound == Flow.OUT; + boolean configureOutbound = outbound == Flow.OUT; + pipeline.add("splitter", framing(local)) + .add(new Wide()) + .add(name(configureInbound), configureInbound ? new Suspending(INITIAL) : new Narrow()) + .add("prepender", framing(local)) + .add(name(configureOutbound), configureOutbound ? new Suspending(INITIAL) : new Narrow()); + } + + public static void main(String[] args) { + ListPipeline pipeline = new ListPipeline(); + configure(pipeline, Flow.IN, false); + configure(pipeline, Flow.OUT, true); + String expected = "[splitter=narrow, anonymous=wide, unconfigured=narrow, prepender=narrow," + + " configured=suspending7, splitter=wide, anonymous=wide, configured=suspending7," + + " prepender=wide, unconfigured=narrow]"; + String actual = pipeline.names.toString(); + System.out.println(actual.equals(expected) ? "probe passed" : "probe failed: " + actual); + } +} diff --git a/incari-client/files/app-web/probes/ThreadLocalProbe.java b/incari-client/files/app-web/probes/ThreadLocalProbe.java new file mode 100644 index 0000000..cd5ed38 --- /dev/null +++ b/incari-client/files/app-web/probes/ThreadLocalProbe.java @@ -0,0 +1,53 @@ +/** + * web-classlib's {@code ThreadLocal} in the browser: four threads take turns through sleeps (each + * wait switches threads, so each thread-local's remembered last thread keeps changing), each + * setting and reading its own value, with {@code withInitial}'s value per thread and after + * {@code remove}. Prints "probe passed". Run it in both builds. + */ +public final class ThreadLocalProbe { + + private static final ThreadLocal NAME = new ThreadLocal<>(); + + private static final ThreadLocal COUNTER = ThreadLocal.withInitial(() -> new int[1]); + + static volatile String failure; + + private ThreadLocalProbe() {} + + static void check(boolean condition, String what) { + if (!condition && failure == null) { + failure = what; + } + } + + public static void main(String[] args) throws InterruptedException { + NAME.set("main"); + Thread[] threads = new Thread[4]; + for (int i = 0; i < threads.length; i++) { + String name = "worker-" + i; + threads[i] = new Thread(() -> { + check(NAME.get() == null, name + " saw another thread's value"); + NAME.set(name); + for (int n = 0; n < 50; n++) { + COUNTER.get()[0]++; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + check(name.equals(NAME.get()), name + " read " + NAME.get() + " after a switch"); + } + check(COUNTER.get()[0] == 50, name + " counted " + COUNTER.get()[0]); + NAME.remove(); + check(NAME.get() == null, name + " still had a value after remove"); + }, name); + threads[i].start(); + } + for (Thread thread : threads) { + thread.join(); + } + check("main".equals(NAME.get()), "main read " + NAME.get()); + check(COUNTER.get()[0] == 0, "main's counter was " + COUNTER.get()[0]); + System.out.println(failure == null ? "probe passed" : "probe failed: " + failure); + } +} diff --git a/incari-client/files/app-web/probes/ThrowCensusProbe.java b/incari-client/files/app-web/probes/ThrowCensusProbe.java new file mode 100644 index 0000000..3f5b5a5 --- /dev/null +++ b/incari-client/files/app-web/probes/ThrowCensusProbe.java @@ -0,0 +1,49 @@ +/** + * Checks the throw census (`-Pteavm.throwCensus`, ADR 0033): throws a known number of times on the + * main thread and on another, across one census report, then prints "probe passed". Run with the + * census on and read the "[Incari] Throws" lines: the main thread's site counts 1000 on it, the + * other thread's 3000 off it. + */ +public final class ThrowCensusProbe { + + static int caught; + + private ThrowCensusProbe() {} + + static void fail(int i) { + throw new IllegalStateException("throw " + i); + } + + static void failElsewhere(int i) { + throw new UnsupportedOperationException("throw " + i); + } + + public static void main(String[] args) throws InterruptedException { + for (int i = 0; i < 1000; i++) { + try { + fail(i); + } catch (IllegalStateException e) { + caught++; + } + } + Thread other = new Thread(() -> { + for (int i = 0; i < 3000; i++) { + try { + failElsewhere(i); + } catch (UnsupportedOperationException e) { + caught++; + } + } + }); + other.start(); + other.join(); + // The census reports at the first throw ten seconds after its first. + Thread.sleep(10_500); + try { + fail(-1); + } catch (IllegalStateException e) { + caught++; + } + System.out.println(caught == 4001 ? "probe passed" : "probe failed: caught " + caught); + } +} diff --git a/incari-client/files/app-web/probes/ViaPipelineUtilProbe.java b/incari-client/files/app-web/probes/ViaPipelineUtilProbe.java new file mode 100644 index 0000000..278d37e --- /dev/null +++ b/incari-client/files/app-web/probes/ViaPipelineUtilProbe.java @@ -0,0 +1,29 @@ +import com.viaversion.viaversion.util.PipelineUtil; + +/** + * Regression probe for web-classlib's substitute for Via's {@code PipelineUtil}: Via's own + * looks up Netty's codec methods reflectively when it loads, which the browser can't do, so the + * class failed to initialize, and Via's checks for a cancelled packet ({@code containsCause}) + * failed with it: the first packet Via dropped on purpose (the game's Login Acknowledged, for a + * 1.8 server) ended the connection. Prints "probe passed" when a cause is found inside a wrapper. + */ +public final class ViaPipelineUtilProbe { + + private ViaPipelineUtilProbe() {} + + public static void main(String[] args) { + Thread thread = new Thread(ViaPipelineUtilProbe::run, "probe"); + thread.start(); + } + + private static void run() { + try { + // Via's own cancel exceptions need a running Via; any cause shows the class loads. + RuntimeException wrapped = new RuntimeException(new java.io.IOException("cancelled")); + boolean found = PipelineUtil.containsCause(wrapped, java.io.IOException.class); + System.out.println(found ? "probe passed" : "probe failed: the cancel wasn't found"); + } catch (Throwable t) { + System.out.println("probe failed: " + t); + } + } +} diff --git a/incari-client/files/app-web/probes/ViaTypeTokenProbe.java b/incari-client/files/app-web/probes/ViaTypeTokenProbe.java new file mode 100644 index 0000000..82aba20 --- /dev/null +++ b/incari-client/files/app-web/probes/ViaTypeTokenProbe.java @@ -0,0 +1,34 @@ +import com.viaversion.viaversion.libs.gson.Gson; +import com.viaversion.viaversion.libs.gson.reflect.TypeToken; +import java.util.Map; + +/** + * Regression probe for TypeCaptures' entry for Via's bundled Gson: Via reads its 1.12-to- + * 1.13 block ids as {@code Map} through an anonymous {@code TypeToken}, which + * reads its type argument from its generic superclass. TeaVM keeps no generic signatures unless + * TypeCaptures records them; without the entry, Via's 1.13 data failed to load and no server older + * than 1.13 could be joined. Prints "probe passed" when the map's values come back as arrays. + */ +public final class ViaTypeTokenProbe { + + private ViaTypeTokenProbe() {} + + public static void main(String[] args) { + Thread thread = new Thread(ViaTypeTokenProbe::run, "probe"); + thread.start(); + } + + private static void run() { + try { + Map map = new Gson() + .fromJson("{\"stone\": [\"minecraft:stone\", \"minecraft:granite\"]}", + new TypeToken>() {}.getType()); + String[] ids = map.get("stone"); + System.out.println(ids != null && ids.length == 2 && ids[1].equals("minecraft:granite") + ? "probe passed" + : "probe failed: " + map); + } catch (Throwable t) { + System.out.println("probe failed: " + t); + } + } +} diff --git a/incari-client/files/app-web/probes/WaitRoutingProbe.java b/incari-client/files/app-web/probes/WaitRoutingProbe.java new file mode 100644 index 0000000..f60fea0 --- /dev/null +++ b/incari-client/files/app-web/probes/WaitRoutingProbe.java @@ -0,0 +1,48 @@ +/** + * Regression probe for tools/webbuild's MonitorElision routing every {@code Object.wait} through + * web-classlib's {@code Waits}, which times the render thread's waits: plain, timed and + * nanosecond waits still wait, wake on a notify from another thread, and time out; a join and a + * CompletableFuture's join (which wait underneath) still return. The first build that routed waits + * also routed Object's own wait(long) call to wait(long, int), which recursed until the stack ran + * out at start. Prints "probe passed". + */ +public final class WaitRoutingProbe { + + private static final Object LOCK = new Object(); + private static boolean ready; + + private WaitRoutingProbe() {} + + public static void main(String[] args) throws Exception { + // A timed wait that times out. + long start = System.currentTimeMillis(); + synchronized (LOCK) { + LOCK.wait(30); + LOCK.wait(5, 500); + } + long waited = System.currentTimeMillis() - start; + // A wait that another thread's notify ends. + Thread notifier = new Thread(() -> { + synchronized (LOCK) { + ready = true; + LOCK.notifyAll(); + } + }); + notifier.start(); + synchronized (LOCK) { + while (!ready) { + LOCK.wait(); + } + } + notifier.join(); + // A future completed on another thread, joined here. + java.util.concurrent.CompletableFuture future = new java.util.concurrent.CompletableFuture<>(); + new Thread(() -> future.complete("done")).start(); + String joined = future.join(); + if (waited >= 30 && ready && joined.equals("done")) { + System.out.println("probe passed"); + } else { + System.out.println("probe failed: waited " + waited + " ms, ready " + ready + ", joined " + joined); + } + } +} diff --git a/incari-client/files/app-web/probes/WeakQueueProbe.java b/incari-client/files/app-web/probes/WeakQueueProbe.java new file mode 100644 index 0000000..69734ee --- /dev/null +++ b/incari-client/files/app-web/probes/WeakQueueProbe.java @@ -0,0 +1,58 @@ +import java.lang.ref.Reference; +import java.lang.ref.ReferenceQueue; +import java.lang.ref.WeakReference; + +/** + * References polled from a ReferenceQueue keep their own class's methods. TeaVM's analysis took + * everything poll() returns for a plain WeakReference, so a method only ever called on polled + * references (Guava's WeakValueReference.getEntry, when a weak-value map reclaims an entry) had + * no code in the subclass, and the call trapped ("dereferencing a null pointer"). Makes garbage + * until the browser collects some referents and the queue hands their references back. + */ +public class WeakQueueProbe { + + /** Called through an interface, as Guava calls WeakValueReference.getEntry(). */ + interface HasTag { + int tag(); + } + + static class Tagged extends WeakReference implements HasTag { + private final int tag; + + Tagged(Object referent, ReferenceQueue queue, int tag) { + super(referent, queue); + this.tag = tag; + } + + /** Called only on references that came back from the queue. */ + @Override + public int tag() { + return tag; + } + } + + public static void main(String[] args) throws Exception { + ReferenceQueue queue = new ReferenceQueue<>(); + Tagged[] kept = new Tagged[20_000]; + for (int i = 0; i < kept.length; i++) { + kept[i] = new Tagged(new int[64], queue, i + 1); + } + long sum = 0; + int polled = 0; + Object[] churn = new Object[1024]; + for (int round = 0; round < 400 && polled == 0; round++) { + for (int i = 0; i < 200_000; i++) { + churn[i & 1023] = new int[32]; + } + // Lets the page's event loop run, where the finalization callbacks come. + Thread.sleep(20); + Reference reference; + while ((reference = queue.poll()) != null) { + sum += ((HasTag) reference).tag(); + polled++; + } + } + System.out.println("polled " + polled + " references, tags summing to " + sum); + System.out.println(polled > 0 && sum > 0 ? "probe passed" : "probe failed: nothing came back from the queue"); + } +} diff --git a/incari-client/files/app-web/probes/WebGpuCallProbe.java b/incari-client/files/app-web/probes/WebGpuCallProbe.java new file mode 100644 index 0000000..8635321 --- /dev/null +++ b/incari-client/files/app-web/probes/WebGpuCallProbe.java @@ -0,0 +1,303 @@ +import org.teavm.interop.Async; +import org.teavm.jso.JSBody; +import org.teavm.jso.JSFunctor; +import org.teavm.jso.JSObject; +import org.teavm.jso.JSProperty; +import org.teavm.jso.typedarrays.Int32Array; +import org.teavm.jso.typedarrays.Uint32Array; +import org.teavm.jso.webgl.WebGL2RenderingContext; +import org.teavm.jso.webgl.WebGLUniformLocation; +import org.teavm.jso.webgpu.GPUBindGroup; +import org.teavm.jso.webgpu.GPUDevice; +import org.teavm.jso.webgpu.GPURenderPassEncoder; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.IntBuffer; + +/** + * What one WebGPU call costs from Java (docs/webgpu-backend.md, the W0 spike's open question): + * the same frame of draws, each with its own uniform (a dynamic offset), encoded five ways and timed + * on the CPU. Through TeaVM's JSO, a call per command, as a Java backend would; in one JavaScript + * loop, the floor any language could reach; Java writing commands into linear memory and one + * JavaScript call replaying them, the TypeScript layer a backend could fall back on; a render bundle + * recorded once; and WebGL2's uniform and draw per object through JSO, as {@code render-webgl2} + * draws what it doesn't multi-draw. Needs a WebGPU adapter: {@code app-web/probes/run.sh + * WebGpuCallProbe -Pbrowser.gpu=webgpu} (Linux Chrome gives WebGPU only on Vulkan). Prints + * microseconds a draw and "probe passed". + */ +public final class WebGpuCallProbe { + + private static final int DRAWS = 2000; + + private static final int WARMUP_FRAMES = 20; + + private static final int FRAMES = 100; + + /** Command codes for the replay route: one int code, then its arguments. */ + private static final int SET_BIND_GROUP = 1; + + private static final int DRAW_INDEXED = 2; + + private WebGpuCallProbe() {} + + /** + * TeaVM's render pass, plus the dynamic-offset overload that takes a range of the offsets array, + * which TeaVM's binding lacks: without it each draw would allocate a subarray. + */ + interface Pass extends GPURenderPassEncoder { + void setBindGroup(int index, GPUBindGroup group, Uint32Array offsets, int start, int length); + } + + /** What {@link #setUp} made: the pipeline, buffers, bind group and target, and a recorded bundle. */ + interface Scene extends JSObject { + @JSProperty + GPUBindGroup bindGroup(); + + @JSProperty + Uint32Array offsets(); + + @JSProperty + WebGL2RenderingContext gl(); + + @JSProperty + WebGLUniformLocation glOffset(); + } + + @JSFunctor + interface Done extends JSObject { + void done(JSObject value); + } + + public static void main(String[] args) { + GPUDevice device = (GPUDevice) requestDevice(); + if (device == null) { + System.out.println("probe failed: no WebGPU adapter (" + adapterNote() + ")"); + return; + } + System.out.println("WebGpuCallProbe: adapter " + adapterNote() + ", " + DRAWS + " draws a frame, " + + FRAMES + " frames"); + Scene scene = setUp(device, DRAWS); + IntBuffer commands = ByteBuffer.allocateDirect(DRAWS * 8 * 4).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer(); + // An Int32Array over the same linear memory, made once: the replay reads it in place. + Int32Array commandView = Int32Array.fromJavaBuffer(commands); + + String[] names = {"JSO, a call per command", "one JavaScript loop", "replayed from linear memory", + "render bundle", "WebGL2 through JSO"}; + double[] totals = new double[names.length]; + for (int frame = 0; frame < WARMUP_FRAMES + FRAMES; frame++) { + for (int route = 0; route < names.length; route++) { + double start = now(); + switch (route) { + case 0 -> { + Pass pass = beginPass(device, scene); + GPUBindGroup group = scene.bindGroup(); + Uint32Array offsets = scene.offsets(); + for (int i = 0; i < DRAWS; i++) { + pass.setBindGroup(0, group, offsets, i, 1); + pass.drawIndexed(3, 1, 0, 0, 0); + } + endPass(device, scene); + } + case 1 -> { + Pass pass = beginPass(device, scene); + drawAllInJs(pass, scene, DRAWS); + endPass(device, scene); + } + case 2 -> { + Pass pass = beginPass(device, scene); + commands.clear(); + for (int i = 0; i < DRAWS; i++) { + commands.put(SET_BIND_GROUP).put(i); + commands.put(DRAW_INDEXED).put(3).put(0).put(0); + } + replay(pass, scene, commandView, commands.position()); + endPass(device, scene); + } + case 3 -> { + Pass pass = beginPass(device, scene); + executeBundle(pass, scene); + endPass(device, scene); + } + default -> { + WebGL2RenderingContext gl = scene.gl(); + WebGLUniformLocation offset = scene.glOffset(); + prepareGl(scene); + for (int i = 0; i < DRAWS; i++) { + gl.uniform4f(offset, (i % 50) * 0.04f - 1, (i / 50) * 0.04f - 1, 0, 0); + gl.drawElements(WebGL2RenderingContext.TRIANGLES, 3, WebGL2RenderingContext.UNSIGNED_SHORT, 0); + } + gl.flush(); + } + } + double elapsed = now() - start; + if (frame >= WARMUP_FRAMES) { + totals[route] += elapsed; + } + // Untimed: let the GPU catch up, so the next frame's calls don't wait on a full queue. + if (route == names.length - 1) { + glFinish(scene); + } else { + workDone(device); + } + } + } + for (int route = 0; route < names.length; route++) { + double frameMillis = totals[route] / FRAMES; + System.out.println(String.format(" %-28s %7.3f ms a frame, %6.3f us a draw", names[route], frameMillis, + frameMillis * 1000 / DRAWS)); + } + String error = takeError(scene); + System.out.println(error == null ? "probe passed" : "probe failed: " + error); + } + + @Async + private static native JSObject requestDevice(); + + private static void requestDevice(org.teavm.interop.AsyncCallback callback) { + requestDevice(value -> callback.complete(value)); + } + + @JSBody( + params = "done", + script = "if (!navigator.gpu) { done(null); return; }" + + "navigator.gpu.requestAdapter().then(function(a) {" + + " if (!a) return null;" + + " globalThis.probeAdapter = a.info.vendor + '/' + a.info.architecture" + + " + (a.info.isFallbackAdapter ? ' (fallback)' : '');" + + " return a.requestDevice();" + + "}).then(function(d) { done(d || null); }, function() { done(null); });") + private static native void requestDevice(Done done); + + @JSBody(script = "return globalThis.probeAdapter || (navigator.gpu ? 'none' : 'no navigator.gpu');") + private static native String adapterNote(); + + @Async + private static native JSObject workDone(GPUDevice device); + + private static void workDone(GPUDevice device, org.teavm.interop.AsyncCallback callback) { + workDone(device, value -> callback.complete(value)); + } + + @JSBody( + params = {"device", "done"}, + script = "device.queue.onSubmittedWorkDone().then(function() { done(null); });") + private static native void workDone(GPUDevice device, Done done); + + /** + * A pipeline drawing one small triangle per draw, moved by a uniform read at a dynamic offset + * (256 bytes apart, WebGPU's minimum); a 256x256 target; the same draws recorded as a bundle; + * and a WebGL2 program doing the same on an OffscreenCanvas. + */ + @JSBody( + params = {"device", "draws"}, + script = "var s = {};" + + "var code = 'struct U { offset: vec4f };'" + + " + '@group(0) @binding(0) var u: U;'" + + " + '@vertex fn vs(@location(0) p: vec2f) -> @builtin(position) vec4f {'" + + " + ' return vec4f(p * 0.02 + u.offset.xy, 0.0, 1.0); }'" + + " + '@fragment fn fs() -> @location(0) vec4f { return vec4f(1.0, 0.5, 0.0, 1.0); }';" + + "device.pushErrorScope('validation');" + + "var module = device.createShaderModule({ code: code });" + + "var layout = device.createBindGroupLayout({ entries: [{ binding: 0," + + " visibility: GPUShaderStage.VERTEX, buffer: { type: 'uniform', hasDynamicOffset: true } }] });" + + "s.pipeline = device.createRenderPipeline({" + + " layout: device.createPipelineLayout({ bindGroupLayouts: [layout] })," + + " vertex: { module: module, entryPoint: 'vs', buffers: [{ arrayStride: 8," + + " attributes: [{ shaderLocation: 0, offset: 0, format: 'float32x2' }] }] }," + + " fragment: { module: module, entryPoint: 'fs', targets: [{ format: 'rgba8unorm' }] }," + + " primitive: { topology: 'triangle-list' } });" + + "var uniforms = new Float32Array(draws * 64);" + + "for (var i = 0; i < draws; i++) {" + + " uniforms[i * 64] = (i % 50) * 0.04 - 1; uniforms[i * 64 + 1] = Math.floor(i / 50) * 0.04 - 1; }" + + "var ubuf = device.createBuffer({ size: uniforms.byteLength," + + " usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });" + + "device.queue.writeBuffer(ubuf, 0, uniforms);" + + "s.bindGroup = device.createBindGroup({ layout: layout," + + " entries: [{ binding: 0, resource: { buffer: ubuf, size: 16 } }] });" + + "s.offsets = new Uint32Array(draws);" + + "for (var i = 0; i < draws; i++) s.offsets[i] = i * 256;" + + "s.vbuf = device.createBuffer({ size: 24, usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST });" + + "device.queue.writeBuffer(s.vbuf, 0, new Float32Array([0, 0, 1, 0, 0, 1]));" + + "s.ibuf = device.createBuffer({ size: 8, usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST });" + + "device.queue.writeBuffer(s.ibuf, 0, new Uint16Array([0, 1, 2, 0]));" + + "s.view = device.createTexture({ size: [256, 256], format: 'rgba8unorm'," + + " usage: GPUTextureUsage.RENDER_ATTACHMENT }).createView();" + + "var b = device.createRenderBundleEncoder({ colorFormats: ['rgba8unorm'] });" + + "b.setPipeline(s.pipeline); b.setVertexBuffer(0, s.vbuf); b.setIndexBuffer(s.ibuf, 'uint16');" + + "for (var i = 0; i < draws; i++) { b.setBindGroup(0, s.bindGroup, s.offsets, i, 1);" + + " b.drawIndexed(3, 1, 0, 0, 0); }" + + "s.bundle = b.finish();" + + "device.popErrorScope().then(function(e) { if (e) s.error = e.message; });" + + "device.onuncapturederror = function(e) { s.error = s.error || e.error.message; };" + + "var gl = new OffscreenCanvas(256, 256).getContext('webgl2');" + + "function shader(type, src) { var sh = gl.createShader(type); gl.shaderSource(sh, src);" + + " gl.compileShader(sh); return sh; }" + + "var p = gl.createProgram();" + + "gl.attachShader(p, shader(gl.VERTEX_SHADER, '#version 300 es\\nin vec2 p; uniform vec4 offset;'" + + " + ' void main() { gl_Position = vec4(p * 0.02 + offset.xy, 0.0, 1.0); }'));" + + "gl.attachShader(p, shader(gl.FRAGMENT_SHADER, '#version 300 es\\nprecision mediump float;'" + + " + ' out vec4 c; void main() { c = vec4(1.0, 0.5, 0.0, 1.0); }'));" + + "gl.bindAttribLocation(p, 0, 'p'); gl.linkProgram(p);" + + "if (!gl.getProgramParameter(p, gl.LINK_STATUS)) s.error = 'WebGL2 link: ' + gl.getProgramInfoLog(p);" + + "s.glProgram = p; s.glOffset = gl.getUniformLocation(p, 'offset');" + + "var vao = gl.createVertexArray(); gl.bindVertexArray(vao);" + + "var vb = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vb);" + + "gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 0, 1, 0, 0, 1]), gl.STATIC_DRAW);" + + "gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);" + + "var ib = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ib);" + + "gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array([0, 1, 2, 0]), gl.STATIC_DRAW);" + + "s.gl = gl;" + + "return s;") + private static native Scene setUp(GPUDevice device, int draws); + + @JSBody( + params = {"device", "s"}, + script = "s.encoder = device.createCommandEncoder();" + + "var pass = s.encoder.beginRenderPass({ colorAttachments: [{ view: s.view," + + " loadOp: 'clear', storeOp: 'store', clearValue: [0, 0, 0, 1] }] });" + + "pass.setPipeline(s.pipeline); pass.setVertexBuffer(0, s.vbuf); pass.setIndexBuffer(s.ibuf, 'uint16');" + + "s.pass = pass; return pass;") + private static native Pass beginPass(GPUDevice device, Scene scene); + + /** Ends the pass {@link #beginPass} began and submits its commands. */ + @JSBody( + params = {"device", "s"}, + script = "s.pass.end(); device.queue.submit([s.encoder.finish()]);") + private static native void endPass(GPUDevice device, Scene scene); + + @JSBody( + params = {"pass", "s", "draws"}, + script = "var g = s.bindGroup, o = s.offsets;" + + "for (var i = 0; i < draws; i++) { pass.setBindGroup(0, g, o, i, 1); pass.drawIndexed(3, 1, 0, 0, 0); }") + private static native void drawAllInJs(Pass pass, Scene scene, int draws); + + @JSBody( + params = {"pass", "s", "view", "length"}, + script = "var g = s.bindGroup, o = s.offsets, i = 0;" + + "while (i < length) {" + + " var op = view[i];" + + " if (op === 1) { pass.setBindGroup(0, g, o, view[i + 1], 1); i += 2; }" + + " else { pass.drawIndexed(view[i + 1], 1, view[i + 2], view[i + 3], 0); i += 4; } }") + private static native void replay(Pass pass, Scene scene, Int32Array view, int length); + + @JSBody(params = {"pass", "s"}, script = "pass.executeBundles([s.bundle]);") + private static native void executeBundle(Pass pass, Scene scene); + + @JSBody( + params = "s", + script = "var gl = s.gl; gl.useProgram(s.glProgram); gl.viewport(0, 0, 256, 256);" + + "gl.clear(gl.COLOR_BUFFER_BIT);") + private static native void prepareGl(Scene scene); + + @JSBody(params = "s", script = "s.gl.finish();") + private static native void glFinish(Scene scene); + + @JSBody( + params = "s", + script = "var e = s.error || null; if (!e && s.gl.getError() !== 0) e = 'WebGL2 error ' + s.gl.getError();" + + " return e;") + private static native String takeError(Scene scene); + + @JSBody(script = "return performance.now();") + private static native double now(); +} diff --git a/incari-client/files/app-web/probes/WrapIntProbe.java b/incari-client/files/app-web/probes/WrapIntProbe.java new file mode 100644 index 0000000..0172630 --- /dev/null +++ b/incari-client/files/app-web/probes/WrapIntProbe.java @@ -0,0 +1,51 @@ +import org.teavm.jso.JSBody; +import org.teavm.jso.JSObject; + +/** + * {@code int}s handed to JavaScript arrive as the same Numbers (tools/webbuild's {@code + * JsoIntrinsics}: an i31 where the value fits, else TeaVM's import): each side of the i31 range's + * edges, the int range's ends, and values from a loop, so they aren't constants; through a + * {@code @JSBody} argument and through a JSO interface method's. Prints "probe passed". + */ +public final class WrapIntProbe { + + private WrapIntProbe() {} + + /** A JavaScript object whose method reports what it got, as a JSO interface call reaches it. */ + interface Checker extends JSObject { + String check(int value, String expected); + } + + public static void main(String[] args) { + int[] values = {0, 1, -1, 7, 36160, (1 << 30) - 1, 1 << 30, -(1 << 30), -(1 << 30) - 1, + Integer.MAX_VALUE, Integer.MIN_VALUE, 0x7fff_fffe, 123_456_789, -987_654_321}; + Checker checker = checker(); + String failure = null; + for (int round = 0; round < 3 && failure == null; round++) { + for (int value : values) { + // Not a constant the compiler could fold: a value read from the array, shifted and back. + int v = (value ^ round) ^ round; + String expected = Integer.toString(v); + String body = describe(v, expected); + String method = checker.check(v, expected); + if (body != null || method != null) { + failure = body != null ? body : method; + break; + } + } + } + System.out.println(failure == null ? "probe passed" : "probe failed: " + failure); + } + + @JSBody( + params = {"value", "expected"}, + script = "return typeof value === 'number' && String(value) === expected ? null" + + " : '@JSBody got ' + typeof value + ' ' + value + ', expected ' + expected;") + private static native String describe(int value, String expected); + + @JSBody( + script = "return { check: function(value, expected) {" + + " return typeof value === 'number' && String(value) === expected ? null" + + " : 'a method got ' + typeof value + ' ' + value + ', expected ' + expected; } };") + private static native Checker checker(); +} diff --git a/incari-client/files/app-web/probes/ZipFileProbe.java b/incari-client/files/app-web/probes/ZipFileProbe.java new file mode 100644 index 0000000..95371aa --- /dev/null +++ b/incari-client/files/app-web/probes/ZipFileProbe.java @@ -0,0 +1,62 @@ +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; +import java.util.Random; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; +import java.util.zip.ZipOutputStream; + +/** + * Regression probe for tools/teavm-patches' TZipFile fix: TeaVM's ZipFile gave its raw + * inflater exactly an entry's compressed bytes, and InflaterInputStream threw EOFException when + * the inflater still asked for input at their end, as it can for a whole entry (638 textures of a + * community resource pack). The JDK's ZipFile adds a dummy byte; the patch does too. Writes entries + * of many sizes and kinds, reads each back to its end, and prints "probe passed" when all match. + */ +public final class ZipFileProbe { + + private ZipFileProbe() {} + + public static void main(String[] args) throws IOException { + Random random = new Random(5); + byte[][] contents = new byte[400][]; + File file = new File("/probe.zip"); + try (ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(file))) { + for (int i = 0; i < contents.length; i++) { + byte[] data = new byte[random.nextInt(4000)]; + // Some random (incompressible), some patterned, some mixed: PNG-like variety. + for (int j = 0; j < data.length; j++) { + data[j] = (byte) (i % 3 == 0 ? random.nextInt() : i % 3 == 1 ? j / 7 : (j % 13) * random.nextInt(3)); + } + contents[i] = data; + zip.putNextEntry(new ZipEntry("entry" + i)); + zip.write(data); + zip.closeEntry(); + } + } + int failures = 0; + String first = ""; + try (ZipFile zip = new ZipFile(file)) { + for (int i = 0; i < contents.length; i++) { + try (InputStream in = zip.getInputStream(zip.getEntry("entry" + i))) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buffer = new byte[512]; + for (int read = in.read(buffer); read >= 0; read = in.read(buffer)) { + out.write(buffer, 0, read); + } + if (!Arrays.equals(out.toByteArray(), contents[i])) { + failures++; + first = first.isEmpty() ? "entry" + i + " differs" : first; + } + } catch (IOException e) { + failures++; + first = first.isEmpty() ? "entry" + i + ": " + e : first; + } + } + } + System.out.println(failures == 0 ? "probe passed" : "probe failed: " + failures + " entries, first " + first); + } +} diff --git a/incari-client/files/app-web/probes/run.sh b/incari-client/files/app-web/probes/run.sh new file mode 100644 index 0000000..01b7112 --- /dev/null +++ b/incari-client/files/app-web/probes/run.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash +# Compiles one probe (app-web/probes/.java) with TeaVM against the browser build's class +# library and runs it in headless Chromium until it prints "probe passed" (see README.md, +# Experiments). Takes seconds, not the full build's ten minutes. +# +# app-web/probes/run.sh SuspendingTernaryProbe +# app-web/probes/run.sh WebGpuCallProbe -Pbrowser.gpu=webgpu -Pteavm.fast (more Gradle options) +set -euo pipefail + +name="${1:?usage: app-web/probes/run.sh }" +root="$(cd "$(dirname "$0")/../.." && pwd)" +classes="$root/app-web/build/probes/$name" + +rm -rf "$classes" +# Probes may use the Netty the browser build keeps (the teavm task puts it on TeaVM's class path); +# javac finds the pinned version in Gradle's cache, which any build of the repo has filled. +netty="$(sed -n 's/^netty = "\(.*\)"/\1/p' "$root/gradle/libs.versions.toml")" +netty_jars="" +for module in netty-common netty-buffer netty-transport netty-codec-base; do + jar="$(find "${GRADLE_USER_HOME:-$HOME/.gradle}/caches/modules-2" -name "$module-$netty.jar" | head -n 1)" + netty_jars="$netty_jars:$jar" +done +# Probes may call TeaVM's interop and JSO APIs, as the page's own code does. +teavm="$(sed -n 's/^teavm = "\(.*\)"/\1/p' "$root/gradle/libs.versions.toml")" +for module in teavm-interop teavm-jso teavm-jso-apis; do + jar="$(find "${GRADLE_USER_HOME:-$HOME/.gradle}/caches/modules-2" -name "$module-$teavm.jar" | head -n 1)" + netty_jars="$netty_jars:$jar" +done +# Probes may use the Via the browser build compiles in. +for library in viaversion viabackwards; do + version="$(sed -n "s/^$library = \"\(.*\)\"/\1/p" "$root/gradle/libs.versions.toml")" + jar="$(find "${GRADLE_USER_HOME:-$HOME/.gradle}/caches/modules-2" -name "$library-common-$version.jar" | head -n 1)" + netty_jars="$netty_jars:$jar" +done +# Probes may also use Incari's platform classes (StorageProbe installs the file system). +cd "$root" +./gradlew -q :platform-web:classes +# Probes compile for Java 25, as the game does; a newer javac must be told. +javac --release 25 -cp "${netty_jars#:}:$root/platform-web/build/classes/java/main" -d "$classes" \ + "$root/app-web/probes/$name.java" +./gradlew :app-web:browserCheck -Pteavm.main="$name" -Pteavm.classpath="$classes" \ + "-Pbrowser.expect=probe (passed|failed.*)" -Pbrowser.count=1 -Pbrowser.seconds=60 "${@:2}" \ + | tee "$root/app-web/build/probes/$name.log" +grep -q "probe passed" "$root/app-web/build/probes/$name.log" diff --git a/incari-client/files/app-web/screenshot-scenes/options.txt b/incari-client/files/app-web/screenshot-scenes/options.txt new file mode 100644 index 0000000..7b820de --- /dev/null +++ b/incari-client/files/app-web/screenshot-scenes/options.txt @@ -0,0 +1,45 @@ +version:5023 +onboardAccessibility:false +pauseOnLostFocus:false +joinedFirstServer:true +skipMultiplayerWarning:true +tutorialStep:none +realmsNotifications:false +graphicsPreset:"custom" +fov:0.0 +fovEffectScale:0.0 +guiScale:2 +renderDistance:8 +simulationDistance:6 +biomeBlendRadius:2 +ao:true +renderClouds:"true" +cloudRange:64 +particles:0 +mipmapLevels:4 +textureFiltering:1 +maxAnisotropyBit:1 +entityShadows:true +entityDistanceScaling:1.0 +improvedTransparency:false +cutoutLeaves:true +weatherRadius:10 +chunkSectionFadeInTime:0.0 +menuBackgroundBlurriness:5 +prioritizeChunkUpdates:0 +bobView:false +gamma:0.5 +vignette:true +screenEffectScale:1.0 +darknessEffectScale:1.0 +damageTiltStrength:0.0 +hideLightningFlashes:true +enableVsync:false +maxFps:60 +inactivityFpsLimit:"minimized" +fullscreen:false +chatVisibility:2 +showSubtitles:false +narrator:0 +soundCategory_master:0.0 +lang:en_us diff --git a/incari-client/files/app-web/screenshot-scenes/scenes.txt b/incari-client/files/app-web/screenshot-scenes/scenes.txt new file mode 100644 index 0000000..4c165f5 --- /dev/null +++ b/incari-client/files/app-web/screenshot-scenes/scenes.txt @@ -0,0 +1,219 @@ +# The screenshot-diff harness's scenes: ./gradlew :app-web:screenshotDiff renders each one +# with the desktop game (Mojang's OpenGL backend) and the browser build (WebGL2), and compares the +# pairs by SSIM. The format is tools/webbuild's SceneScript; ADR 0012 explains the threshold. +# +# Each game joins its own fresh world from server.properties' seed as IncariShot, with +# options.txt's options. The harness freezes each world as soon as its server is up, so the only +# ticks either world runs are the ones the harness and these scenes step (tick step): the same in +# both, so clouds, animated textures and the like line up. Loading chunks takes ticks, so a +# teleport to somewhere new steps the world. Every scene sets its own time, weather, blocks and +# entities, so scenes don't depend on each other. Built scenes float at y 150 and above, so they +# don't depend on the terrain either. In a frozen world a killed entity never finishes dying, so +# entities are cleared by moving them out of sight (up and far away, never into the void, where a +# spectator still following one would die); particles only appear once the world ticks, +# so their scene steps it by one tick; and overworld chunks that reload after a trip to another +# dimension come back unlit, so the dimensions come last. + +threshold 0.90 + +setup + rcon:gamerule advance_time false + rcon:gamerule advance_weather false + rcon:gamerule spawn_mobs false + rcon:gamemode spectator IncariShot + # Hide the HUD and the hand: the scenes are about the world. + key:F1 + +scene terrain Overworld terrain at noon: solid, cutout and translucent terrain, grass, fog, sky + rcon:weather clear + rcon:time set 6000 + rcon:tp IncariShot 0 100 0 45 20 + sleep:3000 + settle + shot:terrain + +scene translucency Water, stained glass, ice, slime and honey, with regular and improved (OIT) transparency + rcon:weather clear + rcon:time set 6000 + rcon:tp IncariShot 20.5 154 34.5 0 25 + sleep:2000 + rcon:fill 13 149 39 27 149 53 minecraft:smooth_stone + rcon:fill 14 150 40 19 153 45 minecraft:glass hollow + rcon:fill 15 150 41 18 152 44 minecraft:water + rcon:setblock 21 150 41 minecraft:red_stained_glass + rcon:setblock 22 150 41 minecraft:lime_stained_glass + rcon:setblock 23 150 41 minecraft:blue_stained_glass + rcon:setblock 22 151 41 minecraft:yellow_stained_glass + rcon:fill 21 150 44 26 152 44 minecraft:light_blue_stained_glass_pane + rcon:setblock 21 150 47 minecraft:ice + rcon:setblock 23 150 47 minecraft:slime_block + rcon:setblock 25 150 47 minecraft:honey_block + rcon:setblock 25 150 42 minecraft:tinted_glass + sleep:2000 + settle + shot:translucency + # F3+X switches improved transparency (the order-independent transparency passes) on and off. + key:F3+KeyX + sleep:2000 + settle + shot:translucency_oit + key:F3+KeyX + sleep:1000 + +scene entities Mobs, an armor stand, a dropped item, block entities, shadows and a glowing outline + rcon:weather clear + rcon:time set 6000 + rcon:tp IncariShot -23.5 154 35.5 0 25 + sleep:2000 + rcon:tp @e[type=!minecraft:player] 0 250 -400 + rcon:fill -32 149 38 -15 149 54 minecraft:grass_block + rcon:summon minecraft:cow -27.5 150 43.5 {NoAI:1b,Rotation:[30f,0f]} + rcon:summon minecraft:sheep -24.5 150 44.5 {NoAI:1b,Color:14b,Rotation:[-20f,0f]} + rcon:summon minecraft:villager -20.5 150 43.5 {NoAI:1b,Rotation:[180f,0f]} + rcon:summon minecraft:zombie -25.5 150 47.5 {NoAI:1b,PersistenceRequired:1b,Glowing:1b,Rotation:[160f,0f]} + rcon:summon minecraft:armor_stand -21.5 150 47.5 {ShowArms:1b,Rotation:[200f,0f],equipment:{head:{id:"minecraft:diamond_helmet"},chest:{id:"minecraft:golden_chestplate"},mainhand:{id:"minecraft:iron_sword"}}} + rcon:summon minecraft:item -18.5 150 42.5 {Item:{id:"minecraft:diamond",count:1},PickupDelay:32767,Age:-32768} + rcon:setblock -29 150 50 minecraft:chest[facing=north] + rcon:setblock -28 150 50 minecraft:oak_sign[rotation=8]{front_text:{messages:["Incari","Scene","",""]}} + rcon:setblock -27 150 50 minecraft:white_banner[rotation=8] + rcon:setblock -26 150 50 minecraft:enchanting_table + rcon:setblock -25 150 50 minecraft:purple_shulker_box + rcon:setblock -24 150 50 minecraft:skeleton_skull[rotation=8] + rcon:setblock -23 150 50 minecraft:bell[attachment=floor,facing=north] + rcon:setblock -22 150 50 minecraft:decorated_pot + rcon:setblock -21 150 50 minecraft:lectern[has_book=true,facing=north] + rcon:setblock -20 150 50 minecraft:conduit + sleep:2000 + settle + shot:entities + +scene particles Particles of several kinds, fixed in place by the frozen world + rcon:weather clear + rcon:time set 6000 + rcon:tp IncariShot -23.5 154 75.5 0 20 + sleep:2000 + rcon:fill -32 149 80 -15 149 92 minecraft:stone + rcon:particle minecraft:flame -27.5 151 83.5 0 0 0 0 1 force + rcon:particle minecraft:heart -25.5 151.5 83.5 0 0 0 0 1 force + rcon:particle minecraft:happy_villager -23.5 151 83.5 0 0 0 0 1 force + rcon:particle minecraft:end_rod -21.5 151.5 83.5 0 0 0 0 1 force + rcon:particle minecraft:note -19.5 151 83.5 0 0 0 0 1 force + rcon:particle minecraft:explosion -23.5 152 86.5 0 0 0 0 1 force + rcon:particle minecraft:soul_fire_flame -27.5 151 85.5 0 0 0 0 1 force + rcon:particle minecraft:crit -19.5 151.5 85.5 0 0 0 0 1 force + # The client adds particles on its next tick. + rcon:tick step 1 + sleep:2000 + settle + shot:particles + +scene sky Sunrise and midnight: sun, moon, stars, clouds, the sky's colors + rcon:weather clear + rcon:time set 23600 + rcon:tp IncariShot 0 110 0 -90 -10 + sleep:2000 + settle + shot:sky_sunrise + rcon:time set 18000 + rcon:tp IncariShot 0 110 0 0 -60 + sleep:2000 + settle + shot:sky_midnight + +scene gui The creative inventory: items, block items, text, and an enchanted item's glint; then the HUD + rcon:weather clear + rcon:time set 6000 + # Players tick in a frozen world, and a creative player falls: stand them on a platform. + rcon:fill -2 149 -2 2 149 2 minecraft:smooth_stone + rcon:tp IncariShot 0 150 0 45 20 + rcon:gamemode creative IncariShot + rcon:item replace entity IncariShot hotbar.0 with minecraft:diamond_sword + rcon:item replace entity IncariShot hotbar.1 with minecraft:grass_block + rcon:item replace entity IncariShot hotbar.2 with minecraft:oak_log + rcon:item replace entity IncariShot hotbar.3 with minecraft:bow + rcon:item replace entity IncariShot hotbar.4 with minecraft:enchanted_golden_apple + rcon:item replace entity IncariShot hotbar.5 with minecraft:water_bucket + rcon:item replace entity IncariShot hotbar.6 with minecraft:torch + rcon:item replace entity IncariShot hotbar.7 with minecraft:shield + rcon:item replace entity IncariShot hotbar.8 with minecraft:red_bed + sleep:2000 + key:KeyE + move:0.02,0.02 + sleep:1500 + settle + shot:gui_inventory + key:Escape + # The HUD over the world: the page keeps it in a texture between refreshes (ADR 0030). + key:F1 + sleep:1000 + settle + shot:gui_hud + key:F1 + rcon:gamemode spectator IncariShot + sleep:1000 + +scene distant_terrain A wide floor seen at a grazing angle: mipmaps and texture filtering + rcon:weather clear + rcon:time set 6000 + rcon:tp IncariShot 0.5 185 90.5 0 30 + rcon:tick step 100 + sleep:7000 + rcon:fill -90 180 0 90 180 180 minecraft:bricks + rcon:tp IncariShot 0.5 181.7 1.5 0 4 + sleep:3000 + settle + shot:distant_terrain + rcon:tp IncariShot 0 100 0 45 20 + rcon:fill -90 180 0 90 180 180 minecraft:air + +scene post_effects Post effects: the pause menu's blur, and a creeper's view + rcon:weather clear + rcon:time set 6000 + rcon:tp IncariShot 0 100 0 45 20 + sleep:2000 + settle + key:Escape + move:0.02,0.02 + sleep:1000 + settle + shot:post_menu_blur + key:Escape + sleep:1000 + rcon:tp @e[type=minecraft:creeper] 0 250 -400 + rcon:summon minecraft:creeper 2.5 101 2.5 {NoAI:1b,NoGravity:1b,Rotation:[45f,20f]} + rcon:spectate @e[type=minecraft:creeper,limit=1] IncariShot + sleep:2000 + settle + shot:post_creeper + # A teleport ends spectating; only then may the creeper leave (a spectator follows its target). + rcon:tp IncariShot 0 100 0 45 20 + sleep:1000 + rcon:tp @e[type=minecraft:creeper] 0 250 -400 + sleep:1000 + +scene weather Rain over the terrain: the weather pass and its darker sky + rcon:weather rain + rcon:time set 6000 + rcon:tp IncariShot 0 100 0 45 20 + # Rain fades in over a few seconds of ticks. + rcon:tick step 200 + sleep:12000 + settle + shot:weather + rcon:weather clear + +scene dimensions The Nether and the End: their fog, sky and terrain + rcon:execute in minecraft:the_nether run tp IncariShot 0 80 0 45 10 + rcon:tick step 200 + sleep:12000 + settle + shot:nether + rcon:execute in minecraft:the_end run tp IncariShot 40 80 40 135 15 + rcon:tick step 200 + sleep:12000 + rcon:execute in minecraft:the_end run tp @e[type=minecraft:ender_dragon] 0 250 -400 + settle + shot:the_end + rcon:execute in minecraft:overworld run tp IncariShot 0 100 0 45 20 + rcon:tick step 200 + sleep:12000 diff --git a/incari-client/files/app-web/screenshot-scenes/server.properties b/incari-client/files/app-web/screenshot-scenes/server.properties new file mode 100644 index 0000000..4442ee2 --- /dev/null +++ b/incari-client/files/app-web/screenshot-scenes/server.properties @@ -0,0 +1,18 @@ +# The screenshot-diff harness's game server (see scenes.txt). The harness adds the address, +# ports and a random RCON password, and starts every run with a fresh world from this seed. +level-seed=20260928 +level-type=minecraft\:normal +generate-structures=true +online-mode=false +white-list=false +difficulty=easy +spawn-monsters=false +view-distance=8 +simulation-distance=6 +spawn-protection=0 +pause-when-empty-seconds=0 +max-tick-time=-1 +broadcast-console-to-ops=false +broadcast-rcon-to-ops=false +sync-chunk-writes=false +enable-status=true diff --git a/incari-client/files/app-web/src/main/java/incari/app/web/AssetPack.java b/incari-client/files/app-web/src/main/java/incari/app/web/AssetPack.java new file mode 100644 index 0000000..ec62d57 --- /dev/null +++ b/incari-client/files/app-web/src/main/java/incari/app/web/AssetPack.java @@ -0,0 +1,79 @@ +package incari.app.web; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import incari.classlib.resources.ClassPathResources; +import incari.platform.web.storage.WebFileSystem; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import org.jspecify.annotations.Nullable; + +/** + * The asset pack (ADR 0014): what the build prepares for the game ahead of time, in one zip + * the page mounts read-only at {@value #ROOT}: the translated shaders, and the vanilla sprites + * decoded with their mip levels (ADR 0026). Like the client jar, the storage worker keeps it + * (under its hash, so a new build's pack is fetched once) and it's mounted in place, each file + * inflated when opened. + * + *

The pack holds translated Mojang files, so it's made on the machine that builds the game + * ({@code :app-web:assetPack}) and never published. + * + *

Its layout: {@code pack.json} ({@code {"format": 1, "game": "26.3"}}), then the files by the + * names the game's loaders read ({@code shaders.json}, {@code sprites.bin}), and under {@value #CLASSPATH} resources + * libraries read from the class path (Via's mapping data). + */ +final class AssetPack { + + /** Where the pack's files appear in the page's file system. */ + static final String ROOT = "/incari-pack"; + + /** The pack's directory of class-path resources. */ + static final String CLASSPATH = "classpath"; + + /** The layout this code reads; a pack of another format is refused. */ + static final int FORMAT = 1; + + private AssetPack() {} + + /** + * Mounts the build's pack, if the build manifest names one; suspends while it's fetched. + * + * @return whether a pack is mounted + */ + static boolean mount(WebFileSystem files) throws IOException { + String url = LoaderPage.packUrl(); + if (url == null) { + return false; + } + double start = Fetch.now(); + WebFileSystem.Mounted mounted = files.mountZip(ROOT, url, cacheKey(url), name -> true); + JsonObject manifest = JsonParser.parseString( + new String(Files.readAllBytes(Path.of(ROOT, "pack.json")), StandardCharsets.UTF_8)) + .getAsJsonObject(); + int format = manifest.get("format").getAsInt(); + String game = manifest.get("game").getAsString(); + if (format != FORMAT || !game.equals(ClientJar.VERSION)) { + throw new IOException("The asset pack is format " + format + " for " + game + "; this build reads format " + + FORMAT + " for " + ClientJar.VERSION); + } + ClassPathResources.addRoot(ROOT + "/" + CLASSPATH); + System.out.println("[Incari] Asset pack: " + mounted.files() + " files, " + + (mounted.cached() ? "from storage" : "downloaded") + ", in " + Math.round(Fetch.now() - start) + + " ms"); + return true; + } + + /** A file of the mounted pack, or null if there's no pack or it lacks the file. */ + static byte @Nullable [] read(String name) throws IOException { + Path file = Path.of(ROOT, name); + return Files.isRegularFile(file) ? Files.readAllBytes(file) : null; + } + + /** The storage key: the pack's version (its URL's {@code ?v=}), so each build's is kept apart. */ + static String cacheKey(String url) { + int version = url.indexOf("?v="); + return "pack-" + (version < 0 ? "unversioned" : url.substring(version + 3)); + } +} diff --git a/incari-client/files/app-web/src/main/java/incari/app/web/ClientJar.java b/incari-client/files/app-web/src/main/java/incari/app/web/ClientJar.java new file mode 100644 index 0000000..f5e026d --- /dev/null +++ b/incari-client/files/app-web/src/main/java/incari/app/web/ClientJar.java @@ -0,0 +1,42 @@ +package incari.app.web; + +import incari.classlib.resources.ClassPathResources; +import incari.client.IncariBuild; +import incari.platform.web.storage.WebFileSystem; +import java.io.IOException; + +/** + * Puts the client jar's resources where the game looks for them ({@link ClassPathResources}): + * the build compiles the game's classes but not the rest of the jar, which is Mojang's to + * distribute. The page fetches the jar the player's machine already has; for development that's + * the one {@code ./incari setup} downloaded, which {@code :app-web:serve} offers at {@value #URL}. + * + *

The jar isn't unpacked: the storage worker keeps it (so later loads don't fetch + * it again), and it's mounted read-only in place, each resource inflated when the game opens it. + * Its bytes stay in the page, outside the game's heap (ADR 0011). + */ +final class ClientJar { + + static final String URL = "client.jar"; + + /** + * The game version the jar is, which names its cached copy: a new version's replaces it. From + * incari.properties, so a version bump can't leave players on a stale cached jar. + */ + static final String VERSION = IncariBuild.MINECRAFT_VERSION; + + private ClientJar() {} + + /** Mounts every resource that isn't a class or jar metadata; suspends while it's fetched. */ + static void mount(WebFileSystem files) throws IOException { + double start = Fetch.now(); + WebFileSystem.Mounted mounted = files.mountZip( + ClassPathResources.ROOT, + URL, + "client-" + VERSION + ".jar", + name -> !name.endsWith(".class") && !name.startsWith("META-INF/")); + System.out.println("[Incari] Client jar: " + mounted.files() + " resources mounted, " + + (mounted.cached() ? "from storage" : "downloaded") + ", in " + Math.round(Fetch.now() - start) + + " ms"); + } +} diff --git a/incari-client/files/app-web/src/main/java/incari/app/web/Fetch.java b/incari-client/files/app-web/src/main/java/incari/app/web/Fetch.java new file mode 100644 index 0000000..291bb79 --- /dev/null +++ b/incari-client/files/app-web/src/main/java/incari/app/web/Fetch.java @@ -0,0 +1,155 @@ +package incari.app.web; + +import java.io.IOException; +import java.util.List; +import org.jspecify.annotations.Nullable; +import org.teavm.interop.Async; +import org.teavm.interop.AsyncCallback; +import org.teavm.jso.JSBody; +import org.teavm.jso.JSFunctor; +import org.teavm.jso.JSObject; +import org.teavm.jso.typedarrays.ArrayBuffer; +import org.teavm.jso.typedarrays.Int8Array; + +/** Downloads files from next to the page: before the game starts, and for its resource reloads. */ +final class Fetch { + + private Fetch() {} + + /** + * The whole file at {@code url}. Suspends the calling coroutine until the download finishes: + * must not block the page. + * + * @param hint what to check if it fails, for the error message + */ + static byte[] bytes(String url, String hint) throws IOException { + Outcome outcome = fetch(url); + ArrayBuffer buffer = outcome.buffer(); + if (buffer == null) { + throw new IOException("Couldn't fetch " + url + ": " + outcome.error() + " (" + hint + ")"); + } + return new Int8Array(buffer).copyToJavaArray(); + } + + /** + * The whole file at {@code url}, tried up to {@code attempts} times while it fails for a reason + * that may pass (no connection, a server error, too many requests), waiting longer each time. + * Suspends the calling thread: never the page's own. + * + * @param hint what to check if it fails, for the error message + */ + static byte[] bytesRetrying(String url, String hint, int attempts) throws IOException { + for (int attempt = 1; ; attempt++) { + Outcome outcome = fetch(url); + ArrayBuffer buffer = outcome.buffer(); + if (buffer != null) { + return new Int8Array(buffer).copyToJavaArray(); + } + String error = String.valueOf(outcome.error()); + if (attempt >= attempts || !passing(error)) { + throw new IOException("Couldn't fetch " + url + ": " + error + " (" + hint + ")"); + } + try { + Thread.sleep(500L * attempt); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException("Interrupted fetching " + url, e); + } + } + } + + /** Whether a fetch's failure may pass: anything but a 4xx answer, except time-outs and rate limits. */ + static boolean passing(String error) { + if (!error.startsWith("Error: HTTP 4")) { + return true; + } + return error.equals("Error: HTTP 408") || error.equals("Error: HTTP 429"); + } + + /** + * The whole files at {@code urls}, in their order, downloaded side by side. Suspends the calling + * coroutine until all have finished: must not block the page. + * + * @param hint what to check if one fails, for the error message + */ + static byte[][] all(List urls, String hint) throws IOException { + Outcome[] outcomes = fetchAll(urls.toArray(String[]::new)); + byte[][] files = new byte[outcomes.length][]; + for (int i = 0; i < outcomes.length; i++) { + ArrayBuffer buffer = outcomes[i].buffer(); + if (buffer == null) { + throw new IOException("Couldn't fetch " + urls.get(i) + ": " + outcomes[i].error() + " (" + hint + ")"); + } + files[i] = new Int8Array(buffer).copyToJavaArray(); + } + return files; + } + + /** + * A download's contents, or why it failed. A failure comes back as a value and is thrown here, not + * through {@code AsyncCallback.error}: TeaVM's WebAssembly GC runtime rethrows an error it + * resumes with out of the JavaScript callback as well, after the caller has caught it, and the + * page crashes on the unhandled rejection (probe: {@code app-web/probes/FetchFailureProbe}). + */ + private record Outcome( + @Nullable ArrayBuffer buffer, @Nullable String error) {} + + @Async + private static native Outcome fetch(String url); + + private static void fetch(String url, AsyncCallback callback) { + start( + url, + buffer -> callback.complete(new Outcome(buffer, null)), + message -> callback.complete(new Outcome(null, message))); + } + + @Async + private static native Outcome[] fetchAll(String[] urls); + + private static void fetchAll(String[] urls, AsyncCallback callback) { + Outcome[] outcomes = new Outcome[urls.length]; + if (urls.length == 0) { + callback.complete(outcomes); + return; + } + int[] left = {urls.length}; + for (int i = 0; i < urls.length; i++) { + int index = i; + start( + urls[i], + buffer -> { + outcomes[index] = new Outcome(buffer, null); + if (--left[0] == 0) { + callback.complete(outcomes); + } + }, + message -> { + outcomes[index] = new Outcome(null, message); + if (--left[0] == 0) { + callback.complete(outcomes); + } + }); + } + } + + @JSFunctor + interface Done extends JSObject { + void done(ArrayBuffer buffer); + } + + @JSFunctor + interface Failed extends JSObject { + void failed(String message); + } + + @JSBody( + params = {"url", "done", "failed"}, + script = "fetch(url).then(function(r) {" + + " if (!r.ok) throw new Error('HTTP ' + r.status); return r.arrayBuffer(); })" + + ".then(function(b) { done(b); }, function(e) { failed(String(e)); });") + private static native void start(String url, Done done, Failed failed); + + @JSBody(script = "return performance.now();") + static native double now(); +} diff --git a/incari-client/files/app-web/src/main/java/incari/app/web/GameWorkerMain.java b/incari-client/files/app-web/src/main/java/incari/app/web/GameWorkerMain.java new file mode 100644 index 0000000..c319c91 --- /dev/null +++ b/incari-client/files/app-web/src/main/java/incari/app/web/GameWorkerMain.java @@ -0,0 +1,137 @@ +package incari.app.web; + +import incari.classlib.concurrent.Waits; +import incari.classlib.resources.ClassPathResources; +import incari.client.datafix.DataFixing; +import incari.client.memory.LightCopies; +import incari.client.net.PacketHandoff; +import incari.client.net.PlatformEventLoopGroupHolder; +import incari.client.singleplayer.ChannelLink; +import incari.client.singleplayer.WorldWorker; +import incari.client.startup.CriterionCodecs; +import incari.client.world.BiomeCells; +import incari.client.world.ChunkCompression; +import incari.client.world.Collisions; +import incari.client.world.DensityBranches; +import incari.client.world.GoalFlags; +import incari.client.world.Heights; +import incari.client.world.PositionalRandoms; +import incari.client.world.RemoteTerrain; +import incari.client.world.SpawnCosts; +import incari.client.world.StrongholdRings; +import incari.client.world.SurfaceBuffers; +import incari.client.world.SurfaceWrites; +import incari.platform.api.Platforms; +import incari.platform.web.WebPlatform; +import incari.platform.web.WorkerPlatform; +import incari.platform.web.storage.WebFileSystem; +import java.io.IOException; +import java.util.List; +import org.teavm.jso.JSBody; +import org.teavm.jso.typedarrays.ArrayBuffer; + +/** + * The entry point of a copy of the game in a worker (ADR 0039): {@code WebMain.main(["--worker", + * role])}, as {@code game-worker.ts} starts it. It sets up what the role needs and nothing of the + * client: a file system of its own (filled by the page), the client jar's resources, the headless + * platform, and the settings the page makes that the server's code reads too. + */ +final class GameWorkerMain { + + /** Where the page's storage worker keeps the client jar, from the private file system's root. */ + private static final String CACHED_JAR = ".incari-cache/client-" + ClientJar.VERSION + ".jar"; + + private GameWorkerMain() {} + + /** {@code query}: the page's query string, for the page options read here too. */ + static void main(String role, String query) throws IOException { + LibraryDefaults.apply(); + // A background pool task that blocks gives the pool up, as on the page. + Waits.beforeWait(WebPlatform::beforeWait); + WebFileSystem files = WebFileSystem.installDetached(List.of(ClassPathResources.ROOT)); + int mounted = mountClientJar(files, !"all".equals(option(query, "workerjar"))); + System.out.println("[Incari] Worker (" + role + "): " + mounted + " of the client jar's resources mounted"); + Platforms.install(new WorkerPlatform(WebStorage.DEFAULT, files)); + PlatformEventLoopGroupHolder.useLocalEventLoops(); + // The page's defaults for what the server's code reads as well (WebMain). + DataFixing.buildLazily(); + LightCopies.setEnabled(true); + Collisions.setEnabled(true); + PacketHandoff.setEnabled(true); + StrongholdRings.setEnabled(!"game".equals(option(query, "rings"))); + SpawnCosts.setEnabled(!"game".equals(option(query, "spawncosts"))); + SpawnCosts.setVerify("verify".equals(option(query, "spawncosts"))); + SurfaceWrites.setEnabled(!"game".equals(option(query, "surface"))); + BiomeCells.setEnabled(!"game".equals(option(query, "biomecells"))); + BiomeCells.setVerify("verify".equals(option(query, "biomecells"))); + Heights.setEnabled(!"game".equals(option(query, "heights"))); + GoalFlags.setEnabled(!"game".equals(option(query, "goalflags"))); + DensityBranches.setEnabled(!"game".equals(option(query, "densitychoices"))); + RemoteTerrain.setHelpers(terrainHelpers(option(query, "terrainworkers"))); + CriterionCodecs.setEnabled(!"game".equals(option(query, "criteria"))); + ChunkCompression.setEnabled(!"game".equals(option(query, "deflate"))); + PositionalRandoms.setEnabled(!"game".equals(option(query, "randoms"))); + SurfaceBuffers.setEnabled(!"game".equals(option(query, "surfacebuffers"))); + // ADR 0041's packets a flush per message (?packets=each: one each, as before). + ChannelLink.setBatched(!"each".equals(option(query, "packets"))); + switch (role) { + case "server" -> WorldWorker.run(); + case "terrain" -> RemoteTerrain.serve(); + default -> throw new IllegalArgumentException("No such worker role: " + role); + } + } + + /** + * Mounts the client jar's resources a worker reads, and returns how many. A server (or a + * terrain helper) reads the data packs, the language file and the root files (the version, the + * markers that find the vanilla pack's roots), never the client's assets: those stay out, and + * the jar's buffer is let go once they're copied (ADR 0043). {@code ?workerjar=all} mounts + * every resource, as before. The buffer is a local here so that it isn't held for the + * program's life by {@code main}'s frame, which never returns. + */ + private static int mountClientJar(WebFileSystem files, boolean serverOnly) throws IOException { + ArrayBuffer jar = WorkerPlatform.cachedZip(CACHED_JAR, ClientJar.URL); + return files.mountZip( + ClassPathResources.ROOT, jar, serverOnly ? GameWorkerMain::serverResource : GameWorkerMain::resource); + } + + /** Every resource of the jar: not a class, not its signature. */ + private static boolean resource(String name) { + return !name.endsWith(".class") && !name.startsWith("META-INF/"); + } + + /** A resource a server reads: the data packs, the languages, and the files at the root. */ + private static boolean serverResource(String name) { + return resource(name) + && (name.startsWith("data/") + || name.startsWith("assets/minecraft/lang/") + || name.equals("assets/.mcassetsroot") + || name.indexOf('/') < 0); + } + + /** + * How many terrain helpers singleplayer's server starts (ADR 0042): the page's + * {@code ?terrainworkers=N}, none otherwise. Off by default: no gain was measured where the + * server keeps up, and where the page and the server have two cores between them a helper would + * only take from both. + */ + private static int terrainHelpers(String option) { + if (option.isEmpty()) { + return 0; + } + try { + return Math.min(Integer.parseInt(option), Math.max(1, hardwareConcurrency() - 2)); + } catch (NumberFormatException e) { + return 0; + } + } + + @JSBody(script = "return (self.navigator && self.navigator.hardwareConcurrency) || 1;") + private static native int hardwareConcurrency(); + + /** A parameter of the page's query string, or "" if it has none. */ + @JSBody( + params = {"query", "name"}, + script = "return new URLSearchParams(query).get(name) || '';") + private static native String option(String query, String name); +} diff --git a/incari-client/files/app-web/src/main/java/incari/app/web/LibraryDefaults.java b/incari-client/files/app-web/src/main/java/incari/app/web/LibraryDefaults.java new file mode 100644 index 0000000..adba52b --- /dev/null +++ b/incari-client/files/app-web/src/main/java/incari/app/web/LibraryDefaults.java @@ -0,0 +1,49 @@ +package incari.app.web; + +/** + * Library settings for the page, set as system properties before the libraries read them (they + * read them once, in static initializers). + * + *

Netty's buffers (ADR 0008): + * + *

    + *
  • {@code io.netty.allocator.type=unpooled}: Netty 4.2's default adaptive allocator can't + * start without method handles ({@code ConcurrentSkipListIntObjMultimap} looks up its own + * fallback through one). Unpooled heap buffers are plain {@code byte[]}, which WebAssembly GC + * allocates cheaply, and a page with one thread gains little from pooling. + *
  • {@code io.netty.noUnsafe=true}: there is no {@code Unsafe}; saying so skips the reflective + * probing and the warning about it. With no cleaner, Netty prefers heap buffers; a direct + * buffer, where a caller asks for one, is TeaVM's, in the module's linear memory. + *
  • {@code io.netty.leakDetection.level=disabled}: leak records capture stack traces and rely + * on reference queues, costly here; leaks are found on the desktop build. + *
  • {@code io.netty.machineId} and {@code io.netty.processId}: what Netty's channel ids + * ({@code DefaultChannelId}) are made from, otherwise found from the network interfaces' MAC + * addresses and the process handle, neither of which a page has. Singleplayer's in-memory + * channels are the first to use them. A fixed machine and process are fine: the ids only + * have to differ within the page, which the counter and the time in each id see to. + *
+ * + *

JOML: {@code joml.format=false}. JOML's {@code Options} builds a {@code DecimalFormat} from a + * pattern TeaVM's parser rejects (a leading space), which failed the first {@code org.joml.Math} + * call (vertex sorting by distance); without it JOML formats with the locale's number format. + */ +final class LibraryDefaults { + + private LibraryDefaults() {} + + static void apply() { + setDefault("io.netty.allocator.type", "unpooled"); + setDefault("io.netty.noUnsafe", "true"); + setDefault("io.netty.leakDetection.level", "disabled"); + setDefault("io.netty.machineId", "00:00:00:00:00:00:00:01"); + setDefault("io.netty.processId", "1"); + setDefault("joml.format", "false"); + } + + /** Keeps a value set before, so a development page can still choose another. */ + private static void setDefault(String key, String value) { + if (System.getProperty(key) == null) { + System.setProperty(key, value); + } + } +} diff --git a/incari-client/files/app-web/src/main/java/incari/app/web/LoaderPage.java b/incari-client/files/app-web/src/main/java/incari/app/web/LoaderPage.java new file mode 100644 index 0000000..579c5c5 --- /dev/null +++ b/incari-client/files/app-web/src/main/java/incari/app/web/LoaderPage.java @@ -0,0 +1,36 @@ +package incari.app.web; + +import org.jspecify.annotations.Nullable; +import org.teavm.jso.JSBody; + +/** + * The host page's loader ({@code src/main/ts/boot.ts}), as the game's start-up sees it: the + * steps it shows under the progress bar, and what the build manifest says about the build. Without + * the loader (an experiment's page), every call does nothing. + */ +final class LoaderPage { + + private LoaderPage() {} + + /** Shows a start-up step on the loading screen, and logs it. */ + static void status(String text) { + System.out.println("[Incari] Loading: " + text); + show(text); + } + + @JSBody(params = "text", script = "var loader = window.incariLoader; if (loader) loader.status(text);") + private static native void show(String text); + + /** The asset pack's URL (versioned by its hash) from the build manifest, or null if the build has none. */ + @JSBody(script = "var build = window.incariBuild; return build && build.pack ? build.pack : null;") + static native @Nullable String packUrl(); + + /** + * The build's id from the build manifest (a hash over its files), or null without a manifest or + * for a development build, whose id names no particular files. + */ + @JSBody( + script = "var build = window.incariBuild;" + + " return build && build.id && build.id !== 'development' ? build.id : null;") + static native @Nullable String buildId(); +} diff --git a/incari-client/files/app-web/src/main/java/incari/app/web/WebAssets.java b/incari-client/files/app-web/src/main/java/incari/app/web/WebAssets.java new file mode 100644 index 0000000..d297a70 --- /dev/null +++ b/incari-client/files/app-web/src/main/java/incari/app/web/WebAssets.java @@ -0,0 +1,165 @@ +package incari.app.web; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import incari.client.audio.RemoteSounds; +import incari.client.resources.RemoteAssets; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * The game's files from the asset index, laid out by name under the assets directory (the layout + * the game reads when it's given no {@code --assetIndex}), where the vanilla pack finds them. + * + *

The index is hundreds of megabytes, so little is downloaded up front. At start: the sound list + * ({@code sounds.json}), the pack's metadata ({@code pack.mcmeta}, which lists the languages and + * is read before the first reload) and the built-in packs' zips (ADR 0055). The sounds get an empty placeholder each, so the game knows they + * exist, and {@link RemoteSounds} fetches one the first time it plays (ADR 0013). The + * Unicode font and the selected language are fetched by {@link RemoteAssets} before + * each resource reload that reads them (ADR 0037). The page gets all of it from next to itself: the + * index at {@value #INDEX_URL} and its objects under {@value #OBJECTS_URL}, which the dev server + * serves from {@code ./incari assets}' download and {@code ./incari build} copies into its folder. + * + *

Not the launcher's layout with an index: the game reads that through its own link file + * system, which TeaVM's {@code java.nio.file} can't walk. + */ +final class WebAssets { + + static final String INDEX_URL = "asset-index.json"; + static final String OBJECTS_URL = "assets/objects/"; + + /** Fetched before the game starts, because it reads them while loading. */ + private static final List AT_START = List.of("minecraft/sounds.json", "pack.mcmeta"); + + /** + * The built-in packs (Programmer Art, High Contrast; 0.7 MB), fetched at start too: the pack + * repository lists them once, before the first reload (ADR 0055). + */ + private static final List BUILT_IN_PACKS = List.of("minecraft/resourcepacks/"); + + /** Tries for each sound's download before it plays silent (and is asked for again later). */ + private static final int SOUND_ATTEMPTS = 3; + + private static final String HINT = "is the dev server serving the assets?"; + + private WebAssets() {} + + /** + * Stores the files read at start and a placeholder for every sound, and installs the fetchers + * for the rest. Without an asset index the page runs silent and in + * English only. + */ + static void install(String assetsDirectory) { + double start = Fetch.now(); + byte[] indexFile; + try { + indexFile = Fetch.bytes(INDEX_URL, "has ./incari assets downloaded the asset index?"); + } catch (IOException e) { + System.out.println("[Incari] No asset index, so no sounds: " + e.getMessage()); + return; + } + try { + File root = new File(assetsDirectory); + JsonObject objects = JsonParser.parseString(new String(indexFile, StandardCharsets.UTF_8)) + .getAsJsonObject() + .getAsJsonObject("objects"); + Map sounds = new HashMap<>(); + Map others = new HashMap<>(); + for (Map.Entry entry : objects.entrySet()) { + String name = entry.getKey(); + String hash = entry.getValue().getAsJsonObject().get("hash").getAsString(); + if (name.endsWith(".ogg")) { + sounds.put(name, hash); + File placeholder = new File(root, name); + if (!placeholder.exists()) { + write(placeholder, new byte[0]); + } + } else { + others.put(name, hash); + } + } + Index index = new Index(root, others); + index.fetch(AT_START); + try { + index.fetch(BUILT_IN_PACKS); + } catch (IOException e) { + // Sounds and languages still work; the Resource Packs screen lists no built-in packs. + System.out.println("[Incari] No built-in resource packs: " + e.getMessage()); + } + RemoteSounds.install(name -> { + String hash = sounds.get(name); + // A sound fetched as it first plays meets whatever the network is doing then. + return hash == null ? null : Fetch.bytesRetrying(objectUrl(hash), HINT, SOUND_ATTEMPTS); + }); + RemoteAssets.install(index::fetch); + System.out.println("[Incari] Assets: " + sounds.size() + " sounds listed in " + + Math.round(Fetch.now() - start) + " ms"); + } catch (IOException | RuntimeException e) { + System.out.println("[Incari] Couldn't set up the assets, so no sounds: " + e); + } + } + + /** The index's files other than sounds, written under {@code root} as they're fetched. */ + private record Index(File root, Map hashes) { + + /** + * Downloads, side by side, each of {@code assets} (names, or folders ending in {@code /}) + * that isn't written yet, and writes it. Suspends the calling coroutine: the entry point at + * start, a background thread before a reload. + */ + void fetch(List assets) throws IOException { + double start = Fetch.now(); + List names = new ArrayList<>(); + List urls = new ArrayList<>(); + for (Map.Entry entry : hashes.entrySet()) { + String name = entry.getKey(); + if (wanted(assets, name) && !new File(root, name).exists()) { + names.add(name); + urls.add(objectUrl(entry.getValue())); + } + } + if (names.isEmpty()) { + return; + } + byte[][] files = Fetch.all(urls, HINT); + long bytes = 0; + for (int i = 0; i < files.length; i++) { + write(new File(root, names.get(i)), files[i]); + bytes += files[i].length; + } + System.out.println("[Incari] Assets: fetched " + names.size() + " files (" + bytes / 1024 + " KB) in " + + Math.round(Fetch.now() - start) + " ms"); + } + + private static boolean wanted(List assets, String name) { + for (String asset : assets) { + if (asset.endsWith("/") ? name.startsWith(asset) : name.equals(asset)) { + return true; + } + } + return false; + } + } + + private static String objectUrl(String hash) { + return OBJECTS_URL + hash.substring(0, 2) + "/" + hash; + } + + private static void write(File file, byte[] contents) throws IOException { + File parent = file.getParentFile(); + if (parent != null && !parent.isDirectory() && !parent.mkdirs()) { + throw new IOException("Can't create " + parent); + } + try (OutputStream out = new FileOutputStream(file)) { + out.write(contents); + } + } +} diff --git a/incari-client/files/app-web/src/main/java/incari/app/web/WebCredits.java b/incari-client/files/app-web/src/main/java/incari/app/web/WebCredits.java new file mode 100644 index 0000000..6fdfcd8 --- /dev/null +++ b/incari-client/files/app-web/src/main/java/incari/app/web/WebCredits.java @@ -0,0 +1,39 @@ +package incari.app.web; + +import incari.client.credits.Credit; +import incari.client.credits.Credits; +import java.net.URI; + +/** + * What the browser build contains that the desktop doesn't, for the credits screen: TeaVM's + * runtime and class library, ThreeTen Backport, which TeaVM maps {@code java.time} onto, and JZlib, + * the deflate engine under TeaVM's zip classes. All are compiled into the build's WebAssembly. + */ +final class WebCredits { + + private WebCredits() {} + + static void install() { + Credits.add(new Credit( + "TeaVM", + null, + "Alexey Andreev and contributors", + "Apache-2.0", + Credits.APACHE_2, + URI.create("https://github.com/konsoletyper/teavm"))); + Credits.add(new Credit( + "ThreeTen Backport", + null, + "Stephen Colebourne and Michael Nascimento Santos", + "BSD-3-Clause", + Credits.BSD_3_CLAUSE, + URI.create("https://github.com/ThreeTen/threetenbp"))); + Credits.add(new Credit( + "JZlib", + null, + "ymnk, JCraft, Inc.", + "BSD-3-Clause", + Credits.BSD_3_CLAUSE, + URI.create("https://github.com/ymnk/jzlib"))); + } +} diff --git a/incari-client/files/app-web/src/main/java/incari/app/web/WebMain.java b/incari-client/files/app-web/src/main/java/incari/app/web/WebMain.java new file mode 100644 index 0000000..cf9e9f9 --- /dev/null +++ b/incari-client/files/app-web/src/main/java/incari/app/web/WebMain.java @@ -0,0 +1,388 @@ +package incari.app.web; + +import com.mojang.renderpearl.api.device.GpuBackend; +import incari.app.web.headless.HeadlessBackend; +import incari.classlib.concurrent.Waits; +import incari.classlib.resources.ClassPathResources; +import incari.client.TickPacing; +import incari.client.datafix.DataFixing; +import incari.client.gui.HudCache; +import incari.client.memory.LightCopies; +import incari.client.memory.PackedUnihex; +import incari.client.modules.IncariModules; +import incari.client.net.PacketHandoff; +import incari.client.net.PlatformEventLoopGroupHolder; +import incari.client.online.IncariOnline; +import incari.client.online.UpdateNotice; +import incari.client.particle.AmbientParticles; +import incari.client.particle.ParticleBudget; +import incari.client.particle.ParticleInstancing; +import incari.client.particle.ParticleLight; +import incari.client.platform.GraphicsBackends; +import incari.client.platform.OnlineServices; +import incari.client.profile.PlayerName; +import incari.client.profiler.Profiling; +import incari.client.render.AnimatedSprites; +import incari.client.render.EntityOcclusion; +import incari.client.render.GlyphQuads; +import incari.client.render.GraphUpdates; +import incari.client.render.QuadSort; +import incari.client.render.SignLines; +import incari.client.render.SpriteCache; +import incari.client.render.TerrainVertexFormat; +import incari.client.render.TextLayouts; +import incari.client.render.TintBlend; +import incari.client.render.VertexMath; +import incari.client.render.entity.ModelBatches; +import incari.client.render.entity.OpaqueSkins; +import incari.client.render.mesher.ChestBaking; +import incari.client.render.mesher.MeshTableCache; +import incari.client.render.mesher.Meshing; +import incari.client.render.terrain.TerrainDrawLists; +import incari.client.singleplayer.ChannelLink; +import incari.client.singleplayer.QuickWorlds; +import incari.client.singleplayer.WorkerWorlds; +import incari.client.startup.CriterionCodecs; +import incari.client.startup.DeferredModels; +import incari.client.startup.LoadingFade; +import incari.client.tier.DeviceTier; +import incari.client.world.BiomeCells; +import incari.client.world.ChunkCompression; +import incari.client.world.Collisions; +import incari.client.world.DensityBranches; +import incari.client.world.GoalFlags; +import incari.client.world.Heights; +import incari.client.world.PositionalRandoms; +import incari.client.world.SpawnCosts; +import incari.client.world.StrongholdRings; +import incari.client.world.SurfaceBuffers; +import incari.client.world.SurfaceWrites; +import incari.platform.api.Platforms; +import incari.platform.web.WebPlatform; +import incari.platform.web.storage.WebFileSystem; +import incari.render.webgl2.WebGl2Backend; +import incari.render.webgl2.shaders.ShaderManifest; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Random; +import org.teavm.jso.JSBody; + +/** + * The browser build's entry point: opens the stored files ({@link WebFileSystem}), mounts the + * client jar ({@link ClientJar}) and asset pack ({@link AssetPack}), loads the translated shaders + * ({@link WebShaders}), installs {@link WebPlatform} and the WebGL2 backend, then starts the + * game's {@code Main}. Each step shows on the loading screen ({@link LoaderPage}). + * + *

Page options, for development: + * + *

    + *
  • {@code ?renderer=headless}: run without drawing. + *
  • {@code ?shaders=eager}: link every WebGL program at start-up, so all compile errors show + * at once. + *
  • {@code ?server=ws://...}: join that server once started. {@code ?name=...}: the offline + * name. + *
  • {@code ?world=}: open that singleplayer world; with {@code &seed=}, create it + * first (the singleplayer benchmark). + *
  • {@code ?share=}: share the open world on that relay. {@code ?shared=|}: + * join a shared world (ADR 0062). + *
  • {@code ?options=}: start with that options file from beside the page (the + * screenshot diffs pin their options this way). + *
  • {@code ?profile}: collect frame measurements from the start, for the benchmark. + * {@code ?overlay}: show the profiler's overlay. + *
  • {@code ?drawcensus}: log each pipeline's draws a frame every 600 frames. + * {@code ?gpucensus}: the same for GPU time. + *
  • {@code ?tier=potato|standard|high}: the device tier budgets scale by (particles, largest + * atlas, terrain heaps, decoded sounds). Standard is the default. + *
  • {@code ?mesher=inline|vanilla|verify}: mesh terrain on the page's thread, with the game's + * compiler, or both and compare, instead of in Incari's workers. + *
+ * + *

To compare an Incari change with the game's own way: + * + *

    + *
  • Memory and start-up: {@code ?text=game} (lay out world text every frame), + * {@code ?quads=game}, {@code ?copies=all} (keep a copy of every WebGL buffer), + * {@code ?models=now} (load models before the title screen), {@code ?sprites=off} (decode + * every sprite). + *
  • {@code ?multidraw=off}: one draw per terrain section, not WEBGL_multi_draw (ADR 0022). + *
  • ADR 0027: {@code ?uniforms=each} (upload each uniform write alone), {@code ?rebase=off} + * (move the vertex attributes for each base vertex). + *
  • ADR 0030: {@code ?sort=game}, {@code ?tint=game}, {@code ?items=game} (no instancing), + * {@code ?skins=game}, {@code ?drawlists=game}, {@code ?faces=all} (draw back faces), + * {@code ?animations=all} (animate unseen sprites), {@code ?hud=live} (draw the HUD every + * frame), {@code ?chests=game} (closed chests as block entities). + *
  • ADR 0031: {@code ?ambient=game}, {@code ?glyphs=game}, {@code ?signs=game} (submit blank + * lines), {@code ?graph=game} (full occlusion update at once), {@code ?particlelight=frame} + * (read particle light every frame). + *
+ */ +public final class WebMain { + + /** The background pool's least share of a frame while it has work (ADR 0035). */ + private static final double DEFAULT_POOL_FLOOR_MILLIS = 4.0; + + private WebMain() {} + + public static void main(String[] args) throws IOException { + if (args.length >= 2 && args[0].equals("--worker")) { + // A copy of the game in a worker (ADR 0039): singleplayer's server, never the client. + // The page's query comes third, for the page options the server's code reads too. + GameWorkerMain.main(args[1], args.length > 2 ? args[2] : ""); + return; + } + // Before any library reads them: Netty and JOML read their settings once, at class load. + LibraryDefaults.apply(); + // This thread becomes the game's render thread: its waits hold back the page's frame, so + // they're timed for the frame monitor. + Waits.watch(Thread.currentThread()); + // A background pool task that blocks gives the pool up, so what it waits for can run. + Waits.beforeWait(WebPlatform::beforeWait); + // Before anything touches a file. Dropped files, the jar's resources and the sound + // placeholders (rewritten from the asset index on every load) are never stored. + LoaderPage.status("Opening saved files"); + WebFileSystem files = WebFileSystem.install(List.of( + WebPlatform.DROP_DIRECTORY, + ClassPathResources.ROOT, + AssetPack.ROOT, + WebStorage.DEFAULT.assetsDirectory())); + LoaderPage.status("Loading game files"); + ClientJar.mount(files); + LoaderPage.status("Loading textures"); + boolean pack = AssetPack.mount(files); + if (pack && !"off".equals(option("sprites"))) { + // The vanilla sprites the build decoded, with their mip levels (ADR 0026). + SpriteCache.install(Path.of(AssetPack.ROOT, "sprites.bin")); + } + LoaderPage.status("Loading sounds"); + WebAssets.install(WebStorage.DEFAULT.assetsDirectory()); + Platforms.install(new WebPlatform(WebStorage.DEFAULT, files)); + WebCredits.install(); + // Realms is stripped from the browser build (tools/survey/rules.txt). + OnlineServices.disableRealms(); + // Nor does it call Mojang's other services: no discovery, profile, key or telemetry requests. + OnlineServices.disableMojang(); + // No sockets, so no selector for Netty's event loops to wait on (ADR 0008). + PlatformEventLoopGroupHolder.useLocalEventLoops(); + // Terrain meshing (ADR 0023): Incari's mesher in Web Workers, writing the compact + // terrain vertex. ?mesher=inline meshes on the page's thread instead; ?mesher=vanilla uses + // the game's compiler and vertex format; ?mesher=verify meshes both ways and compares. + String mesher = option("mesher"); + switch (mesher) { + case "vanilla" -> Meshing.configure(Meshing.Mode.VANILLA, false); + case "verify" -> Meshing.configure(Meshing.Mode.VERIFY, false); + default -> { + TerrainVertexFormat.useCompact(); + Meshing.configure(Meshing.Mode.INCARI, !"inline".equals(mesher)); + // Translucent layers in an order that holds from every camera are never re-sorted + // (ADR 0034); ?resort=game sorts them all as the game does. + Meshing.setFixedOrder(!"game".equals(option("resort"))); + // Snapshots read each section's copied blocks directly (ADR 0034); + // ?snapshotreads=game reads them a block at a time through the region. + Meshing.setDirectReads(!"game".equals(option("snapshotreads"))); + // The mesher's tables kept from start to start (ADR 0032); ?meshtables=build builds + // them every time. + String build = LoaderPage.buildId(); + if (build != null && !"build".equals(option("meshtables"))) { + MeshTableCache.enable(Path.of("/incari/cache/mesher-tables.bin"), build); + } + // Closed chests meshed into terrain (ADR 0030); ?chests=game draws them the game's way. + if (!"game".equals(option("chests"))) { + ChestBaking.enable(); + } + } + } + // Entities, particles and text (ADR 0024): ?entityculling=off draws entities no visible + // section holds, and ?instancing=off entity models the game's way, to compare; ?particles=potato, + // standard or high picks the particle cap whatever the device's tier. + EntityOcclusion.setEnabled(!"off".equals(option("entityculling"))); + if (!"off".equals(option("instancing")) && !"headless".equals(option("renderer"))) { + ModelBatches.enable(); + // Particles too (ADR 0032); ?particlequads=game builds their vertices as the game does. + if (!"game".equals(option("particlequads"))) { + ParticleInstancing.enable(); + } + } + // The device's tier (not yet picked from the device): ?tier=potato, standard (the default) or high. + DeviceTier tier = DeviceTier.named(option("tier")); + DeviceTier.set(tier == null ? DeviceTier.STANDARD : tier); + ParticleBudget.setTier(DeviceTier.named(option("particles"))); + // The memory diet (ADR 0025): the data fixer is built only if something old arrives. + DataFixing.buildLazily(); + // Start-up (ADR 0026): the loading screen fades in half a second, not two, and the + // title screen shows before the block, item and entity models are loaded. + LoadingFade.set(250); + if (!"now".equals(option("models"))) { + DeferredModels.enable(); + } + // The memory diet's reuse of world text and its baked-quad writer: ?text=game and + // ?quads=game take the game's own paths, to compare. + TextLayouts.setEnabled(!"game".equals(option("text"))); + VertexMath.setQuadsEnabled(!"game".equals(option("quads"))); + // ADR 0027's changes, each with the game's (or ADR 0025's) way to compare. + QuadSort.setEnabled(!"game".equals(option("sort"))); + ModelBatches.setItemsEnabled(!"game".equals(option("items"))); + OpaqueSkins.setEnabled(!"game".equals(option("skins"))); + TintBlend.setEnabled(!"game".equals(option("tint"))); + // ADR 0030's terrain draw list and sprite animation, each with the game's way to compare. + TerrainDrawLists.setEnabled(!"game".equals(option("drawlists"))); + TerrainDrawLists.setFacingCulling(!"all".equals(option("faces"))); + AnimatedSprites.setEnabled(!"all".equals(option("animations"))); + HudCache.setEnabled(!"live".equals(option("hud"))); + // Development: ?modules=minimap,coordinates (or all) turns those modules on at start. + if (!option("modules").isEmpty()) { + IncariModules.startWith(Arrays.asList(option("modules").split(","))); + } + // ADR 0031's changes, each with the game's way to compare. + AmbientParticles.setEnabled(!"game".equals(option("ambient"))); + GlyphQuads.setEnabled(!"game".equals(option("glyphs"))); + SignLines.setEnabled(!"game".equals(option("signs"))); + GraphUpdates.setEnabled(!"game".equals(option("graph"))); + ParticleLight.setAcrossFrames(!"frame".equals(option("particlelight"))); + // ADR 0032's catch-up ticks spread over frames; ?ticks=game runs them back to back. + TickPacing.setEnabled(!"game".equals(option("ticks"))); + // The background pool's least share of a frame while it has work (ADR 0035); + // ?poolfloor= to compare, 1 being the old minimum. + String poolFloor = option("poolfloor"); + WebPlatform.setPoolFloor(poolFloor.isEmpty() ? DEFAULT_POOL_FLOOR_MILLIS : Double.parseDouble(poolFloor)); + Collisions.setEnabled(!"game".equals(option("collisions"))); + // Singleplayer's server on the page (?singleplayer=page); the worker reads the same options. + StrongholdRings.setEnabled(!"game".equals(option("rings"))); + SpawnCosts.setEnabled(!"game".equals(option("spawncosts"))); + SpawnCosts.setVerify("verify".equals(option("spawncosts"))); + // ADR 0041's world generation and loading changes, each with the game's way to compare. + SurfaceWrites.setEnabled(!"game".equals(option("surface"))); + BiomeCells.setEnabled(!"game".equals(option("biomecells"))); + BiomeCells.setVerify("verify".equals(option("biomecells"))); + Heights.setEnabled(!"game".equals(option("heights"))); + CriterionCodecs.setEnabled(!"game".equals(option("criteria"))); + // Saved chunks deflated at zlib's fastest level (?deflate=game: its default). + ChunkCompression.setEnabled(!"game".equals(option("deflate"))); + // The surface rules' positional randoms drawn without making them (?randoms=game: made). + PositionalRandoms.setEnabled(!"game".equals(option("randoms"))); + SurfaceBuffers.setEnabled(!"game".equals(option("surfacebuffers"))); + // The Unicode font's glyphs packed into arrays (?unihex=game: an object each, as the game keeps them). + PackedUnihex.setEnabled(!"game".equals(option("unihex"))); + // ADR 0042's lazy range choices (the server worker reads the same option). + GoalFlags.setEnabled(!"game".equals(option("goalflags"))); + DensityBranches.setEnabled(!"game".equals(option("densitychoices"))); + // ADR 0041's packets a flush per message (?packets=each: one each, as before). + ChannelLink.setBatched(!"each".equals(option("packets"))); + // ADR 0041's region files left in place for the worker (?inplace=off: handed over whole, as before). + WebFileSystem.setInPlaceHandOver(!"off".equals(option("inplace"))); + // ADR 0032's light maps brought up to date in place; ?light=game copies them as the game does. + LightCopies.setEnabled(!"game".equals(option("light"))); + LightCopies.setVerify("verify".equals(option("light"))); + // ADR 0033: packets their handlers only hand to the game's thread queued without the round + // trip; ?handoff=game calls the handler on the network's thread first, as the game does. + PacketHandoff.setEnabled(!"game".equals(option("handoff"))); + // ADR 0039: singleplayer's server in a worker; ?singleplayer=page runs it on the page, as ADR 0038 did. + WorkerWorlds.setEnabled(!"page".equals(option("singleplayer"))); + WebGl2Backend.uploadEachUniformWrite("each".equals(option("uniforms"))); + WebGl2Backend.movePointersForQuadDraws("off".equals(option("rebase"))); + // Development: ?drawcensus logs each pipeline's draws a frame to the console. + WebGl2Backend.countDrawsByPipeline(present("drawcensus")); + // Development: ?gpucensus logs each pipeline's GPU time a frame (ADR 0031). + WebGl2Backend.timeDrawsByPipeline(present("gpucensus")); + // ?copies=all: every WebGL buffer keeps the game's copy, as before ADR 0025, to compare. + WebGl2Backend.keepAllCopies("all".equals(option("copies"))); + if ("headless".equals(option("renderer"))) { + GraphicsBackends.install(preference -> new GpuBackend[] {new HeadlessBackend()}); + GraphicsBackends.setRendering(false); + } else { + ShaderManifest shaders = WebShaders.load(pack); + boolean eager = "eager".equals(option("shaders")); + boolean multiDraw = !"off".equals(option("multidraw")); + GraphicsBackends.install(preference -> + new GpuBackend[] {new WebGl2Backend(WebPlatform.CANVAS_ID, shaders, eager, multiDraw)}); + } + if (present("profile")) { + Profiling.collect(true); + } + if (present("overlay")) { + Profiling.showOverlay(true); + } + String options = option("options"); + if (!options.isEmpty()) { + // Development: start with these options (the screenshot-diff harness pins its scenes' + // options this way), in place of whatever the game directory holds. + Path gameDirectory = Path.of(WebStorage.DEFAULT.gameDirectory()); + Files.createDirectories(gameDirectory); + Files.write( + gameDirectory.resolve("options.txt"), Fetch.bytes(options, "is the page serving " + options + "?")); + } + if (present("online")) { + // Development: Incari accounts against another service (ADR 0058), ?online=ws://localhost:8080/v1/ws; + // ?online= (empty) turns them off. + IncariOnline.useUrl(option("online")); + } + if ("on".equals(option("updates"))) { + // Testing: the title screen's update notice in a dev build too, ?updates=on (with + // ?online= against tools/onlinedev --release ). + UpdateNotice.force(true); + } + String name = option("name"); + if (!name.isEmpty() || !option("server").isEmpty()) { + // The page names the player, or joins a server straight away: no Edit Profile first. + PlayerName.fixAtLaunch(); + } + List arguments = new ArrayList<>(Arrays.asList(new String[] { + "--version", + ClientJar.VERSION, + "--versionType", + "incari-web", + "--gameDir", + WebStorage.DEFAULT.gameDirectory(), + "--assetsDir", + WebStorage.DEFAULT.assetsDirectory(), + "--accessToken", + "0", + // No profile, user property or chat key requests to Mojang (OnlineServices). + "--offlineDeveloperMode", + "--username", + // A first start suggests a name of its own, as Eagler clients do; Edit Profile keeps it. + name.isEmpty() ? PlayerName.suggest(new Random()) : name + })); + String server = option("server"); + if (!server.isEmpty()) { + // Straight into a server, as a launcher's quick play does. + arguments.addAll(List.of("--quickPlayMultiplayer", server)); + String via = option("via"); + if (!via.isEmpty() && !incari.client.net.ServerVersions.setQuickPlay(server, via)) { + System.err.println("Not a Via choice: ?via=" + via + " (off, auto or a release)"); + } + } + String world = option("world"); + String seed = option("seed"); + if (!world.isEmpty() && !seed.isEmpty()) { + // The singleplayer benchmark's world: made from the seed at the title screen, or opened. + QuickWorlds.createAtTitle(world, Long.parseLong(seed)); + } else if (!world.isEmpty()) { + arguments.addAll(List.of("--quickPlaySingleplayer", world)); + } + String sharedWorld = option("shared"); + int bar = sharedWorld.lastIndexOf('|'); + if (bar > 0) { + // The shared-world check's guest (ADR 0062): joins a shared world from the title screen. + QuickWorlds.joinSharedAtTitle(sharedWorld.substring(0, bar), sharedWorld.substring(bar + 1)); + } + String share = option("share"); + if (!share.isEmpty()) { + // The shared-world check's host (ADR 0062): the world shared on this relay once it's open. + incari.client.singleplayer.WorkerWorlds.shareWhenOpen(share); + } + LoaderPage.status("Starting the game"); + net.minecraft.client.main.Main.main(arguments.toArray(String[]::new)); + } + + /** A query parameter of the page's URL, or "" if it has none. */ + @JSBody(params = "name", script = "return new URLSearchParams(location.search).get(name) || '';") + private static native String option(String name); + + /** Whether the page's URL has a query parameter, with or without a value. */ + @JSBody(params = "name", script = "return new URLSearchParams(location.search).has(name);") + private static native boolean present(String name); +} diff --git a/incari-client/files/app-web/src/main/java/incari/app/web/WebShaders.java b/incari-client/files/app-web/src/main/java/incari/app/web/WebShaders.java new file mode 100644 index 0000000..29536d4 --- /dev/null +++ b/incari-client/files/app-web/src/main/java/incari/app/web/WebShaders.java @@ -0,0 +1,34 @@ +package incari.app.web; + +import incari.render.webgl2.shaders.ShaderManifest; +import java.io.IOException; +import java.nio.charset.StandardCharsets; + +/** + * The game's shaders as the build translated them for WebGL2 ({@code tools/shaders}). They're + * translated Mojang files, so like the client jar they're kept beside the page, never built into + * it: in the asset pack ({@link AssetPack}), or as the manifest {@code :app-web:shaders} wrote, which + * {@code :app-web:serve} offers at {@value #URL}. + */ +final class WebShaders { + + static final String URL = "shaders.json"; + + private WebShaders() {} + + /** + * The translated shaders: from the asset pack if one is mounted, else fetched from beside + * the page, as an experiment's build without a pack has them. + */ + static ShaderManifest load(boolean fromPack) throws IOException { + double start = Fetch.now(); + byte[] bytes = fromPack ? AssetPack.read(URL) : null; + if (bytes == null) { + bytes = Fetch.bytes(URL, "is the development server serving the shaders? run ./gradlew :app-web:shaders"); + } + ShaderManifest manifest = ShaderManifest.parse(new String(bytes, StandardCharsets.UTF_8)); + System.out.println("[Incari] Shaders: " + manifest.stages().size() + " translated stages loaded " + + (fromPack ? "from the asset pack " : "") + "in " + Math.round(Fetch.now() - start) + " ms"); + return manifest; + } +} diff --git a/incari-client/files/app-web/src/main/java/incari/app/web/WebStorage.java b/incari-client/files/app-web/src/main/java/incari/app/web/WebStorage.java new file mode 100644 index 0000000..da2a310 --- /dev/null +++ b/incari-client/files/app-web/src/main/java/incari/app/web/WebStorage.java @@ -0,0 +1,13 @@ +package incari.app.web; + +import incari.platform.api.storage.PlatformStorage; +import org.jspecify.annotations.Nullable; + +/** Where the browser build keeps its files: under {@code WebFileSystem.ROOT}, which survives a reload. */ +record WebStorage( + String gameDirectory, + String assetsDirectory, + @Nullable String assetIndex) implements PlatformStorage { + + static final WebStorage DEFAULT = new WebStorage("/incari/game", "/incari/assets", null); +} diff --git a/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessBackend.java b/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessBackend.java new file mode 100644 index 0000000..f0f80ae --- /dev/null +++ b/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessBackend.java @@ -0,0 +1,36 @@ +package incari.app.web.headless; + +import com.mojang.renderpearl.api.device.GpuBackend; +import com.mojang.renderpearl.api.device.GpuDebugOptions; +import com.mojang.renderpearl.api.device.GpuDevice; +import org.jspecify.annotations.Nullable; + +/** + * A graphics backend that draws nothing, for running the game before the browser has a renderer + * (as before the WebGL2 backend existed). Its device accepts every call and keeps no GPU state; + * the entry point also switches the frame's render step off, so the game only ticks. + */ +public final class HeadlessBackend implements GpuBackend { + + @Override + public String getName() { + return "Headless"; + } + + @Override + public void loadLibrary() {} + + @Override + public void unloadLibrary() {} + + /** The canvas is the window; the handle only has to be non-zero. */ + @Override + public long createWindow(@Nullable String title, int width, int height, long flags) { + return 1L; + } + + @Override + public GpuDevice createDevice(GpuDebugOptions debugOptions) { + return new HeadlessDevice(); + } +} diff --git a/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessBuffer.java b/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessBuffer.java new file mode 100644 index 0000000..29d760d --- /dev/null +++ b/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessBuffer.java @@ -0,0 +1,72 @@ +package incari.app.web.headless; + +import com.mojang.renderpearl.api.buffers.GpuBuffer; +import com.mojang.renderpearl.api.buffers.GpuBufferSlice; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import org.jspecify.annotations.Nullable; +import org.lwjgl.system.MemoryUtil; + +/** + * A buffer as plain memory, allocated when first mapped or written: the game writes uniforms and + * vertices into mapped buffers and sometimes reads them back, so that has to work even with + * nothing to draw. The memory comes from LWJGL's {@code MemoryUtil}, since the game treats mapped + * memory as native ({@code memCopy}, {@code memAddress}); closing frees it. + */ +final class HeadlessBuffer implements GpuBuffer { + + private final @GpuBuffer.Usage int usage; + private final long size; + private @Nullable ByteBuffer memory; + private boolean closed; + + HeadlessBuffer(@GpuBuffer.Usage int usage, long size) { + this.usage = usage; + this.size = size; + } + + @Override + public long size() { + return size; + } + + @Override + public @GpuBuffer.Usage int usage() { + return usage; + } + + @Override + public boolean isClosed() { + return closed; + } + + @Override + public GpuBufferSlice.MappedView map(long offset, long length, boolean read, boolean write) { + ByteBuffer view = memory().duplicate().order(ByteOrder.nativeOrder()); + view.limit(Math.toIntExact(offset + length)).position(Math.toIntExact(offset)); + return new GpuBufferSlice.MappedView( + slice(offset, length), view.slice().order(ByteOrder.nativeOrder()), () -> {}); + } + + void write(long offset, ByteBuffer data) { + ByteBuffer target = memory().duplicate(); + target.position(Math.toIntExact(offset)); + target.put(data.duplicate()); + } + + private ByteBuffer memory() { + ByteBuffer current = memory; + if (current == null) { + current = MemoryUtil.memCalloc(Math.toIntExact(size)).order(ByteOrder.nativeOrder()); + memory = current; + } + return current; + } + + @Override + public void close() { + closed = true; + MemoryUtil.memFree(memory); + memory = null; + } +} diff --git a/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessDevice.java b/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessDevice.java new file mode 100644 index 0000000..7c1f8f0 --- /dev/null +++ b/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessDevice.java @@ -0,0 +1,150 @@ +package incari.app.web.headless; + +import com.mojang.renderpearl.api.GpuFormat; +import com.mojang.renderpearl.api.buffers.GpuBuffer; +import com.mojang.renderpearl.api.commands.CommandEncoder; +import com.mojang.renderpearl.api.commands.GpuQueryPool; +import com.mojang.renderpearl.api.device.DeviceFeatures; +import com.mojang.renderpearl.api.device.DeviceInfo; +import com.mojang.renderpearl.api.device.DeviceLimits; +import com.mojang.renderpearl.api.device.DeviceType; +import com.mojang.renderpearl.api.device.GpuDevice; +import com.mojang.renderpearl.api.device.GpuSurface; +import com.mojang.renderpearl.api.device.HintsAndWorkarounds; +import com.mojang.renderpearl.api.pipeline.CompiledRenderPipeline; +import com.mojang.renderpearl.api.pipeline.RenderPipeline; +import com.mojang.renderpearl.api.pipeline.ShaderSource; +import com.mojang.renderpearl.api.textures.AddressMode; +import com.mojang.renderpearl.api.textures.FilterMode; +import com.mojang.renderpearl.api.textures.GpuSampler; +import com.mojang.renderpearl.api.textures.GpuTexture; +import com.mojang.renderpearl.api.textures.GpuTextureView; +import java.nio.ByteBuffer; +import java.util.List; +import java.util.OptionalDouble; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; +import java.util.function.BooleanSupplier; +import java.util.function.Supplier; +import org.jspecify.annotations.Nullable; + +/** + * A device with no GPU behind it: textures and samplers are descriptions, buffers are plain memory + * (so mapped writes and reads behave), pipelines "compile" at once, and commands do nothing. + */ +final class HeadlessDevice implements GpuDevice { + + private static final DeviceInfo INFO = new DeviceInfo( + "Headless", + "Incari", + "none", + false, + "Headless", + 1.0F, + new DeviceLimits(1, 256, 8192, 256L * 1024 * 1024, 0, 8, 0), + new DeviceFeatures(false, false, false, false, false, false, false, false), + Set.of(), + new HintsAndWorkarounds(false, false, false, false), + DeviceType.CPU); + + private final CommandEncoder encoder = new HeadlessEncoder(); + + @Override + public GpuSurface createSurface(long windowHandle, BooleanSupplier isIconified) { + return new HeadlessSurface(); + } + + @Override + public CommandEncoder createCommandEncoder() { + return encoder; + } + + @Override + public GpuSampler createSampler( + AddressMode addressModeU, + AddressMode addressModeV, + FilterMode minFilter, + FilterMode magFilter, + int maxAnisotropy, + OptionalDouble maxLod) { + return new HeadlessSampler(addressModeU, addressModeV, minFilter, magFilter, maxAnisotropy, maxLod); + } + + @Override + public GpuTexture createTexture( + @Nullable Supplier label, + @GpuTexture.Usage int usage, + GpuFormat format, + int width, + int height, + int depthOrLayers, + int mipLevels) { + return createTexture( + label == null ? null : label.get(), usage, format, width, height, depthOrLayers, mipLevels); + } + + @Override + public GpuTexture createTexture( + @Nullable String label, + @GpuTexture.Usage int usage, + GpuFormat format, + int width, + int height, + int depthOrLayers, + int mipLevels) { + return new HeadlessTexture(label == null ? "" : label, usage, format, width, height, depthOrLayers, mipLevels); + } + + @Override + public GpuTextureView createTextureView(GpuTexture texture) { + return new HeadlessTextureView(texture, 0, texture.getMipLevels()); + } + + @Override + public GpuTextureView createTextureView(GpuTexture texture, int baseMipLevel, int mipLevels) { + return new HeadlessTextureView(texture, baseMipLevel, mipLevels); + } + + @Override + public GpuBuffer createBuffer(@Nullable Supplier label, @GpuBuffer.Usage int usage, long size) { + return new HeadlessBuffer(usage, size); + } + + @Override + public GpuBuffer createBuffer(@Nullable Supplier label, @GpuBuffer.Usage int usage, ByteBuffer data) { + HeadlessBuffer buffer = new HeadlessBuffer(usage, data.remaining()); + buffer.write(0, data); + return buffer; + } + + @Override + public List getLastDebugMessages() { + return List.of(); + } + + @Override + public boolean isDebuggingEnabled() { + return false; + } + + @Override + public CompletableFuture compilePipeline( + RenderPipeline pipeline, ShaderSource shaderSource, Executor executor) { + CompiledRenderPipeline compiled = new HeadlessPipeline(); + return CompletableFuture.completedFuture(() -> compiled); + } + + @Override + public void close() {} + + @Override + public GpuQueryPool createTimestampQueryPool(int size) { + return new HeadlessQueryPool(size); + } + + @Override + public DeviceInfo getDeviceInfo() { + return INFO; + } +} diff --git a/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessEncoder.java b/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessEncoder.java new file mode 100644 index 0000000..90c6764 --- /dev/null +++ b/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessEncoder.java @@ -0,0 +1,155 @@ +package incari.app.web.headless; + +import com.mojang.blaze3d.platform.NativeImage; +import com.mojang.renderpearl.api.buffers.GpuBuffer; +import com.mojang.renderpearl.api.buffers.GpuBufferSlice; +import com.mojang.renderpearl.api.buffers.TransientMemory; +import com.mojang.renderpearl.api.commands.CommandEncoder; +import com.mojang.renderpearl.api.commands.GpuFence; +import com.mojang.renderpearl.api.commands.GpuQueryPool; +import com.mojang.renderpearl.api.commands.RenderPass; +import com.mojang.renderpearl.api.commands.RenderPassDescriptor; +import com.mojang.renderpearl.api.textures.GpuTexture; +import java.nio.ByteBuffer; +import org.joml.Vector4fc; + +/** + * Commands that do nothing, except where the game can see the result: buffer writes and copies + * land in {@link HeadlessBuffer} memory, and read-back callbacks run at once. + */ +final class HeadlessEncoder implements CommandEncoder { + + private final HeadlessTransientMemory transientMemory = new HeadlessTransientMemory(); + + @Override + public void submit() { + transientMemory.release(); + } + + @Override + public TransientMemory transientMemory() { + return transientMemory; + } + + @Override + public RenderPass createRenderPass(RenderPassDescriptor descriptor) { + return new HeadlessRenderPass(); + } + + @Override + public void clearColorTexture(GpuTexture colorTexture, Vector4fc clearColor) {} + + @Override + public void clearColorAndDepthTextures( + GpuTexture colorTexture, Vector4fc clearColor, GpuTexture depthTexture, double clearDepth) {} + + @Override + public void clearColorAndDepthTextures( + GpuTexture colorTexture, + Vector4fc clearColor, + GpuTexture depthTexture, + double clearDepth, + int regionX, + int regionY, + int regionWidth, + int regionHeight, + int mipLevel) {} + + @Override + public void clearDepthTexture(GpuTexture depthTexture, double clearDepth) {} + + @Override + public void writeToBuffer(GpuBufferSlice destination, ByteBuffer data) { + if (destination.buffer() instanceof HeadlessBuffer buffer) { + buffer.write(destination.offset(), data); + } + } + + @Override + public void copyToBuffer(GpuBufferSlice source, GpuBufferSlice target) { + try (GpuBufferSlice.MappedView from = source.map(true, false)) { + writeToBuffer(target, from.data()); + } + } + + @Override + public void writeToTexture(GpuTexture destination, NativeImage source) {} + + @Override + public void writeToTexture( + GpuTexture destination, NativeImage source, int mipLevel, int depthOrLayer, int destX, int destY) {} + + @Override + public void writeToTexture( + GpuTexture destination, + ByteBuffer source, + int mipLevel, + int depthOrLayer, + int destX, + int destY, + int width, + int height) {} + + @Override + public void copyBufferToTexture( + GpuBufferSlice source, + int sourceX, + int sourceY, + int sourceWidth, + int sourceHeight, + GpuTexture destination, + int destinationX, + int destinationY, + int copyWidth, + int copyHeight, + int mipLevel, + int arrayLayer) {} + + @Override + public void copyTextureToBuffer( + GpuTexture source, GpuBuffer destination, long offset, Runnable callback, int mipLevel) { + callback.run(); + } + + @Override + public void copyTextureToBuffer( + GpuTexture source, + GpuBuffer destination, + long offset, + Runnable callback, + int mipLevel, + int x, + int y, + int width, + int height) { + callback.run(); + } + + @Override + public void copyTextureToTexture( + GpuTexture source, + GpuTexture destination, + int mipLevel, + int destX, + int destY, + int sourceX, + int sourceY, + int width, + int height) {} + + @Override + public GpuFence createFence() { + return new GpuFence() { + @Override + public void close() {} + + @Override + public boolean awaitCompletion(long timeoutNS) { + return true; + } + }; + } + + @Override + public void writeTimestamp(GpuQueryPool pool, int index) {} +} diff --git a/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessPipeline.java b/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessPipeline.java new file mode 100644 index 0000000..9bd51f2 --- /dev/null +++ b/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessPipeline.java @@ -0,0 +1,19 @@ +package incari.app.web.headless; + +import com.mojang.renderpearl.api.pipeline.CompiledRenderPipeline; + +/** A pipeline that "compiled" at once: there are no shaders to run. */ +final class HeadlessPipeline implements CompiledRenderPipeline { + + private boolean closed; + + @Override + public boolean isClosed() { + return closed; + } + + @Override + public void close() { + closed = true; + } +} diff --git a/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessQueryPool.java b/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessQueryPool.java new file mode 100644 index 0000000..990ae82 --- /dev/null +++ b/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessQueryPool.java @@ -0,0 +1,35 @@ +package incari.app.web.headless; + +import com.mojang.renderpearl.api.commands.GpuQueryPool; +import java.util.Arrays; +import java.util.OptionalLong; + +/** Timestamp queries that never get a value: there's no GPU time to measure. */ +final class HeadlessQueryPool implements GpuQueryPool { + + private final int size; + + HeadlessQueryPool(int size) { + this.size = size; + } + + @Override + public int size() { + return size; + } + + @Override + public OptionalLong getValue(int index) { + return OptionalLong.empty(); + } + + @Override + public OptionalLong[] getValues(int index, int count) { + OptionalLong[] values = new OptionalLong[count]; + Arrays.fill(values, OptionalLong.empty()); + return values; + } + + @Override + public void close() {} +} diff --git a/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessRenderPass.java b/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessRenderPass.java new file mode 100644 index 0000000..6766ca5 --- /dev/null +++ b/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessRenderPass.java @@ -0,0 +1,91 @@ +package incari.app.web.headless; + +import com.mojang.renderpearl.api.buffers.GpuBuffer; +import com.mojang.renderpearl.api.buffers.GpuBufferSlice; +import com.mojang.renderpearl.api.commands.GpuQueryPool; +import com.mojang.renderpearl.api.commands.RenderPass; +import com.mojang.renderpearl.api.pipeline.CompiledRenderPipeline; +import com.mojang.renderpearl.api.pipeline.IndexType; +import com.mojang.renderpearl.api.textures.GpuSampler; +import com.mojang.renderpearl.api.textures.GpuTextureView; +import java.nio.ByteBuffer; +import java.nio.IntBuffer; +import java.util.Collection; +import org.jspecify.annotations.Nullable; +import org.lwjgl.PointerBuffer; + +/** A render pass that draws nothing. */ +final class HeadlessRenderPass implements RenderPass { + + @Override + public void pushDebugGroup(java.util.function.Supplier label) {} + + @Override + public void popDebugGroup() {} + + @Override + public void writeTimestamp(GpuQueryPool pool, int index) {} + + @Override + public void setPipeline(CompiledRenderPipeline pipeline) {} + + @Override + public void setUniform(String name, @Nullable GpuTextureView textureView, @Nullable GpuSampler sampler) {} + + @Override + public void setUniform(String name, GpuBuffer value) {} + + @Override + public void setUniform(String name, GpuBufferSlice value) {} + + @Override + public void pushConstants(ByteBuffer value) {} + + @Override + public void enableScissor(int x, int y, int width, int height) {} + + @Override + public void disableScissor() {} + + @Override + public void setVertexBuffer(int slot, @Nullable GpuBufferSlice vertexBuffer) {} + + @Override + public void setIndexBuffer(GpuBuffer indexBuffer, IndexType indexType) {} + + @Override + public void drawIndexed(int indexCount, int instanceCount, int firstIndex, int vertexOffset, int firstInstance) {} + + @Override + public void multiDrawIndexed(IntBuffer drawParameters, int instanceCount, int firstInstance, int drawCount) {} + + @Override + public void multiDrawIndexed( + PointerBuffer firstIndexOffsets, IntBuffer indexCounts, IntBuffer vertexOffsets, int drawCount) {} + + @Override + public void drawIndexedIndirect(GpuBufferSlice commands, int drawCount) {} + + @Override + public void drawMultipleIndexed( + Collection> draws, + @Nullable GpuBuffer defaultIndexBuffer, + @Nullable IndexType defaultIndexType, + Collection dynamicUniforms, + T uniformArgument) {} + + @Override + public void draw(int vertexCount, int instanceCount, int firstVertex, int firstInstance) {} + + @Override + public void multiDraw(IntBuffer drawParameters, int instanceCount, int firstInstance, int drawCount) {} + + @Override + public void multiDraw(IntBuffer firstVertices, IntBuffer vertexCounts, int drawCount) {} + + @Override + public void drawIndirect(GpuBufferSlice commands, int drawCount) {} + + @Override + public void close() {} +} diff --git a/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessSampler.java b/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessSampler.java new file mode 100644 index 0000000..9792f8d --- /dev/null +++ b/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessSampler.java @@ -0,0 +1,73 @@ +package incari.app.web.headless; + +import com.mojang.renderpearl.api.textures.AddressMode; +import com.mojang.renderpearl.api.textures.FilterMode; +import com.mojang.renderpearl.api.textures.GpuSampler; +import java.util.OptionalDouble; + +/** A sampler's settings, kept only so the game can read them back. */ +final class HeadlessSampler implements GpuSampler { + + private final AddressMode addressModeU; + private final AddressMode addressModeV; + private final FilterMode minFilter; + private final FilterMode magFilter; + private final int maxAnisotropy; + private final OptionalDouble maxLod; + private boolean closed; + + HeadlessSampler( + AddressMode addressModeU, + AddressMode addressModeV, + FilterMode minFilter, + FilterMode magFilter, + int maxAnisotropy, + OptionalDouble maxLod) { + this.addressModeU = addressModeU; + this.addressModeV = addressModeV; + this.minFilter = minFilter; + this.magFilter = magFilter; + this.maxAnisotropy = maxAnisotropy; + this.maxLod = maxLod; + } + + @Override + public AddressMode getAddressModeU() { + return addressModeU; + } + + @Override + public AddressMode getAddressModeV() { + return addressModeV; + } + + @Override + public FilterMode getMinFilter() { + return minFilter; + } + + @Override + public FilterMode getMagFilter() { + return magFilter; + } + + @Override + public int getMaxAnisotropy() { + return maxAnisotropy; + } + + @Override + public OptionalDouble getMaxLod() { + return maxLod; + } + + @Override + public boolean isClosed() { + return closed; + } + + @Override + public void close() { + closed = true; + } +} diff --git a/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessSurface.java b/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessSurface.java new file mode 100644 index 0000000..211e212 --- /dev/null +++ b/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessSurface.java @@ -0,0 +1,55 @@ +package incari.app.web.headless; + +import com.mojang.renderpearl.api.commands.CommandEncoder; +import com.mojang.renderpearl.api.device.GpuSurface; +import com.mojang.renderpearl.api.textures.GpuTextureView; +import java.util.Collection; +import java.util.List; +import java.util.Optional; +import org.jspecify.annotations.Nullable; + +/** + * A surface that never has an image to draw into: acquiring one does nothing, so the game skips + * its blit and present each frame. + */ +final class HeadlessSurface implements GpuSurface { + + private GpuSurface.@Nullable Configuration configuration; + + @Override + public void configure(GpuSurface.Configuration config) { + configuration = config; + } + + @Override + public Optional currentConfiguration() { + return Optional.ofNullable(configuration); + } + + @Override + public Collection supportedPresentModes() { + return List.of(GpuSurface.PresentMode.FIFO, GpuSurface.PresentMode.IMMEDIATE); + } + + @Override + public boolean isSuboptimal() { + return false; + } + + @Override + public boolean isAcquired() { + return false; + } + + @Override + public void acquireNextTexture() {} + + @Override + public void blitFromTexture(CommandEncoder commandEncoder, GpuTextureView textureView) {} + + @Override + public void present() {} + + @Override + public void close() {} +} diff --git a/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessTexture.java b/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessTexture.java new file mode 100644 index 0000000..fd003a0 --- /dev/null +++ b/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessTexture.java @@ -0,0 +1,79 @@ +package incari.app.web.headless; + +import com.mojang.renderpearl.api.GpuFormat; +import com.mojang.renderpearl.api.textures.GpuTexture; + +/** A texture's description with no pixels: writes to it are dropped. */ +final class HeadlessTexture implements GpuTexture { + + private final String label; + private final @GpuTexture.Usage int usage; + private final GpuFormat format; + private final int width; + private final int height; + private final int depthOrLayers; + private final int mipLevels; + private boolean closed; + + HeadlessTexture( + String label, + @GpuTexture.Usage int usage, + GpuFormat format, + int width, + int height, + int depthOrLayers, + int mipLevels) { + this.label = label; + this.usage = usage; + this.format = format; + this.width = width; + this.height = height; + this.depthOrLayers = depthOrLayers; + this.mipLevels = mipLevels; + } + + @Override + public int getWidth(int mipLevel) { + return Math.max(1, width >> mipLevel); + } + + @Override + public int getHeight(int mipLevel) { + return Math.max(1, height >> mipLevel); + } + + @Override + public int getDepthOrLayers() { + return depthOrLayers; + } + + @Override + public int getMipLevels() { + return mipLevels; + } + + @Override + public GpuFormat getFormat() { + return format; + } + + @Override + public @GpuTexture.Usage int usage() { + return usage; + } + + @Override + public String getLabel() { + return label; + } + + @Override + public boolean isClosed() { + return closed; + } + + @Override + public void close() { + closed = true; + } +} diff --git a/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessTextureView.java b/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessTextureView.java new file mode 100644 index 0000000..a694a16 --- /dev/null +++ b/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessTextureView.java @@ -0,0 +1,54 @@ +package incari.app.web.headless; + +import com.mojang.renderpearl.api.textures.GpuTexture; +import com.mojang.renderpearl.api.textures.GpuTextureView; + +/** A view of a {@link HeadlessTexture}'s mip levels. */ +final class HeadlessTextureView implements GpuTextureView { + + private final GpuTexture texture; + private final int baseMipLevel; + private final int mipLevels; + private boolean closed; + + HeadlessTextureView(GpuTexture texture, int baseMipLevel, int mipLevels) { + this.texture = texture; + this.baseMipLevel = baseMipLevel; + this.mipLevels = mipLevels; + } + + @Override + public boolean isClosed() { + return closed; + } + + @Override + public GpuTexture texture() { + return texture; + } + + @Override + public int baseMipLevel() { + return baseMipLevel; + } + + @Override + public int mipLevels() { + return mipLevels; + } + + @Override + public int getWidth(int mipLevel) { + return texture.getWidth(baseMipLevel + mipLevel); + } + + @Override + public int getHeight(int mipLevel) { + return texture.getHeight(baseMipLevel + mipLevel); + } + + @Override + public void close() { + closed = true; + } +} diff --git a/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessTransientMemory.java b/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessTransientMemory.java new file mode 100644 index 0000000..6bb3c7c --- /dev/null +++ b/incari-client/files/app-web/src/main/java/incari/app/web/headless/HeadlessTransientMemory.java @@ -0,0 +1,116 @@ +package incari.app.web.headless; + +import com.mojang.renderpearl.api.buffers.GpuBuffer; +import com.mojang.renderpearl.api.buffers.GpuBufferSlice; +import com.mojang.renderpearl.api.buffers.TransientMemory; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.ArrayList; +import java.util.List; +import org.lwjgl.system.MemoryUtil; + +/** + * Per-frame scratch memory as fresh {@code MemoryUtil} allocations: nothing is uploaded, so + * nothing needs pooling. Uploads copy their data, so later reads of the slices see it. Everything + * handed out lives until the frame's commands are submitted ({@link #release}), as transient + * memory does on a real device. + */ +final class HeadlessTransientMemory implements TransientMemory { + + private final List cpu = new ArrayList<>(); + private final List buffers = new ArrayList<>(); + + /** Frees this frame's allocations; the encoder calls it on submit. */ + void release() { + for (ByteBuffer buffer : cpu) { + MemoryUtil.memFree(buffer); + } + cpu.clear(); + for (HeadlessBuffer buffer : buffers) { + buffer.close(); + } + buffers.clear(); + } + + private HeadlessBuffer track(HeadlessBuffer buffer) { + buffers.add(buffer); + return buffer; + } + + @Override + public ByteBuffer allocateCpu(long size, long alignment, long minimumAllocation, long elementSize) { + ByteBuffer buffer = MemoryUtil.memCalloc(Math.toIntExact(size)).order(ByteOrder.nativeOrder()); + cpu.add(buffer); + return buffer; + } + + @Override + public GpuBufferSlice.MappedView allocateStaging( + long size, long alignment, @GpuBuffer.Usage int usage, long minimumAllocation, long elementSize) { + return track(new HeadlessBuffer(usage, size)).map(true, true); + } + + @Override + public GpuBufferSlice allocateGpu( + long size, long alignment, @GpuBuffer.Usage int usage, long minimumAllocation, long elementSize) { + return track(new HeadlessBuffer(usage, size)).slice(); + } + + @Override + public GpuBufferSlice.MappedView allocateGpuMapped( + long size, long alignment, @GpuBuffer.Usage int usage, long minimumAllocation, long elementSize) { + return track(new HeadlessBuffer(usage, size)).map(true, true); + } + + @Override + public GpuBufferSlice uploadStaging( + List data, + long alignment, + @GpuBuffer.Usage int usage, + long minimumAllocation, + long elementSize) { + return upload(data, usage); + } + + @Override + public GpuBufferSlice uploadGpu( + List data, + long alignment, + @GpuBuffer.Usage int usage, + long minimumAllocation, + long elementSize) { + return upload(data, usage); + } + + @Override + public List multiUploadStaging(List data, long alignment, @GpuBuffer.Usage int usage) { + return multiUpload(data, usage); + } + + @Override + public List multiUploadGpu(List data, long alignment, @GpuBuffer.Usage int usage) { + return multiUpload(data, usage); + } + + private GpuBufferSlice upload(List data, @GpuBuffer.Usage int usage) { + long size = 0; + for (ByteBuffer part : data) { + size += part.remaining(); + } + HeadlessBuffer buffer = track(new HeadlessBuffer(usage, size)); + long offset = 0; + for (ByteBuffer part : data) { + buffer.write(offset, part); + offset += part.remaining(); + } + return buffer.slice(); + } + + private List multiUpload(List data, @GpuBuffer.Usage int usage) { + List slices = new ArrayList<>(data.size()); + for (ByteBuffer part : data) { + slices.add(upload(List.of(part), usage)); + } + return slices; + } +} diff --git a/incari-client/files/app-web/src/main/java/incari/app/web/mesher/MesherWorker.java b/incari-client/files/app-web/src/main/java/incari/app/web/mesher/MesherWorker.java new file mode 100644 index 0000000..6bea852 --- /dev/null +++ b/incari-client/files/app-web/src/main/java/incari/app/web/mesher/MesherWorker.java @@ -0,0 +1,80 @@ +package incari.app.web.mesher; + +import incari.mesher.Bytes; +import incari.mesher.MeshJobs; +import java.nio.ByteBuffer; +import org.jspecify.annotations.Nullable; +import org.teavm.jso.JSBody; +import org.teavm.jso.JSFunctor; +import org.teavm.jso.JSObject; +import org.teavm.jso.typedarrays.Int8Array; + +/** + * The mesher workers' program (ADR 0023): compiled by TeaVM on its own into + * {@code mesher.wasm}, which each of the page's mesher workers loads. It holds the mesher and + * answers the game's messages ({@link MeshJobs}); the worker's bootstrap script + * ({@code platform-web}'s {@code program-worker.js}) moves the bytes in and out. + * + *

Worker-side: no game objects, nothing but the mesher. Messages arrive in a direct buffer (the + * module's linear memory, where the bootstrap can copy them in one go), and replies leave the same + * way. + */ +public final class MesherWorker { + + private static final MeshJobs JOBS = new MeshJobs(); + private static ByteBuffer input = ByteBuffer.allocateDirect(64 * 1024); + private static ByteBuffer output = ByteBuffer.allocateDirect(256 * 1024); + private static byte[] message = new byte[64 * 1024]; + + private MesherWorker() {} + + public static void main(String[] args) { + install(MesherWorker::input, MesherWorker::handle, MesherWorker::output); + } + + /** A view of {@code length} bytes to copy the next message into. */ + private static Int8Array input(int length) { + if (input.capacity() < length) { + input = ByteBuffer.allocateDirect(Math.max(length, input.capacity() * 2)); + } + return Int8Array.fromJavaBuffer(input.slice(0, length)); + } + + /** Handles the message just copied in; returns its reply's length, or -1 for none. */ + private static int handle(int length) { + if (message.length < length) { + message = new byte[Math.max(length, message.length * 2)]; + } + input.get(0, message, 0, length); + Bytes.@Nullable Out reply = JOBS.handle(message, 0, length); + if (reply == null) { + return -1; + } + int size = reply.size(); + if (output.capacity() < size) { + output = ByteBuffer.allocateDirect(Math.max(size, output.capacity() * 2)); + } + output.put(0, reply.array(), 0, size); + return size; + } + + /** A view of the reply's {@code length} bytes. */ + private static Int8Array output(int length) { + return Int8Array.fromJavaBuffer(output.slice(0, length)); + } + + @JSFunctor + interface View extends JSObject { + Int8Array view(int length); + } + + @JSFunctor + interface Handle extends JSObject { + int handle(int length); + } + + @JSBody( + params = {"input", "handle", "output"}, + script = "self.__incariProgram = {input: input, handle: handle, output: output};") + private static native void install(View input, Handle handle, View output); +} diff --git a/incari-client/files/app-web/src/main/java/incari/app/web/mesher/package-info.java b/incari-client/files/app-web/src/main/java/incari/app/web/mesher/package-info.java new file mode 100644 index 0000000..dc87925 --- /dev/null +++ b/incari-client/files/app-web/src/main/java/incari/app/web/mesher/package-info.java @@ -0,0 +1,5 @@ +/** The mesher workers' program: compiled apart from the game, for the page's Web Workers. */ +@NullMarked +package incari.app.web.mesher; + +import org.jspecify.annotations.NullMarked; diff --git a/incari-client/files/app-web/src/main/java/incari/app/web/package-info.java b/incari-client/files/app-web/src/main/java/incari/app/web/package-info.java new file mode 100644 index 0000000..9d4c175 --- /dev/null +++ b/incari-client/files/app-web/src/main/java/incari/app/web/package-info.java @@ -0,0 +1,5 @@ +/** The browser build's entry point. */ +@NullMarked +package incari.app.web; + +import org.jspecify.annotations.NullMarked; diff --git a/incari-client/files/app-web/src/main/ts/boot.ts b/incari-client/files/app-web/src/main/ts/boot.ts new file mode 100644 index 0000000..2a0c5e0 --- /dev/null +++ b/incari-client/files/app-web/src/main/ts/boot.ts @@ -0,0 +1,451 @@ +/** + * The host page's loader: checks the browser, reads the build manifest, offers Fast (recommended) or + * Compatible where both run (ADR 0036), streams the build with a progress bar, registers the service + * worker that caches it, and starts the game. The game then reports its start-up steps through + * `window.incariLoader` until its first frame, when the loading screen goes. + * + * Loaded by `index.html` as a module; `:app-web:pageScripts` strips the types. + */ +import { detectFeatures } from "./features.ts"; +import { createJspiImports, supportsJspi } from "./jspi.ts"; +import { + createAsyncImports, + createPageAsyncImports, + createPageTimer, + pageWakeupScope, + startTimerWorker, + type PageTimer, +} from "./wakeups.ts"; +import { + buildFor, + buildName, + buildOptions, + countingResponse, + DEFAULT_MANIFEST, + formatBytes, + initialBuild, + missingWasmGc, + missingWebgl2, + parseManifest, + requestedBuild, + rustPage, + sizeOf, + versioned, + type BuildKind, + type BuildManifest, + type BuildOption, + type WasmTarget, +} from "./loader.ts"; + +/** What the game's code calls while it starts (`incari.app.web.LoaderPage`, platform-web's first frame). */ +export interface LoaderHooks { + /** A start-up step, shown under the bar. */ + status(text: string): void; + /** The game has drawn its first frame: the loading screen goes. */ + done(): void; +} + +/** TeaVM's WebAssembly GC loader, which `incari.wasm-runtime.js` defines. */ +interface TeaVmRuntime { + wasmGC: { + load( + url: string, + options: { + stackDeobfuscator?: { enabled: boolean; path?: string; externalInfoPath?: string }; + installImports?: (imports: Record) => void; + }, + ): Promise<{ exports: { main(args: string[]): void }; instance: WebAssembly.Instance }>; + }; +} + +interface IncariWindow { + incariLoader?: LoaderHooks; + /** What the game reads about its build (`incari.app.web.LoaderPage`). */ + incariBuild?: { + id: string; + game: string; + release: boolean; + pack: string | null; + programs: Record; + /** The game's own build as this page loaded it, for copies of it in workers (ADR 0039). */ + program?: { runtime: string; module: string; jspi: boolean }; + }; + TeaVM?: TeaVmRuntime; + /** + * A timer a hidden page still gets on time (wakeups.ts): platform-web's frames and background + * pool fall back on it while the page is hidden. + */ + incariTimer?: PageTimer; + /** + * Calls `wake`, then runs the thread wake-ups it caused (wakeups.ts, `runWoken`): platform-web's + * network wake calls it rather than leave them to timers the browser runs late in play. + */ + incariRunWoken?: (wake: () => void) => void; + /** The single-file page's embedded files (offline.ts): where a script of theirs loads from. */ + incariFiles?: { base: string; url(href: string): string }; +} + +const page = window as unknown as IncariWindow & Window; +const options = new URLSearchParams(location.search); +/** What page-relative URLs resolve against: the single-file page's folder, whose own URL may have none. */ +const pageUrl = page.incariFiles?.base ?? location.href; + +const screen = element("incari-loader"); +const track = element("incari-track"); +const picker = element("incari-choose"); +const bar = element("incari-bar"); +const statusLine = element("incari-status"); +const detailLine = element("incari-detail"); + +function element(id: string): HTMLElement { + const found = document.getElementById(id); + if (found === null) { + throw new Error(`index.html has no #${id}`); + } + return found; +} + +function show(status: string, detail = ""): void { + statusLine.textContent = status; + detailLine.textContent = detail; +} + +/** The bar's fill, 0 to 1; null for a step that can't say how far it is (the bar pulses). */ +function progress(fraction: number | null): void { + bar.classList.toggle("indeterminate", fraction === null); + bar.style.width = fraction === null ? "100%" : `${String(Math.round(fraction * 1000) / 10)}%`; +} + +let failed = false; + +/** Stops with a message the player can act on. tools/webbuild's checks watch for the console line. */ +function fail(error: unknown): void { + if (failed) { + return; + } + failed = true; + const text = error instanceof Error ? error.message : String(error); + screen.classList.add("failed"); + screen.hidden = false; + progress(1); + show("The game couldn't start", text); + // One line, so log readers that split on newlines still get the whole stack. + const stack = error instanceof Error && error.stack !== undefined ? error.stack : text; + console.error("[Incari] Crashed: " + stack.replace(/\n\s*/g, " | ")); +} + +/** Where the player's last pick is kept, to start the next choice on it. */ +const BUILD_KEY = "incari.build"; + +function rememberedBuild(): string | null { + try { + return localStorage.getItem(BUILD_KEY); + } catch { + return null; + } +} + +function rememberBuild(kind: BuildKind): void { + try { + localStorage.setItem(BUILD_KEY, kind); + } catch { + // Storage blocked: the next choice starts on the recommended build. + } +} + +/** + * Shows the choice between the builds and waits for the player's pick. A build that can't run here + * is shown disabled, with the reason. Fast is marked as the one to use wherever it works. + */ +function askForBuild(builds: readonly BuildOption[], initial: BuildKind): Promise { + show("Choose a version", ""); + track.hidden = true; + picker.hidden = false; + return new Promise((resolve) => { + for (const build of builds) { + const button = element(`incari-pick-${build.kind}`) as HTMLButtonElement; + // Rust's button is hidden unless this copy has it. + button.hidden = false; + button.disabled = !build.available; + element(`incari-why-${build.kind}`).textContent = build.reason ?? ""; + button.addEventListener("click", () => { + picker.hidden = true; + track.hidden = false; + rememberBuild(build.kind); + resolve(build.kind); + }); + if (build.kind === initial) { + button.focus(); + } + } + }); +} + +async function readManifest(): Promise { + let response: Response; + try { + response = await fetch("build.json", { cache: "no-cache" }); + } catch { + return DEFAULT_MANIFEST; + } + // An experiment's build (a probe) has no manifest: TeaVM's development output. + return response.ok ? parseManifest(await response.json()) : DEFAULT_MANIFEST; +} + +/** + * Registers the service worker and waits a moment for it to take the page over, so this visit's + * download already goes through its cache. `?sw=off` skips it (and unregisters it) for development. + */ +async function registerWorker(manifest: BuildManifest): Promise { + const workers = navigator.serviceWorker as ServiceWorkerContainer | undefined; + // The single-file page holds every file itself, and a page opened from the disk can't have one. + if (workers === undefined || page.incariFiles !== undefined) { + return; + } + if (options.get("sw") === "off") { + for (const registration of await workers.getRegistrations()) { + await registration.unregister(); + } + return; + } + try { + await workers.register("sw.js", { type: "module", scope: "./" }); + await Promise.race([workers.ready, new Promise((resolve) => setTimeout(resolve, 3000))]); + if (workers.controller !== null && manifest.files.length > 0) { + workers.controller.postMessage({ type: "build", keep: manifest.files.map((f) => versioned(manifest, f.path)) }); + } + } catch (error) { + // Older browsers have no module workers: the game runs, uncached. + console.warn("[Incari] No service worker, so nothing is cached between visits: " + String(error)); + } +} + +function loadScript(src: string): Promise { + return new Promise((resolve, reject) => { + const script = document.createElement("script"); + // A script element fetches without `fetch`, so the single-file page's shim can't answer it. + script.src = page.incariFiles?.url(src) ?? src; + script.onload = () => { + resolve(); + }; + script.onerror = () => { + reject(new Error(`Couldn't load ${src}`)); + }; + document.head.append(script); + }); +} + +/** Whether the service worker's cache already holds `url` (false where there's no cache to ask). */ +async function cachedByWorker(url: string): Promise { + try { + return (await caches.match(url)) !== undefined; + } catch { + return false; + } +} + +/** + * Downloads `url` through `fetch` with a progress bar. TeaVM's loader fetches the module itself, so + * the page's `fetch` is wrapped for that one URL while it does: the response it gets counts its + * bytes and still compiles as it streams. + * + * Not when the service worker already has the file: nothing downloads, and the wrapper would copy + * every chunk through JavaScript on the page's thread (a quarter of a second for the development + * build on the desktop) and hand the browser a made-up response its compiled-code cache can't + * recognise. + */ +async function withDownloadProgress(url: string, total: number, label: string, work: () => Promise): Promise { + const absolute = new URL(url, pageUrl).href; + if (await cachedByWorker(absolute)) { + progress(null); + show("Starting the game", "From this browser's cache"); + return work(); + } + const original = window.fetch.bind(window); + window.fetch = async (input: RequestInfo | URL, init?: RequestInit): Promise => { + const target = input instanceof Request ? input.url : new URL(String(input), pageUrl).href; + const response = await original(input, init); + if (target !== absolute) { + return response; + } + return countingResponse(response, (received) => { + progress(total > 0 ? Math.min(received / total, 1) : null); + show(label, total > 0 ? `${formatBytes(received)} of ${formatBytes(total)}` : formatBytes(received)); + if (total > 0 && received >= total) { + progress(null); + show("Compiling the game", ""); + } + }); + }; + try { + return await work(); + } finally { + window.fetch = original; + } +} + +async function startBuild(manifest: BuildManifest, kind: BuildKind, target: WasmTarget): Promise { + show("Loading", `The ${buildName(kind)} build`); + await loadScript(versioned(manifest, target.runtime)); + const runtime = page.TeaVM; + if (runtime === undefined) { + throw new Error(`${target.runtime} didn't define TeaVM's loader`); + } + const moduleUrl = versioned(manifest, target.module); + const debug = + target.deobfuscator !== undefined && target.debugInfo !== undefined + ? { + enabled: true, + path: versioned(manifest, target.deobfuscator), + externalInfoPath: versioned(manifest, target.debugInfo), + } + : { enabled: false }; + // The Fast build suspends through JSPI (jspi.ts); Compatible imports none of it. Given wherever the + // browser has JSPI, so an experiment's Fast build (no manifest to say so) runs too. + const jspi = supportsJspi() ? createJspiImports(fail) : null; + // A hidden page's own timers are held to a wake-up a second, then a minute (Chrome, after five + // minutes hidden and silent): too few to answer a server's keep-alives. While hidden, the game's + // threads wake through a channel and a worker's timer instead (wakeups.ts); `?wakeups=timers` + // keeps TeaVM's own timers throughout. + const timerWorker = options.get("wakeups") === "timers" ? null : startTimerWorker(); + const pageTimer = timerWorker === null ? null : createPageTimer(timerWorker); + if (pageTimer !== null) { + page.incariTimer = pageTimer; + } + if (page.incariBuild !== undefined) { + page.incariBuild.program = { runtime: versioned(manifest, target.runtime), module: moduleUrl, jspi: jspi !== null }; + } + const teavm = await withDownloadProgress(moduleUrl, sizeOf(manifest, target.module), "Downloading the game", () => + runtime.wasmGC.load(moduleUrl, { + stackDeobfuscator: debug, + installImports: (imports) => { + if (jspi !== null) { + imports.teavmJspi = jspi.module; + } + // Threads woken without the browser's 4 ms timer clamp (wakeups.ts), as in singleplayer's + // worker; on the page always only when asked, until the page's frames are measured with + // it, and otherwise only while the page is hidden. + if (options.get("wakeups") === "channel") { + imports.teavmAsync = createAsyncImports(); + } else if (pageTimer !== null) { + const pageImports = createPageAsyncImports(pageWakeupScope(pageTimer)); + imports.teavmAsync = pageImports; + // A server message's connection thread runs as the message comes (ADR 0075); + // `?netwake=timers` leaves it to TeaVM's timer, which play delays ~35 ms. + if (options.get("netwake") !== "timers") { + page.incariRunWoken = (wake) => { + pageImports.runWoken(wake); + }; + } + } + }, + }), + ); + if (jspi !== null) { + jspi.attach(teavm.instance.exports); + // The engine never frees a waiting fiber's stack: a page going away ends them all, or the + // whole game stays in the tab's memory through the next load (jspi.ts). That includes a page + // the back/forward cache keeps, whose game can't run again: it reloads if it comes back. + window.addEventListener("pagehide", (event) => { + console.log( + `[Incari] Loader: page hidden${event.persisted ? " into the back/forward cache" : ""}; ending its threads`, + ); + jspi.terminate(); + }); + window.addEventListener("pageshow", (event) => { + if (event.persisted) { + location.reload(); + } + }); + } + show("Starting", ""); + // main() returns at the game's first suspension; the rest runs from the page's event loop. + teavm.exports.main([]); +} + +async function boot(): Promise { + // The game's stacks run deep; JavaScript keeps 10 frames of a trace by default. + Error.stackTraceLimit = 1000; + // An error that escapes Java (a JavaScript exception in the runtime) ends the game. main() + // returns at the first suspension, so later ones only reach the window's handlers. + // Not one from a browser extension's script, which isn't the game's to end. + window.addEventListener("error", (event) => { + if (/^(chrome|moz|safari(-web)?)-extension:/.test(event.filename)) { + console.warn(`[Incari] Ignored an extension's error: ${event.message}`); + return; + } + fail(event.error ?? event.message); + }); + window.addEventListener("unhandledrejection", (event) => { + fail(event.reason); + }); + page.incariLoader = { + status: (text) => { + if (!failed) { + progress(null); + show(text, ""); + } + }, + done: () => { + if (!failed) { + screen.hidden = true; + } + }, + }; + + show("Checking your browser"); + progress(null); + const features = await detectFeatures(); + const manifest = await readManifest(); + const builds = buildOptions(features, manifest); + // Rust needs neither (it draws through WebGPU); where it can run, the choice says what can't. + const missing = missingWebgl2(features) ?? missingWasmGc(features); + if (missing !== null && !builds.some((build) => build.kind === "rust" && build.available)) { + throw new Error(missing); + } + // The player picks where more than one build can run; `?build=fast`, `compatible` or `rust` + // picks in the address (the checks and the benchmark do), and a browser that can run only one runs it. + const runnable = builds.filter((build) => build.available); + if (runnable.length === 0) { + throw new Error(builds.map((build) => build.reason).join(" ")); + } + const requested = requestedBuild(options.get("build")); + const only = runnable.length === 1 ? runnable[0]?.kind : undefined; + const picked = requested ?? only ?? (await askForBuild(builds, initialBuild(builds, rememberedBuild()))); + const choice = buildFor(picked, builds, manifest); + if (choice.kind === "unsupported") { + throw new Error(choice.reason); + } + if (choice.kind === "rust") { + // Its own page, files and service worker (ADR 0068). + console.log("[Incari] Loader: opening the Rust build"); + location.assign(rustPage(choice.target, location.href)); + return; + } + page.incariBuild = { + id: manifest.id, + game: manifest.game, + release: manifest.release, + pack: manifest.pack === undefined ? null : versioned(manifest, manifest.pack), + // The workers' programs, by the versioned URLs their loaders fetch them from. + programs: Object.fromEntries( + Object.entries(manifest.programs ?? {}).map(([name, program]) => [ + name, + { runtime: versioned(manifest, program.runtime), module: versioned(manifest, program.module) }, + ]), + ), + }; + const why = + requested !== null ? "asked for in the address" : only !== undefined ? "the only one that runs here" : "picked"; + console.log( + `[Incari] Loader: build ${manifest.id.slice(0, 12)} (${manifest.release ? "release" : "development"}), running ${buildName( + choice.kind, + )} (${why}); JSPI ${features.jspi ? "yes" : "no"}, cross-origin isolated ${features.crossOriginIsolated ? "yes" : "no"}`, + ); + await registerWorker(manifest); + const started = performance.now(); + await startBuild(manifest, choice.kind, choice.target); + console.log(`[Incari] Loader: build loaded and started in ${String(Math.round(performance.now() - started))} ms`); +} + +boot().catch(fail); diff --git a/incari-client/files/app-web/src/main/ts/cache-policy.ts b/incari-client/files/app-web/src/main/ts/cache-policy.ts new file mode 100644 index 0000000..e74cd7f --- /dev/null +++ b/incari-client/files/app-web/src/main/ts/cache-policy.ts @@ -0,0 +1,70 @@ +/** + * What the service worker (`sw.ts`) does with each request the page makes. Pure, so it can be + * tested; the worker only carries it out. + */ + +/** + * - `build`: a build file, versioned by its hash in the URL (`?v=`): from the cache once it's there. + * - `immutable`: a game asset named by its content hash (`assets/objects/ab/abcd...`): the same. + * - `page`: the page and what it starts from: from the network while there is one, from the cache + * when offline, so a returning player can start without a connection. + * - `pass`: not the worker's business (the client jar, which the storage worker keeps itself; + * other origins; the development server's own files). + */ +export type Strategy = "build" | "immutable" | "page" | "pass"; + +/** The worker's caches. A new layout gets a new name; the worker deletes names it doesn't know. */ +export const CACHES = { + build: "incari-build-v1", + immutable: "incari-assets-v1", + page: "incari-page-v1", +} as const; + +/** Files the page starts from, kept for offline starts. */ +const PAGE_FILES = new Set([ + "", + "index.html", + "boot.js", + "loader.js", + "features.js", + "jspi.js", + "wakeups.js", + "game-worker.js", + "cache-policy.js", + "build.json", + "asset-index.json", +]); + +export function strategyFor(url: URL, scope: URL, method = "GET"): Strategy { + if (method !== "GET" || url.origin !== scope.origin || !url.pathname.startsWith(scope.pathname)) { + return "pass"; + } + const path = url.pathname.slice(scope.pathname.length); + if (path.startsWith("rust/")) { + // The Rust build's own service worker keeps its files (ADR 0068). + return "pass"; + } + if (path === "client.jar") { + // Kept by the storage worker (OPFS or IndexedDB, ADR 0011): caching it here would store it twice. + return "pass"; + } + if (url.searchParams.has("v")) { + return "build"; + } + if (/^assets\/objects\/[0-9a-f]{2}\/[0-9a-f]{40}$/.test(path)) { + return "immutable"; + } + if (PAGE_FILES.has(path)) { + return "page"; + } + return "pass"; +} + +/** + * Which cached build files to drop once the page runs a build: every versioned URL the build + * doesn't list. `keep` holds the URLs, relative to the scope, that the running build loads. + */ +export function staleBuildEntries(cached: readonly string[], keep: readonly string[], scope: URL): string[] { + const wanted = new Set(keep.map((path) => new URL(path, scope).href)); + return cached.filter((href) => !wanted.has(href)); +} diff --git a/incari-client/files/app-web/src/main/ts/features.ts b/incari-client/files/app-web/src/main/ts/features.ts new file mode 100644 index 0000000..ce1c43c --- /dev/null +++ b/incari-client/files/app-web/src/main/ts/features.ts @@ -0,0 +1,108 @@ +/** + * What the browser supports, checked once before anything is downloaded. The loader uses it to + * offer the builds that can run here (Fast needs JSPI, both need WebAssembly GC, Rust needs WebGPU), + * and to explain a failure before the player waits through a download that can't run. + */ +import { supportsJspi } from "./jspi.ts"; + +export interface BrowserFeatures { + /** WebAssembly with the GC proposal: needed by both builds of the game. */ + readonly wasmGc: boolean; + /** WebAssembly JavaScript Promise Integration: needed by the Fast build (ADR 0036). */ + readonly jspi: boolean; + /** + * SharedArrayBuffer is usable, which needs COOP/COEP headers on the page. Worker meshing uses + * it; without it, workers fall back to transferring buffers. + */ + readonly crossOriginIsolated: boolean; + /** A WebGL2 context can be created: the graphics floor for Fast and Compatible. */ + readonly webgl2: boolean; + /** WebGPU gives an adapter: what the experimental Rust build draws with (ADR 0068). */ + readonly webgpu: boolean; +} + +/** + * The smallest module that uses a GC type: the header, then a type section declaring one empty + * struct (0x5f). Engines without the GC proposal reject the struct type form. + */ +// prettier-ignore +const WASM_GC_PROBE = new Uint8Array([ + 0x00, 0x61, 0x73, 0x6d, // magic "\0asm" + 0x01, 0x00, 0x00, 0x00, // version 1 + 0x01, 0x03, // type section, 3 bytes + 0x01, // one type + 0x5f, 0x00, // struct with no fields +]); + +/** The parts of the global scope detection reads, so tests can supply their own. */ +export interface FeatureScope { + readonly WebAssembly?: Pick; + readonly crossOriginIsolated?: boolean; + readonly SharedArrayBuffer?: unknown; + readonly document?: Pick; + readonly navigator?: { readonly gpu?: GpuLike }; +} + +/** The part of `navigator.gpu` detection calls; TypeScript's DOM types don't have WebGPU yet. */ +export interface GpuLike { + requestAdapter(): Promise; +} + +/** + * Async because only asking for an adapter tells: a browser can have `navigator.gpu` and no GPU it + * will use (blocklisted drivers, software rendering off). + */ +export async function detectFeatures(scope: FeatureScope = globalThis): Promise { + return { + wasmGc: supportsWasmGc(scope), + jspi: supportsWasmGc(scope) && supportsJspi(scope), + crossOriginIsolated: scope.crossOriginIsolated === true && scope.SharedArrayBuffer !== undefined, + webgl2: supportsWebgl2(scope), + webgpu: await supportsWebgpu(scope), + }; +} + +async function supportsWebgpu(scope: FeatureScope): Promise { + const gpu = scope.navigator?.gpu; + if (gpu === undefined) { + return false; + } + let timer: ReturnType | undefined; + try { + // Bounded: an adapter request on a wedged GPU process can take seconds, and this is before the + // player sees anything. + const adapter = await Promise.race([ + gpu.requestAdapter(), + new Promise((resolve) => { + timer = setTimeout(() => { + resolve(null); + }, 2000); + }), + ]); + return adapter !== null && adapter !== undefined; + } catch { + return false; + } finally { + clearTimeout(timer); + } +} + +function supportsWasmGc(scope: FeatureScope): boolean { + try { + return scope.WebAssembly?.validate(WASM_GC_PROBE) === true; + } catch { + // Some engines throw on unknown type forms instead of returning false. + return false; + } +} + +function supportsWebgl2(scope: FeatureScope): boolean { + if (scope.document === undefined) { + return false; + } + const canvas = scope.document.createElement("canvas"); + // Released straight away: this only asks whether a context can exist. + const context = canvas.getContext("webgl2"); + context?.getExtension("WEBGL_lose_context")?.loseContext(); + return context !== null; +} diff --git a/incari-client/files/app-web/src/main/ts/game-worker.ts b/incari-client/files/app-web/src/main/ts/game-worker.ts new file mode 100644 index 0000000..b977edc --- /dev/null +++ b/incari-client/files/app-web/src/main/ts/game-worker.ts @@ -0,0 +1,260 @@ +/** + * A copy of the game's program in a module worker (ADR 0039): singleplayer's server, apart from the + * page's thread. The page (platform-web's `JsChannel`) starts it with the build it loaded itself; + * this loads TeaVM's runtime and that module, with the Fast build's JSPI imports (jspi.ts), and + * starts the program in the role it was given. + * + * The page and the program here talk through `__incariParent`, the same four calls the page's side + * offers: `send` a numbered message of bytes (the buffer is handed over), `take` the next one if any, + * `next` for a promise of it, `close`. A message only queues here: Java waits for it on a thread of + * its own. The worker's console lines show in the page's DevTools (and the browser checks) as they + * are; a start that fails is reported to the page, which prints it. + */ +import { createJspiImports } from "./jspi.ts"; +import { createAsyncImports } from "./wakeups.ts"; + +/** A numbered message of bytes; kind -1 ends the channel. */ +export interface Envelope { + kind: number; + data: ArrayBuffer; +} + +/** What the page sends first, with a port of its storage worker's if it has one (ADR 0041). */ +export interface StartMessage { + start: { runtime: string; module: string; jspi: boolean; role: string; query?: string }; + storage?: MessagePort | null; +} + +/** What the program here reaches the page through. */ +export interface ParentChannel { + send(kind: number, data: ArrayBuffer): void; + take(): Envelope | null; + next(): Promise; + close(): void; +} + +interface TeaVmRuntime { + wasmGC: { + load( + url: string, + options: { installImports?: (imports: Record) => void }, + ): Promise<{ exports: { main(args: string[]): void }; instance: WebAssembly.Instance }>; + }; +} + +/** The parts of a worker's scope this uses, so tests can supply their own. */ +export interface WorkerScope { + postMessage(message: unknown, transfer?: Transferable[]): void; + onmessage: ((event: { data: unknown }) => void) | null; + close(): void; + console: Console; + TeaVM?: TeaVmRuntime; + __incariParent?: ParentChannel; + /** The page's storage worker, for the program's file changes (platform-web's BrowserStore). */ + __incariStorage?: MessagePort | null; + /** Starts another copy of the program, in a worker of this one's (platform-web's JsChannel). */ + __incariStartWorker?: (role: string) => ParentChannel | null; + /** The single-file page's embedded files (offline.ts): where a script of theirs loads from. */ + incariFiles?: { url(href: string): string }; +} + +/** A worker of this one's, as `startChild` uses it. */ +export interface ChildWorker { + postMessage(message: unknown, transfer?: Transferable[]): void; + listen(onMessage: (data: unknown) => void, onError: (message: string) => void): void; + terminate(): void; +} + +/** What a worker of this one's is made with, so tests can supply their own. */ +export type WorkerFactory = (url: URL, options: WorkerOptions) => ChildWorker; + +/** A real worker, for `startChild`. */ +export function browserWorker(url: URL, options: WorkerOptions): ChildWorker { + const worker = new Worker(url, options); + return { + postMessage: (message, transfer) => { + worker.postMessage(message, transfer ?? []); + }, + listen(onMessage, onError) { + worker.onmessage = (event) => { + onMessage(event.data); + }; + worker.onerror = (event) => { + onError(event.message); + }; + }, + terminate: () => { + worker.terminate(); + }, + }; +} + +/** + * Starts the program again in a worker of this one's, with the build this one runs and in `role` + * (ADR 0042: singleplayer's server starts its terrain helpers so), and returns the channel to it: + * the same four calls the page has to this worker. + */ +export function startChild( + scope: Pick, + build: StartMessage["start"], + role: string, + createWorker: WorkerFactory, + scriptUrl: URL, +): ParentChannel { + const inbox = createInbox(); + const worker = createWorker(scriptUrl, { type: "module", name: `incari-${role}` }); + worker.listen( + (message) => { + const data = message as Partial; + if (data.kind === -1) { + inbox.push(null); + } else if (typeof data.kind === "number" && data.data instanceof ArrayBuffer) { + inbox.push({ kind: data.kind, data: data.data }); + } + }, + (error) => { + scope.console.error(`[Incari] The ${role} worker failed: ${error}`); + inbox.push(null); + }, + ); + worker.postMessage({ start: { ...build, role }, storage: null }); + return { + send(kind, data) { + worker.postMessage({ kind, data }, [data]); + }, + take: () => inbox.take(), + next: () => inbox.next(), + close() { + worker.postMessage({ kind: -1, data: new ArrayBuffer(0) }); + // It ends itself on that; this only makes sure. + setTimeout(() => { + worker.terminate(); + }, 5000); + inbox.push(null); + }, + }; +} + +/** A queue of envelopes that a waiting reader is handed as they come. */ +export function createInbox(): { + push(envelope: Envelope | null): void; + take(): Envelope | null; + next(): Promise; +} { + const queue: (Envelope | null)[] = []; + let waiting: ((envelope: Envelope | null) => void) | null = null; + let ended = false; + return { + push(envelope) { + if (ended) { + return; + } + if (envelope === null) { + ended = true; + } + if (waiting !== null) { + const resolve = waiting; + waiting = null; + resolve(envelope); + } else { + queue.push(envelope); + } + }, + take() { + const head = queue[0]; + if (head === undefined || head === null) { + return null; + } + queue.shift(); + return head; + }, + next() { + if (queue.length > 0) { + return Promise.resolve(queue.shift() ?? null); + } + return new Promise((resolve) => { + waiting = resolve; + }); + }, + }; +} + +/** Starts serving the page's messages on `scope`. */ +export function serve(scope: WorkerScope): void { + const inbox = createInbox(); + // Ends the program's waiting fibers before the worker goes, as the page does on `pagehide` + // (jspi.ts): a worker closed with suspended stacks crashed the tab's process later (ADR 0042). + let unwind = (): void => undefined; + let role = ""; + + scope.__incariParent = { + send(kind, data) { + scope.postMessage({ kind, data }, [data]); + }, + take: () => inbox.take(), + next: () => inbox.next(), + close() { + unwind(); + scope.postMessage({ kind: -1, data: new ArrayBuffer(0) }); + scope.close(); + }, + }; + + async function start(message: StartMessage["start"]): Promise { + // An import fetches without `fetch`, so the single-file page's shim can't answer it. + await import(scope.incariFiles?.url(message.runtime) ?? message.runtime); + const runtime = scope.TeaVM; + if (runtime === undefined) { + throw new Error(`${message.runtime} didn't define TeaVM's loader`); + } + const jspi = message.jspi + ? createJspiImports((error) => { + scope.console.error("[Incari] Worker:", error); + }) + : null; + const teavm = await runtime.wasmGC.load(message.module, { + installImports: (imports) => { + if (jspi !== null) { + imports.teavmJspi = jspi.module; + } + // Threads woken without the browser's 4 ms timer clamp (wakeups.ts). + imports.teavmAsync = createAsyncImports(); + }, + }); + jspi?.attach(teavm.instance.exports); + unwind = () => { + jspi?.terminate(); + }; + scope.__incariStartWorker = (role) => + typeof Worker === "undefined" + ? null + : startChild(scope, message, role, browserWorker, new URL("game-worker.js", import.meta.url)); + // main() returns at the program's first wait; the rest runs from this worker's event loop. + teavm.exports.main(["--worker", message.role, message.query ?? ""]); + } + + scope.onmessage = (event) => { + const data = event.data as Partial & Partial; + if (data.start !== undefined) { + scope.__incariStorage = data.storage ?? null; + role = data.start.role; + start(data.start).catch((error: unknown) => { + scope.console.error("[Incari] Worker: couldn't start the program:", error); + scope.postMessage({ kind: -1, data: new ArrayBuffer(0) }); + }); + } else if (data.kind === -1) { + inbox.push(null); + // A terrain helper has nothing to hand back: it ends with its server's channel. + if (role === "terrain") { + unwind(); + scope.close(); + } + } else if (typeof data.kind === "number" && data.data instanceof ArrayBuffer) { + inbox.push({ kind: data.kind, data: data.data }); + } + }; +} + +if (typeof (globalThis as { WorkerGlobalScope?: unknown }).WorkerGlobalScope !== "undefined") { + serve(globalThis as unknown as WorkerScope); +} diff --git a/incari-client/files/app-web/src/main/ts/jspi.ts b/incari-client/files/app-web/src/main/ts/jspi.ts new file mode 100644 index 0000000..c4c85b7 --- /dev/null +++ b/incari-client/files/app-web/src/main/ts/jspi.ts @@ -0,0 +1,120 @@ +/** + * The JavaScript side of the Fast build's fibers (WebAssembly JavaScript Promise Integration; TeaVM's + * patched `Fiber.Jspi` in tools/teavm-patches; ADR 0036). The Fast build has no coroutines: + * a Java thread that blocks calls `teavmJspi.await`, which hands the engine a promise, and the engine + * keeps the thread's whole WebAssembly stack until the promise settles. Each thread runs in its own + * call of the module's `teavm.jspi.run` export through `WebAssembly.promising`, so suspending one + * returns to whoever started it. The Compatible build imports none of this. + * + * The engine never frees a suspended stack, nor anything it reaches: a fiber still waiting when the + * page goes away would keep the whole program alive in the tab's process through every reload. So + * `terminate` (on `pagehide`) resumes each waiting fiber with an order to end, which it obeys with a + * trap that unwinds its stack past every Java handler. + */ + +/** What JSPI adds to `WebAssembly`; missing in engines without it. */ +interface JspiApi { + Suspending: new (fn: (...args: never[]) => unknown) => object; + promising: (fn: (...args: never[]) => unknown) => (...args: never[]) => Promise; +} + +/** The parts of the global scope the imports read, so tests can supply their own. */ +export interface JspiScope { + readonly WebAssembly?: object; +} + +export function supportsJspi(scope: JspiScope = globalThis): boolean { + const api = scope.WebAssembly as Partial | undefined; + return typeof api?.Suspending === "function" && typeof api.promising === "function"; +} + +export interface JspiImports { + /** The `teavmJspi` import module. */ + readonly module: Record; + /** Gives the imports the instance's exports, which they call to start a fiber. */ + attach(exports: Record): void; + /** Promises created and not yet settled or dropped, for tests and leak checks. */ + pending(): number; + /** Ends every fiber: each waiting one now, any other at its next wait. */ + terminate(): void; +} + +/** What a fiber's wait resumes with: carry on, or end (`Fiber.Jspi.suspend`). */ +const RESUME = 0; +const END = 1; + +/** + * Builds the `teavmJspi` imports. `fail` gets an error that escapes a fiber: it can't reach the + * starter's stack, which has moved on by the time the fiber's promise settles. + */ +export function createJspiImports(fail: (error: unknown) => void, scope: JspiScope = globalThis): JspiImports { + const api = scope.WebAssembly as JspiApi; + const promises = new Map; resolve: (value: number) => void }>(); + let nextId = 1; + let run: ((id: number) => Promise) | null = null; + let ending = false; + // The fibers' traps on the way out aren't failures. + const report = (error: unknown): void => { + if (!ending) { + fail(error); + } + }; + + const module: Record = { + create(): number { + const id = nextId++; + let resolve!: (value: number) => void; + const promise = new Promise((r) => { + resolve = r; + }); + promises.set(id, { promise, resolve }); + return id; + }, + // Hands the engine the promise: the calling fiber's stack waits for it. + await: new api.Suspending((id: number): Promise => { + const entry = promises.get(id); + if (entry === undefined) { + throw new Error(`No JSPI promise ${String(id)} to wait for`); + } + if (ending) { + promises.delete(id); + return Promise.resolve(END); + } + return entry.promise; + }), + resolve(id: number): void { + const entry = promises.get(id); + promises.delete(id); + entry?.resolve(ending ? END : RESUME); + }, + // A call that completed before its fiber had to wait. + drop(id: number): void { + promises.delete(id); + }, + run(id: number): void { + if (run === null) { + throw new Error("A fiber started before the module's exports were attached"); + } + // Returns once the fiber ends or first waits; the rest runs as its promises settle. + run(id).catch(report); + }, + }; + + return { + module, + attach(exports) { + const runExport = exports["teavm.jspi.run"]; + if (typeof runExport === "function") { + run = api.promising(runExport as (id: number) => unknown) as (id: number) => Promise; + } + }, + pending: () => promises.size, + terminate() { + ending = true; + for (const entry of promises.values()) { + entry.resolve(END); + } + promises.clear(); + }, + }; +} diff --git a/incari-client/files/app-web/src/main/ts/loader.ts b/incari-client/files/app-web/src/main/ts/loader.ts new file mode 100644 index 0000000..157f2fb --- /dev/null +++ b/incari-client/files/app-web/src/main/ts/loader.ts @@ -0,0 +1,266 @@ +/** + * The loader's decisions, kept apart from the page so they can be tested: which build to run, what + * the build manifest says, and how far a download has got. `boot.ts` does the page's side. + */ +import type { BrowserFeatures } from "./features.ts"; + +/** One file of the build, as `build.json` lists it. */ +export interface BuildFile { + readonly path: string; + readonly size: number; + /** Hex SHA-256 of the file: its version, so a cache can keep it until it changes. */ + readonly sha256: string; +} + +/** A build of the game: TeaVM's loader script and the WebAssembly GC module it loads. */ +export interface WasmTarget { + readonly runtime: string; + readonly module: string; + /** The development build's stack deobfuscator and its debug information, if it has them. */ + readonly deobfuscator?: string; + readonly debugInfo?: string; +} + +/** A program the page's workers run beside the game: its own module and loader. */ +export interface ProgramTarget { + readonly runtime: string; + readonly module: string; +} + +/** + * The Rust build (ADR 0068): Horizon's browser port with Incari's mods, a page of its own that the + * loader opens instead of loading a module. + */ +export interface RustTarget { + /** Its page, relative to this one. */ + readonly page: string; +} + +/** + * The builds of the game. What a player sees them called, and what they are: + * + * - **Fast**: suspends Java's threads through JSPI (JavaScript Promise Integration), so its code runs + * at full speed. It needs a browser with JSPI. WebAssembly GC, like Compatible (ADR 0036). + * - **Compatible**: emulates the threads with TeaVM's coroutines, which slows all of its code and + * doubles its size, but runs wherever WebAssembly GC does (Safari, older Chrome and Firefox). + * - **Rust**: experimental, a rewrite of the game in Rust drawing through WebGPU (ADR 0068). Never + * recommended; offered where WebGPU works and the copy includes it. + */ +export type BuildKind = "fast" | "compatible" | "rust"; + +/** + * `build.json`, which `:app-web:buildManifest` writes beside the builds: what there is to load, and + * each file's size and hash. A page served without one (an experiment's build) gets + * {@link DEFAULT_MANIFEST}. + */ +export interface BuildManifest { + readonly format: 2; + /** A hash over every file's: changes whenever any file does. */ + readonly id: string; + /** The game version the build is of. */ + readonly game: string; + readonly release: boolean; + readonly fast?: WasmTarget; + readonly compatible?: WasmTarget; + readonly rust?: RustTarget; + /** The asset pack (build-time data the game mounts read-only), if the build has one. */ + readonly pack?: string; + /** Programs for the page's workers, by name (`mesher`). */ + readonly programs?: Readonly>; + readonly files: readonly BuildFile[]; +} + +/** + * What an experiment's build (no `build.json`) has: TeaVM's development output as `incari.wasm`. It + * may be either kind; the page gives every module the Fast build's imports where the browser has + * JSPI (boot.ts), so a Fast experiment runs as this entry too. + */ +export const DEFAULT_MANIFEST: BuildManifest = { + format: 2, + id: "development", + game: "unknown", + release: false, + compatible: { + runtime: "incari.wasm-runtime.js", + module: "incari.wasm", + deobfuscator: "incari.wasm-deobfuscator.wasm", + debugInfo: "incari.wasm.teadbg", + }, + files: [], +}; + +/** Checks that `value` is a manifest this loader understands; throws saying what's wrong if not. */ +export function parseManifest(value: unknown): BuildManifest { + if (typeof value !== "object" || value === null) { + throw new Error("build.json isn't an object"); + } + const manifest = value as Partial; + if (manifest.format !== 2) { + throw new Error(`build.json has format ${String(manifest.format)}; this page reads format 2. Reload the page.`); + } + if (typeof manifest.id !== "string" || !Array.isArray(manifest.files)) { + throw new Error("build.json has no id or file list"); + } + if (manifest.fast === undefined && manifest.compatible === undefined && manifest.rust === undefined) { + throw new Error("build.json lists no build to run"); + } + return manifest as BuildManifest; +} + +/** The build to run, or why it can't run. */ +export type Choice = + | { readonly kind: "fast" | "compatible"; readonly target: WasmTarget } + | { readonly kind: "rust"; readonly target: RustTarget } + | { readonly kind: "unsupported"; readonly reason: string }; + +/** Why neither build can run without WebGL 2, the graphics floor for both; null if it's there. */ +export function missingWebgl2(features: BrowserFeatures): string | null { + return features.webgl2 + ? null + : "This browser can't run WebGL 2, which the game needs. Check that hardware acceleration is on."; +} + +/** Why neither build can run without WebAssembly GC; null if it's there. */ +export function missingWasmGc(features: BrowserFeatures): string | null { + return features.wasmGc + ? null + : "This browser is too old to run the game. Use Chrome or Edge 119, Firefox 120, Safari 18.2 or newer."; +} + +/** One build on the loading screen's choice: whether it can run here, and why not. */ +export interface BuildOption { + readonly kind: BuildKind; + readonly available: boolean; + /** Why it can't run: the browser lacks what it needs, or the build doesn't include it. */ + readonly reason?: string; +} + +/** + * The builds to offer, Fast first: it's the one to run wherever it works (far quicker, and a smaller + * download). Compatible is for browsers without JSPI. Rust comes last, and only when the copy has it. + */ +export function buildOptions(features: BrowserFeatures, manifest: BuildManifest): readonly BuildOption[] { + const fast: BuildOption = + manifest.fast === undefined + ? { kind: "fast", available: false, reason: "This copy of the game doesn't include Fast." } + : features.jspi + ? { kind: "fast", available: true } + : { + kind: "fast", + available: false, + reason: "Fast needs Chrome or Edge 137, Firefox 153 or newer.", + }; + const compatible: BuildOption = + manifest.compatible === undefined + ? { kind: "compatible", available: false, reason: "This copy of the game doesn't include Compatible." } + : { kind: "compatible", available: true }; + if (manifest.rust === undefined) { + return [fast, compatible]; + } + const rust: BuildOption = features.webgpu + ? { kind: "rust", available: true } + : { + kind: "rust", + available: false, + reason: "Rust needs WebGPU: Chrome or Edge 113 or newer, with a graphics card it supports.", + }; + return [fast, compatible, rust]; +} + +/** `?build=fast`, `compatible` or `rust`: a build asked for in the address, skipping the choice. */ +export function requestedBuild(value: string | null): BuildKind | null { + return value === "fast" || value === "compatible" || value === "rust" ? value : null; +} + +/** + * The option the choice starts on: the player's last pick if it can still run, else Fast if it can, + * else Compatible, and Rust only when nothing else runs. + */ +export function initialBuild(options: readonly BuildOption[], remembered: string | null): BuildKind { + const available = options.filter((option) => option.available).map((option) => option.kind); + const last = requestedBuild(remembered); + if (last !== null && available.includes(last)) { + return last; + } + return available.includes("fast") ? "fast" : available.includes("compatible") ? "compatible" : "rust"; +} + +/** The manifest's entry for a picked build, or why it can't run. */ +export function buildFor(kind: BuildKind, options: readonly BuildOption[], manifest: BuildManifest): Choice { + const option = options.find((o) => o.kind === kind); + const unsupported: Choice = { kind: "unsupported", reason: option?.reason ?? `No ${kind} build to run.` }; + if (option?.available !== true) { + return unsupported; + } + if (kind === "rust") { + return manifest.rust === undefined ? unsupported : { kind, target: manifest.rust }; + } + const target = kind === "fast" ? manifest.fast : manifest.compatible; + return target === undefined ? unsupported : { kind, target }; +} + +/** What the player calls a build. */ +export function buildName(kind: BuildKind): string { + return kind === "fast" ? "Fast" : kind === "compatible" ? "Compatible" : "Rust"; +} + +/** + * The Rust build's page with this page's address options, but `?build`: Horizon reads its own + * (`?args=`, its command line), and the rest it ignores. + */ +export function rustPage(target: RustTarget, here: string): string { + const url = new URL(target.page, here); + const search = new URL(here).searchParams; + search.delete("build"); + url.search = search.toString(); + return url.href; +} + +/** A file's URL with its hash as the version, so a cache keeps it exactly until it changes. */ +export function versioned(manifest: BuildManifest, path: string): string { + const file = manifest.files.find((f) => f.path === path); + return file === undefined ? path : `${path}?v=${file.sha256.slice(0, 16)}`; +} + +/** The size the manifest gives a file, or 0 if it doesn't list it. */ +export function sizeOf(manifest: BuildManifest, path: string): number { + return manifest.files.find((f) => f.path === path)?.size ?? 0; +} + +/** + * A response whose body reports each chunk as it's read, for a progress bar. Headers and status are + * kept, so `WebAssembly.compileStreaming` still accepts it (it needs `application/wasm`) and still + * compiles while the bytes arrive. + */ +export function countingResponse(response: Response, onBytes: (received: number) => void): Response { + const body = response.body; + if (body === null) { + return response; + } + let received = 0; + const counted = body.pipeThrough( + new TransformStream({ + transform(chunk, controller) { + received += chunk.byteLength; + onBytes(received); + controller.enqueue(chunk); + }, + }), + ); + return new Response(counted, { status: response.status, statusText: response.statusText, headers: response.headers }); +} + +/** A byte count for people: "12.3 MB". */ +export function formatBytes(bytes: number): string { + if (bytes < 1000) { + return `${String(bytes)} B`; + } + const units = ["kB", "MB", "GB"]; + let value = bytes / 1000; + let unit = 0; + while (value >= 1000 && unit < units.length - 1) { + value /= 1000; + unit++; + } + return `${value.toFixed(value < 10 ? 1 : 0)} ${units[unit] ?? "GB"}`; +} diff --git a/incari-client/files/app-web/src/main/ts/offline.ts b/incari-client/files/app-web/src/main/ts/offline.ts new file mode 100644 index 0000000..bbb9342 --- /dev/null +++ b/incari-client/files/app-web/src/main/ts/offline.ts @@ -0,0 +1,456 @@ +/** + * The single-file page (`./incari build --html`, ADR 0057): the whole build in one HTML file that + * opens straight from the disk. `tools/webbuild`'s `SingleFile` puts every file of the web folder in + * the page as base64 (gzipped where that helps) and this script in it, inline. It serves those files + * to the page and to every worker by the names they already fetch them by, so the game's code is the + * same as in the folder's build. + * + * A `file://` page can't fetch the files beside it, start a module worker from a Blob URL, or use the + * origin private file system, and its workers can't read the page's Blob URLs. A classic worker from + * a Blob URL works, shares the page's IndexedDB, and can import its own Blob URLs. So: + * + * - The page and every worker get a shim ({@link installFiles}) that answers `fetch`, + * `importScripts` and `new Worker` for the embedded files from their own Blobs. + * - A worker starts as a classic one that installs the shim, then runs its real script (as a module + * if one was asked for). + * - A worker asks the page through a port for a file it doesn't have yet. + * - The storage worker falls back to IndexedDB by itself. + * + * {@link installFiles} and {@link startWorker} are copied into each worker by their source text, so + * they use nothing from this module, only their parameters and the realm's globals. + */ + +/** What a realm's shim is set up with. Everything here can be posted to a worker. */ +export interface FileSetup { + /** The page's folder: relative URLs resolve against it everywhere, since a worker's own URL is a Blob's. */ + readonly base: string; + /** Every embedded file's path, decoded or not. */ + readonly paths: readonly string[]; + /** The files decoded so far, by path; the scripts always are, since `importScripts` can't wait. */ + readonly blobs: Readonly>; + /** The source of a worker's first script: {@link startWorker} given {@link installFiles}. */ + readonly shim: string; + /** In a worker: where to ask for a file it doesn't have. */ + readonly port?: MessagePort; + /** In a worker: the script it was started with, and whether to run it as a module. */ + readonly script?: WorkerScript; +} + +/** A worker's real script: an embedded file (`path`), or a Blob the page made from source. */ +export interface WorkerScript { + readonly path: string | null; + readonly blob: Blob; + readonly module: boolean; +} + +/** What a realm's shim offers its code. */ +export interface FileAccess { + /** The page's folder ({@link FileSetup.base}): resolve page-relative names against it, not `location`. */ + readonly base: string; + /** A URL this realm can load an embedded file's script from (a Blob URL), or `href` itself. */ + url(href: string): string; + /** A Blob URL of an embedded module whose relative imports point at Blob URLs of their own. */ + moduleUrl(path: string): Promise; + /** Runs a worker's real script. */ + start(script: WorkerScript): Promise; +} + +/** The globals the shim replaces or uses. */ +export interface FileScope { + fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise; + Worker?: new (url: string | URL, options?: WorkerOptions) => Worker; + importScripts?: (...urls: string[]) => void; + incariFiles?: FileAccess; +} + +/** A file the page decodes when it's first asked for. */ +export type Decoder = (path: string) => Promise; + +/** + * Installs the shim on `scope`. `decode` is the page's; a worker asks `setup.port` instead. + * Self-contained: copied into workers by its source. + */ +export function installFiles(scope: FileScope, setup: FileSetup, decode?: Decoder): FileAccess { + const all = new Set(setup.paths); + const blobs = new Map(Object.entries(setup.blobs)); + const pending = new Map>(); + // Blob URLs made in this realm: by embedded file, and the modules' back to their file, so a worker + // started from `import.meta.url` (game-worker.ts) is one of the files again. + const urls = new Map(); + const modules = new Map>(); + const moduleFiles = new Map(); + // Script Blobs this realm made URLs of (the storage and program workers' sources), to start + // those workers from. + const scripts = new Map(); + const realFetch = scope.fetch.bind(scope); + const RealWorker = scope.Worker; + const realImportScripts = scope.importScripts?.bind(scope); + const createObjectUrl = URL.createObjectURL.bind(URL); + const revokeObjectUrl = URL.revokeObjectURL.bind(URL); + + const asked = new Map void>(); + let nextAsk = 0; + const port = setup.port; + if (port !== undefined) { + port.onmessage = (event: MessageEvent<{ id: number; blob: Blob | null }>) => { + asked.get(event.data.id)?.(event.data.blob); + asked.delete(event.data.id); + }; + } + const fromPage: Decoder = + decode ?? + ((path) => + port === undefined + ? Promise.resolve(null) + : new Promise((resolve) => { + const id = nextAsk++; + asked.set(id, resolve); + port.postMessage({ id, path }); + })); + + /** The embedded file `url` names, relative to the page's folder, or null if it names none. */ + function fileOf(url: string): string | null { + const module = moduleFiles.get(url); + if (module !== undefined) { + return module; + } + let href: string; + try { + href = new URL(url, setup.base).href; + } catch { + return null; + } + if (!href.startsWith(setup.base)) { + return null; + } + // Versioned URLs (`?v=`, loader.ts) name the same file. + const path = decodeURIComponent(href.slice(setup.base.length).replace(/[?#].*$/s, "")); + return all.has(path) ? path : null; + } + + function blobOf(path: string): Promise { + const known = blobs.get(path); + if (known !== undefined) { + return Promise.resolve(known); + } + let waiting = pending.get(path); + if (waiting === undefined) { + waiting = fromPage(path).then((blob) => { + if (blob !== null) { + blobs.set(path, blob); + } + return blob; + }); + pending.set(path, waiting); + } + return waiting; + } + + function urlOf(path: string): string { + let url = urls.get(path); + if (url === undefined) { + const blob = blobs.get(path); + if (blob === undefined) { + throw new Error(`${path} isn't loaded yet`); + } + url = createObjectUrl(blob); + urls.set(path, url); + } + return url; + } + + /** The page's scripts import no cycle, so each module's imports are made first. */ + function moduleUrl(path: string): Promise { + let made = modules.get(path); + if (made === undefined) { + made = (async () => { + const blob = await blobOf(path); + if (blob === null) { + throw new Error(`No ${path} in this file`); + } + const source = await blob.text(); + const imports = /(\b(?:from|import)\s*\(?\s*)(["'])(\.{1,2}\/[^"'\n]+)\2/g; + const targets = new Map(); + for (const match of source.matchAll(imports)) { + const specifier = match[3] ?? ""; + const target = fileOf(new URL(specifier, setup.base + path).href); + if (target !== null && !targets.has(specifier)) { + targets.set(specifier, await moduleUrl(target)); + } + } + const rewritten = source.replace(imports, (whole: string, before: string, quote: string, specifier: string) => { + const target = targets.get(specifier); + return target === undefined ? whole : before + quote + target + quote; + }); + const url = createObjectUrl(new Blob([rewritten], { type: "text/javascript" })); + moduleFiles.set(url, path); + return url; + })(); + modules.set(path, made); + } + return made; + } + + scope.fetch = async (input, init) => { + const path = fileOf(input instanceof Request ? input.url : String(input)); + if (path === null) { + return realFetch(input, init); + } + const blob = await blobOf(path); + return blob === null ? new Response(null, { status: 404, statusText: "Not Found" }) : new Response(blob); + }; + + URL.createObjectURL = (object) => { + const url = createObjectUrl(object); + if (object instanceof Blob && object.type.includes("javascript")) { + scripts.set(url, object); + } + return url; + }; + URL.revokeObjectURL = (url) => { + scripts.delete(url); + revokeObjectUrl(url); + }; + + if (realImportScripts !== undefined) { + scope.importScripts = (...requested) => { + realImportScripts( + ...requested.map((url) => { + const path = fileOf(url); + return path === null ? url : urlOf(path); + }), + ); + }; + } + + let shimUrl: string | null = null; + if (RealWorker !== undefined) { + // A function, not a class: `new` returns the real worker it makes. + const OfflineWorker = function (url: string | URL, options?: WorkerOptions): Worker { + const href = String(url); + const path = fileOf(href); + const blob = path === null ? scripts.get(href) : blobs.get(path); + if (blob === undefined) { + return new RealWorker(url, options); + } + shimUrl ??= createObjectUrl(new Blob([setup.shim], { type: "text/javascript" })); + const worker = new RealWorker(shimUrl, options?.name === undefined ? {} : { name: options.name }); + const channel = new MessageChannel(); + channel.port1.onmessage = (event: MessageEvent<{ id: number; path: string }>) => { + void blobOf(event.data.path).then((found) => { + channel.port1.postMessage({ id: event.data.id, blob: found }); + }); + }; + const files: FileSetup = { + base: setup.base, + paths: setup.paths, + blobs: Object.fromEntries(blobs), + shim: setup.shim, + port: channel.port2, + script: { path, blob, module: options?.type === "module" }, + }; + worker.postMessage({ incariFiles: files }, [channel.port2]); + return worker; + }; + scope.Worker = OfflineWorker as unknown as new (url: string | URL, options?: WorkerOptions) => Worker; + } + + const access: FileAccess = { + base: setup.base, + url(href) { + const path = fileOf(href); + return path === null ? href : urlOf(path); + }, + moduleUrl, + async start(script) { + if (script.module) { + await import(script.path === null ? createObjectUrl(script.blob) : await moduleUrl(script.path)); + } else if (realImportScripts !== undefined) { + realImportScripts(createObjectUrl(script.blob)); + } + }, + }; + scope.incariFiles = access; + return access; +} + +/** The parts of a worker's scope {@link startWorker} uses. */ +export interface StartScope extends FileScope { + addEventListener(type: "message", listener: (event: MessageEvent) => void): void; + removeEventListener(type: "message", listener: (event: MessageEvent) => void): void; + dispatchEvent(event: Event): boolean; + setTimeout(handler: () => void, timeout: number): unknown; +} + +/** + * A worker's first script: waits for the page's files, installs the shim, and runs the real script. + * Messages that come before that script listens are held and handed to it in order. Self-contained: + * copied into workers by its source. + */ +export function startWorker(scope: StartScope, install: typeof installFiles): void { + const held: MessageEvent[] = []; + const hold = (event: MessageEvent): void => { + held.push(event); + }; + const first = (event: MessageEvent<{ incariFiles?: FileSetup } | null>): void => { + const setup = event.data?.incariFiles; + if (setup?.script === undefined) { + return; + } + scope.removeEventListener("message", first); + scope.addEventListener("message", hold); + install(scope, setup) + .start(setup.script) + .then( + () => { + scope.removeEventListener("message", hold); + for (const message of held.splice(0)) { + scope.dispatchEvent(new MessageEvent("message", { data: message.data, ports: [...message.ports] })); + } + }, + (error: unknown) => { + // An uncaught error, so the worker's `onerror` on the other side hears of it. + scope.setTimeout(() => { + throw error; + }, 0); + }, + ); + }; + scope.addEventListener("message", first); +} + +/** The source of a worker's first script. */ +export function shimSource(): string { + return `"use strict";\n(${startWorker.toString()})(self, ${installFiles.toString()});\n`; +} + +/** How `SingleFile` marks an embedded file: ` + + diff --git a/incari-client/files/app-web/src/test/java/incari/app/web/memory/MemoryParityTest.java b/incari-client/files/app-web/src/test/java/incari/app/web/memory/MemoryParityTest.java new file mode 100644 index 0000000..2000687 --- /dev/null +++ b/incari-client/files/app-web/src/test/java/incari/app/web/memory/MemoryParityTest.java @@ -0,0 +1,70 @@ +package incari.app.web.memory; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.mojang.blaze3d.vertex.BufferBuilder; +import incari.platform.api.Platform; +import incari.platform.api.Platforms; +import incari.platform.api.threads.PlatformThreads; +import java.lang.reflect.Proxy; +import java.util.Map; +import java.util.Set; +import java.util.function.Supplier; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +/** + * The memory layer's gate (ADR 0008): the game's vertex and image code writes the same bytes over web-classlib's memory + * as over LWJGL's. {@link MemoryScenario} runs twice, once as the desktop game runs it (LWJGL's + * {@code MemoryUtil}, STB's PNG decoder) and once with the game's classes linked to the browser + * build's stand-ins ({@link SubstitutingClassLoader}), and every result must match to the byte. + * + *

This covers the stand-ins' logic and the heap's bookkeeping with its JVM backend; the browser + * probe runs the same scenario over linear memory and prints {@link MemoryScenario#digest}s to compare with these. + */ +class MemoryParityTest { + + /** + * What the game's static initializers ask of the platform while these classes load: how many + * background threads {@code Util} may start. Anything else fails loudly. + */ + @BeforeAll + static void installPlatform() { + if (Platforms.isInstalled()) { + return; + } + PlatformThreads inline = suggested -> 0; + Platforms.install((Platform) Proxy.newProxyInstance( + Platform.class.getClassLoader(), + new Class[] {Platform.class}, + (proxy, method, args) -> switch (method.getName()) { + case "threads" -> inline; + case "nanoTime" -> System.nanoTime(); + case "toString" -> "MemoryParityTest platform"; + default -> throw new UnsupportedOperationException(method.getName()); + })); + } + + @Test + void vertexAndImageBytesMatchVanilla() throws Exception { + Map vanilla = new MemoryScenario().get(); + + SubstitutingClassLoader loader = new SubstitutingClassLoader( + getClass().getClassLoader(), BufferBuilder.class, Set.of(MemoryScenario.class.getName())); + @SuppressWarnings("unchecked") // The scenario's type, loaded again. + Supplier> substituted = + (Supplier>) loader.loadClass(MemoryScenario.class.getName()) + .getConstructor() + .newInstance(); + Map browser = substituted.get(); + + assertThat(browser.keySet()).containsExactlyElementsOf(vanilla.keySet()); + for (Map.Entry result : vanilla.entrySet()) { + assertThat(result.getValue()).as(result.getKey()).isNotEmpty(); + assertThat(browser.get(result.getKey())).as(result.getKey()).isEqualTo(result.getValue()); + } + System.out.println("Memory parity: " + vanilla.size() + " results match; " + loader.reloadedCount() + + " game classes linked to the stand-ins"); + vanilla.forEach((name, bytes) -> System.out.println(" " + name + " " + MemoryScenario.digest(bytes))); + } +} diff --git a/incari-client/files/app-web/src/test/java/incari/app/web/memory/MemoryScenario.java b/incari-client/files/app-web/src/test/java/incari/app/web/memory/MemoryScenario.java new file mode 100644 index 0000000..8725a96 --- /dev/null +++ b/incari-client/files/app-web/src/test/java/incari/app/web/memory/MemoryScenario.java @@ -0,0 +1,425 @@ +package incari.app.web.memory; + +import com.mojang.blaze3d.buffers.Std140Builder; +import com.mojang.blaze3d.platform.NativeImage; +import com.mojang.blaze3d.vertex.BufferBuilder; +import com.mojang.blaze3d.vertex.ByteBufferBuilder; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.MeshData; +import com.mojang.blaze3d.vertex.VertexSorting; +import com.mojang.renderpearl.api.pipeline.PrimitiveTopology; +import com.mojang.renderpearl.api.vertex.VertexFormat; +import com.mojang.renderpearl.api.vertex.VertexFormatElement; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.function.Supplier; +import java.util.zip.CRC32; +import java.util.zip.Deflater; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.MemoryUtil; + +/** + * The game's own off-heap memory users, run through whatever {@code MemoryUtil} the class loader + * binds: LWJGL's on the desktop, web-classlib's stand-in in the browser build or under + * {@link SubstitutingClassLoader}. Vertices through {@code BufferBuilder}'s fast and generic paths, + * sorted index buffers, {@code ByteBufferBuilder}'s growth and compaction, {@code NativeImage} + * pixels and PNG decoding, a uniform block on the {@code MemoryStack}, and {@code MemoryUtil} + * directly. Each result is the bytes the game would hand the GPU, by name. + * + *

Deterministic: its own generator, not {@code Random}. Bytes the game leaves unwritten (the + * fourth byte of a packed normal) come from {@code malloc} and are garbage, so they're zeroed in + * the copies returned. Also compiled into a browser probe, so it uses nothing TeaVM lacks. + */ +public final class MemoryScenario implements Supplier> { + + private int seed = 0x1234567; + + @Override + public Map get() { + Map out = new LinkedHashMap<>(); + try { + entityQuads(out); + blockQuads(out); + genericFormats(out); + compaction(out); + images(out); + pngs(out); + uniforms(out); + memoryUtil(out); + } catch (IOException e) { + throw new IllegalStateException(e); + } + return out; + } + + /** The entity fast path, then the quads sorted back to front, as translucent geometry is. */ + private void entityQuads(Map out) { + // Small, so the builder grows (reallocates) several times. + try (ByteBufferBuilder vertices = new ByteBufferBuilder(64); + ByteBufferBuilder indices = new ByteBufferBuilder(16)) { + BufferBuilder builder = new BufferBuilder(vertices, PrimitiveTopology.QUADS, DefaultVertexFormat.ENTITY); + for (int i = 0; i < 4 * 700; i++) { + builder.addVertex( + coordinate(), + coordinate(), + coordinate(), + next(), + unit(), + unit(), + next() & 0xFFFF_FFFF, + next(), + signed(), + signed(), + signed()); + } + try (MeshData mesh = builder.buildOrThrow()) { + out.put("entity.vertices", vertexBytes(mesh.vertexBuffer(), DefaultVertexFormat.ENTITY)); + mesh.sortQuads(indices, VertexSorting.byDistance(3.0F, -2.0F, 5.0F)); + ByteBuffer sorted = mesh.indexBuffer(); + out.put("entity.indices", bytes(sorted == null ? ByteBuffer.allocate(0) : sorted)); + } + } + } + + private void blockQuads(Map out) { + try (ByteBufferBuilder vertices = new ByteBufferBuilder(256)) { + BufferBuilder builder = new BufferBuilder(vertices, PrimitiveTopology.QUADS, DefaultVertexFormat.BLOCK); + for (int i = 0; i < 4 * 300; i++) { + builder.addVertex( + coordinate(), coordinate(), coordinate(), next(), unit(), unit(), 0, next(), 0.0F, 1.0F, 0.0F); + } + try (MeshData mesh = builder.buildOrThrow()) { + out.put("block.vertices", vertexBytes(mesh.vertexBuffer(), DefaultVertexFormat.BLOCK)); + } + } + } + + /** Element by element, the path most of the GUI and debug renderers take. */ + private void genericFormats(Map out) { + try (ByteBufferBuilder vertices = new ByteBufferBuilder(32)) { + BufferBuilder lines = new BufferBuilder( + vertices, PrimitiveTopology.LINES, DefaultVertexFormat.POSITION_COLOR_NORMAL_LINE_WIDTH); + for (int i = 0; i < 4 * 50; i++) { + lines.addVertex(coordinate(), coordinate(), coordinate()) + .setColor(next()) + .setNormal(signed(), signed(), signed()) + .setLineWidth(unit() * 4.0F); + } + try (MeshData mesh = lines.buildOrThrow()) { + out.put( + "lines.vertices", + vertexBytes(mesh.vertexBuffer(), DefaultVertexFormat.POSITION_COLOR_NORMAL_LINE_WIDTH)); + } + BufferBuilder gui = new BufferBuilder( + vertices, PrimitiveTopology.TRIANGLES, DefaultVertexFormat.POSITION_TEX_LIGHTMAP_COLOR); + for (int i = 0; i < 3 * 90; i++) { + gui.addVertex(coordinate(), coordinate(), 0.0F) + .setUv(unit(), unit()) + .setLight(next()) + .setColor(next() & 0xFF, next() & 0xFF, next() & 0xFF, next() & 0xFF); + } + try (MeshData mesh = gui.buildOrThrow()) { + out.put( + "gui.vertices", + vertexBytes(mesh.vertexBuffer(), DefaultVertexFormat.POSITION_TEX_LIGHTMAP_COLOR)); + } + } + } + + /** + * Two meshes built from one buffer while a third is being written: closing both moves the + * unfinished one to the buffer's start with an overlapping {@code memCopy}. + */ + private void compaction(Map out) { + try (ByteBufferBuilder shared = new ByteBufferBuilder(128)) { + MeshData first = quads(shared, 3); + MeshData second = quads(shared, 5); + out.put("compaction.second", vertexBytes(second.vertexBuffer(), DefaultVertexFormat.POSITION_COLOR)); + BufferBuilder third = + new BufferBuilder(shared, PrimitiveTopology.QUADS, DefaultVertexFormat.POSITION_COLOR); + for (int i = 0; i < 4 * 7; i++) { + third.addVertex(coordinate(), coordinate(), coordinate()).setColor(next()); + } + first.close(); + second.close(); + try (MeshData mesh = third.buildOrThrow()) { + out.put("compaction.third", vertexBytes(mesh.vertexBuffer(), DefaultVertexFormat.POSITION_COLOR)); + } + } + } + + private MeshData quads(ByteBufferBuilder buffer, int count) { + BufferBuilder builder = new BufferBuilder(buffer, PrimitiveTopology.QUADS, DefaultVertexFormat.POSITION_COLOR); + for (int i = 0; i < 4 * count; i++) { + builder.addVertex(coordinate(), coordinate(), coordinate()).setColor(next()); + } + return builder.buildOrThrow(); + } + + private void images(Map out) { + try (NativeImage image = new NativeImage(37, 23, false); + NativeImage zeroed = new NativeImage(NativeImage.Format.RGBA, 16, 16, true); + NativeImage wide = new NativeImage(41, 23, true)) { + for (int y = 0; y < image.getHeight(); y++) { + for (int x = 0; x < image.getWidth(); x++) { + image.setPixel(x, y, next()); + } + } + image.fillRect(3, 4, 9, 5, 0x80FF4020); + image.copyRect(0, 0, 20, 10, 12, 8, true, false); + image.copyRect(zeroed, 5, 5, 2, 2, 10, 10, false, true); + wide.copyFrom(image); + out.put("image.pixels", bytes(image.getPixelBytes())); + out.put("image.zeroed", bytes(zeroed.getPixelBytes())); + out.put("image.wide", bytes(wide.getPixelBytes())); + try (NativeImage mapped = image.mappedCopy(argb -> argb ^ 0x00FF00FF)) { + out.put("image.mapped", bytes(mapped.getPixelBytes())); + out.put("image.abgr", ints(mapped.getPixelsABGR())); + } + byte[] luminance = new byte[16]; + try (NativeImage alpha = new NativeImage(NativeImage.Format.LUMINANCE_ALPHA, 4, 4, true)) { + for (int i = 0; i < luminance.length; i++) { + luminance[i] = alpha.getLuminanceOrAlpha(i % 4, i / 4); + } + } + out.put("image.luminance", luminance); + } + } + + /** PNGs of every colour type and row filter, decoded by STB on the desktop and PngDecoder in the browser. */ + private void pngs(Map out) throws IOException { + int[][] kinds = {{6, 4}, {2, 3}, {0, 1}, {4, 2}, {3, 1}}; + for (int[] kind : kinds) { + byte[] png = png(29, 17, kind[0], kind[1]); + // byte[] reads through the MemoryStack; an InputStream through memAlloc and memRealloc. + try (NativeImage fromBytes = NativeImage.read(png); + NativeImage fromStream = NativeImage.read(new ByteArrayInputStream(png))) { + out.put("png.type" + kind[0], bytes(fromBytes.getPixelBytes())); + out.put("png.type" + kind[0] + ".stream", bytes(fromStream.getPixelBytes())); + } + } + // Larger than the stack, so NativeImage.read(byte[]) takes memAlloc instead. + byte[] big = png(300, 120, 6, 4); + try (NativeImage image = NativeImage.read(big)) { + out.put("png.big", bytes(image.getPixelBytes())); + } + } + + private void uniforms(Map out) { + try (MemoryStack stack = MemoryStack.stackPush()) { + ByteBuffer block = Std140Builder.onStack(stack, 96) + .putVec4(unit(), unit(), unit(), unit()) + .putIVec4(next(), next(), next(), next()) + .putVec3(unit(), unit(), unit()) + .putFloat(unit()) + .putVec2(unit(), unit()) + .putIVec2(next(), next()) + .putInt(next()) + .putFloat(unit()) + .putVec2(unit(), unit()) + .get(); + out.put("std140", bytes(block)); + java.nio.IntBuffer ints = stack.callocInt(5); + ints.put(2, next()); + out.put("stack.ints", bytes(MemoryUtil.memByteBuffer(MemoryUtil.memAddress(ints), 20))); + } + } + + private void memoryUtil(Map out) { + long address = MemoryUtil.nmemCalloc(8, 8); + MemoryUtil.memPutInt(address, 0x11223344); + MemoryUtil.memPutFloat(address + 4, 1.25F); + MemoryUtil.memPutShort(address + 8, (short) -2); + MemoryUtil.memPutByte(address + 10, (byte) 0x7F); + // Overlapping, to a lower address, as ByteBufferBuilder compacts. (LWJGL's memCopy is + // memcpy: an overlap the other way gives different bytes on different machines.) + MemoryUtil.memCopy(address + 3, address + 1, 11); + ByteBuffer text = MemoryUtil.memUTF8("héllo, wörld"); + long copy = MemoryUtil.nmemAlloc(text.remaining() + 1); + MemoryUtil.memCopy(MemoryUtil.memAddress(text), copy, text.remaining() + 1); + String back = MemoryUtil.memUTF8(copy); + ByteBuffer grown = MemoryUtil.memRealloc(MemoryUtil.memAlloc(4).putInt(0, 42), 4096); + ByteArrayOutputStream result = new ByteArrayOutputStream(); + append(result, bytes(MemoryUtil.memByteBuffer(address, 64))); + append(result, back.getBytes(StandardCharsets.UTF_8)); + result.write(MemoryUtil.memGetInt(address + 3)); + result.write(MemoryUtil.memGetByte(address + 13)); + result.write(grown.getInt(0)); + result.write(grown.capacity() >> 8); + MemoryUtil.memFree(grown); + MemoryUtil.nmemFree(copy); + MemoryUtil.memFree(text); + MemoryUtil.nmemFree(address); + out.put("memoryutil", result.toByteArray()); + } + + // --- PNG files, written here so the check needs no game assets ------------------------------ + + /** + * A {@code width}x{@code height} 8-bit PNG of {@code colorType} (0 grey, 2 RGB, 3 palette, 4 + * grey and alpha, 6 RGBA), its rows filtered by each of the five filters in turn. + */ + private byte[] png(int width, int height, int colorType, int channels) { + byte[][] rows = new byte[height][width * channels]; + for (byte[] row : rows) { + for (int i = 0; i < row.length; i++) { + // Some runs of equal bytes, so the filters have something to predict. + row[i] = (byte) ((next() & 3) == 0 ? next() : i * 7); + } + } + ByteArrayOutputStream raw = new ByteArrayOutputStream(); + byte[] previous = new byte[width * channels]; + for (int y = 0; y < height; y++) { + int filter = y % 5; + raw.write(filter); + append(raw, filtered(rows[y], previous, channels, filter)); + previous = rows[y]; + } + ByteArrayOutputStream file = new ByteArrayOutputStream(); + append(file, new byte[] {(byte) 0x89, 'P', 'N', 'G', '\r', '\n', 0x1A, '\n'}); + ByteArrayOutputStream header = new ByteArrayOutputStream(); + writeInt(header, width); + writeInt(header, height); + append(header, new byte[] {8, (byte) colorType, 0, 0, 0}); + chunk(file, "IHDR", header.toByteArray()); + if (colorType == 3) { + byte[] palette = new byte[256 * 3]; + byte[] alpha = new byte[256]; + for (int i = 0; i < 256; i++) { + palette[i * 3] = (byte) i; + palette[i * 3 + 1] = (byte) (255 - i); + palette[i * 3 + 2] = (byte) (i * 3); + alpha[i] = (byte) (i * 5); + } + chunk(file, "PLTE", palette); + chunk(file, "tRNS", alpha); + } + Deflater deflater = new Deflater(); + deflater.setInput(raw.toByteArray()); + deflater.finish(); + ByteArrayOutputStream packed = new ByteArrayOutputStream(); + byte[] chunk = new byte[4096]; + while (!deflater.finished()) { + packed.write(chunk, 0, deflater.deflate(chunk)); + } + deflater.end(); + chunk(file, "IDAT", packed.toByteArray()); + chunk(file, "IEND", new byte[0]); + return file.toByteArray(); + } + + private static byte[] filtered(byte[] row, byte[] above, int stride, int filter) { + byte[] result = new byte[row.length]; + for (int i = 0; i < row.length; i++) { + int a = i >= stride ? row[i - stride] & 0xFF : 0; + int b = above[i] & 0xFF; + int c = i >= stride ? above[i - stride] & 0xFF : 0; + int prediction = + switch (filter) { + case 1 -> a; + case 2 -> b; + case 3 -> (a + b) / 2; + case 4 -> paeth(a, b, c); + default -> 0; + }; + result[i] = (byte) (row[i] - prediction); + } + return result; + } + + private static int paeth(int a, int b, int c) { + int p = a + b - c; + int pa = Math.abs(p - a); + int pb = Math.abs(p - b); + int pc = Math.abs(p - c); + return pa <= pb && pa <= pc ? a : pb <= pc ? b : c; + } + + private static void chunk(ByteArrayOutputStream file, String type, byte[] data) { + byte[] name = type.getBytes(StandardCharsets.US_ASCII); + writeInt(file, data.length); + append(file, name); + append(file, data); + CRC32 crc = new CRC32(); + crc.update(name); + crc.update(data); + writeInt(file, (int) crc.getValue()); + } + + /** {@code out.writeBytes(bytes)}, which TeaVM's class library lacks. */ + private static void append(ByteArrayOutputStream out, byte[] bytes) { + out.write(bytes, 0, bytes.length); + } + + private static void writeInt(ByteArrayOutputStream out, int value) { + out.write(value >>> 24); + out.write(value >>> 16); + out.write(value >>> 8); + out.write(value); + } + + // --- Values and bytes --------------------------------------------------------------------- + + /** xorshift32: the same sequence on every platform. */ + private int next() { + seed ^= seed << 13; + seed ^= seed >>> 17; + seed ^= seed << 5; + return seed; + } + + private float unit() { + return (next() >>> 8) / (float) (1 << 24); + } + + private float signed() { + return unit() * 2.0F - 1.0F; + } + + private float coordinate() { + return (unit() - 0.5F) * 64.0F; + } + + /** + * A result's fingerprint, to compare a browser run with a desktop one by eye: 64-bit FNV-1a + * (TeaVM has no {@code MessageDigest}). + */ + public static String digest(byte[] bytes) { + long hash = 0xcbf29ce484222325L; + for (byte b : bytes) { + hash = (hash ^ (b & 0xFF)) * 0x100000001b3L; + } + return Long.toHexString(hash) + "/" + bytes.length; + } + + /** A buffer's remaining bytes, from its own position; the buffer doesn't move. */ + private static byte[] bytes(ByteBuffer buffer) { + byte[] bytes = new byte[buffer.remaining()]; + buffer.duplicate().get(bytes); + return bytes; + } + + private static byte[] ints(int[] values) { + ByteBuffer buffer = ByteBuffer.allocate(values.length * 4); + buffer.asIntBuffer().put(values); + return buffer.array(); + } + + /** Vertex bytes with the padding byte after each packed normal cleared (malloc leaves it unset). */ + private static byte[] vertexBytes(ByteBuffer vertices, VertexFormat format) { + byte[] bytes = bytes(vertices); + VertexFormatElement normal = format.getElement("Normal"); + if (normal != null) { + int stride = format.getVertexSize(); + for (int at = normal.offset() + 3; at < bytes.length; at += stride) { + bytes[at] = 0; + } + } + return bytes; + } +} diff --git a/incari-client/files/app-web/src/test/java/incari/app/web/memory/SubstitutingClassLoader.java b/incari-client/files/app-web/src/test/java/incari/app/web/memory/SubstitutingClassLoader.java new file mode 100644 index 0000000..b17a1d2 --- /dev/null +++ b/incari-client/files/app-web/src/test/java/incari/app/web/memory/SubstitutingClassLoader.java @@ -0,0 +1,222 @@ +package incari.app.web.memory; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayDeque; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.stream.Stream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; +import org.jspecify.annotations.Nullable; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.commons.ClassRemapper; +import org.objectweb.asm.commons.Remapper; + +/** + * Loads the game's classes as the browser build links them, as far as memory goes: every + * reference to an LWJGL class that {@code web-classlib} stands in for ({@code MemoryUtil}, + * {@code MemoryStack}, {@code STBImage}...) is renamed to the stand-in, the way TeaVM's + * substitution does it, and the stand-ins run on this JVM. + * + *

Only the classes that need it are loaded again here: those that name a stand-in's class, and + * those that name one of them, and so on. Everything else, the stand-ins included, comes from the + * parent, so the game's shared data (vertex formats, enums) is the same objects on both sides. + * The {@code roots} are test classes that drive the game and are loaded here too. + */ +final class SubstitutingClassLoader extends ClassLoader { + + private static final String SUBSTITUTES = "incari/classlib/substitutes/"; + + private final Set reloaded; + private final Remapper remapper; + + SubstitutingClassLoader(ClassLoader parent, Class gameClass, Set roots) { + super("substituting", parent); + Map> references = references(gameClass); + for (String root : roots) { + references.put(root.replace('.', '/'), referencesOf(readParent(root.replace('.', '/')))); + } + this.reloaded = closure(references); + this.reloaded.addAll(roots.stream().map(root -> root.replace('.', '/')).toList()); + this.remapper = new Remapper(Opcodes.ASM9) { + @Override + public String map(String internalName) { + String substitute = substituteFor(internalName); + return substitute != null ? substitute : internalName; + } + }; + } + + /** How many of the game's classes are loaded again, for the test's report. */ + int reloadedCount() { + return reloaded.size(); + } + + @Override + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + synchronized (getClassLoadingLock(name)) { + if (!reloaded.contains(name.replace('.', '/'))) { + return super.loadClass(name, resolve); + } + Class loaded = findLoadedClass(name); + if (loaded == null) { + ClassWriter writer = new ClassWriter(0); + new ClassReader(readParent(name.replace('.', '/'))).accept(new ClassRemapper(writer, remapper), 0); + byte[] bytes = writer.toByteArray(); + loaded = defineClass(name, bytes, 0, bytes.length); + } + if (resolve) { + resolveClass(loaded); + } + return loaded; + } + } + + /** {@code org/lwjgl/system/MemoryUtil$MemoryAllocator} to its stand-in's name, if web-classlib has one. */ + private @Nullable String substituteFor(String internalName) { + if (!internalName.startsWith("org/lwjgl/")) { + return null; + } + int slash = internalName.lastIndexOf('/'); + String candidate = SUBSTITUTES + internalName.substring(0, slash + 1) + "T" + internalName.substring(slash + 1); + return getParent().getResource(candidate + ".class") != null ? candidate : null; + } + + private byte[] readParent(String internalName) { + try (InputStream in = getParent().getResourceAsStream(internalName + ".class")) { + if (in == null) { + throw new IllegalStateException("No class file for " + internalName); + } + return in.readAllBytes(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + /** The classes each class of the game names, read from the jar or directory {@code gameClass} came from. */ + private static Map> references(Class gameClass) { + Map> references = new HashMap<>(); + try { + Path location = Path.of(gameClass + .getProtectionDomain() + .getCodeSource() + .getLocation() + .toURI()); + if (Files.isDirectory(location)) { + try (Stream files = Files.walk(location)) { + for (Path file : (Iterable) files::iterator) { + String relative = location.relativize(file).toString().replace('\\', '/'); + if (relative.endsWith(".class")) { + references.put( + relative.substring(0, relative.length() - 6), + referencesOf(Files.readAllBytes(file))); + } + } + } + } else { + try (ZipInputStream zip = new ZipInputStream(Files.newInputStream(location))) { + for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) { + String name = entry.getName(); + if (name.endsWith(".class") && !name.startsWith("META-INF/")) { + references.put(name.substring(0, name.length() - 6), referencesOf(zip.readAllBytes())); + } + } + } + } + } catch (IOException e) { + throw new UncheckedIOException(e); + } catch (URISyntaxException e) { + throw new IllegalStateException(e); + } + return references; + } + + /** + * Every class a class file names, loosely: each UTF-8 constant as a name itself (what class + * entries point at) and the {@code Lpkg/Name;} names inside it (descriptors and signatures). + * Names that aren't classes are harmless; they match nothing. + */ + private static Set referencesOf(byte[] classFile) { + Set names = new HashSet<>(); + ClassReader reader = new ClassReader(classFile); + for (int i = 1; i < reader.getItemCount(); i++) { + int offset = reader.getItem(i); + // A CONSTANT_Utf8 entry: tag 1, a big-endian length, then the text (ASCII for class names). + if (offset > 0 && classFile[offset - 1] == 1) { + int length = ((classFile[offset] & 0xFF) << 8) | (classFile[offset + 1] & 0xFF); + String text = new String(classFile, offset + 2, length, java.nio.charset.StandardCharsets.ISO_8859_1); + names.add(text.startsWith("[") ? text.substring(text.lastIndexOf('[') + 1) : text); + addDescriptorNames(text, names); + } + } + return names; + } + + /** Names in {@code Lpkg/Name;} form inside a descriptor or signature, loosely: false names are harmless. */ + private static void addDescriptorNames(String text, Set names) { + int at = text.indexOf('L'); + while (at >= 0) { + int end = text.indexOf(';', at); + if (end < 0) { + return; + } + String candidate = text.substring(at + 1, end); + int generic = candidate.indexOf('<'); + names.add(generic >= 0 ? candidate.substring(0, generic) : candidate); + at = text.indexOf('L', end); + } + } + + /** + * The classes that reach a stand-in's class through the references, and every class in their + * packages: a class loaded here can't use package-private members of one from the parent, + * whose runtime package differs. + */ + private Set closure(Map> references) { + Map> users = new HashMap<>(); + Map> packages = new HashMap<>(); + ArrayDeque pending = new ArrayDeque<>(); + Set result = new HashSet<>(); + for (Map.Entry> entry : references.entrySet()) { + String name = entry.getKey(); + packages.computeIfAbsent(packageOf(name), p -> new HashSet<>()).add(name); + for (String reference : entry.getValue()) { + users.computeIfAbsent(reference, n -> new HashSet<>()).add(name); + if (substituteFor(reference) != null && result.add(name)) { + pending.add(name); + } + } + } + Set expandedPackages = new HashSet<>(); + while (!pending.isEmpty()) { + String name = pending.removeFirst(); + for (String user : users.getOrDefault(name, Set.of())) { + if (result.add(user)) { + pending.add(user); + } + } + if (expandedPackages.add(packageOf(name))) { + for (String mate : packages.getOrDefault(packageOf(name), Set.of())) { + if (result.add(mate)) { + pending.add(mate); + } + } + } + } + return result; + } + + private static String packageOf(String internalName) { + int slash = internalName.lastIndexOf('/'); + return slash < 0 ? "" : internalName.substring(0, slash); + } +} diff --git a/incari-client/files/app-web/src/test/ts/cache-policy.test.ts b/incari-client/files/app-web/src/test/ts/cache-policy.test.ts new file mode 100644 index 0000000..2d7980d --- /dev/null +++ b/incari-client/files/app-web/src/test/ts/cache-policy.test.ts @@ -0,0 +1,47 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; + +import { staleBuildEntries, strategyFor } from "../../main/ts/cache-policy.ts"; + +const scope = new URL("https://example.test/incari/"); +const at = (path: string) => new URL(path, scope); + +describe("strategyFor", () => { + it("keeps versioned build files until their version changes", () => { + assert.equal(strategyFor(at("incari.wasm?v=0123456789abcdef"), scope), "build"); + assert.equal(strategyFor(at("incari.pack?v=0123456789abcdef"), scope), "build"); + }); + + it("keeps game assets named by their content hash", () => { + assert.equal(strategyFor(at("assets/objects/ab/ab" + "0".repeat(38)), scope), "immutable"); + assert.equal(strategyFor(at("assets/objects/ab/not-a-hash"), scope), "pass"); + }); + + it("serves the page from the network, with a copy for offline starts", () => { + for (const path of ["", "index.html", "boot.js", "build.json", "asset-index.json"]) { + assert.equal(strategyFor(at(path), scope), "page", path); + } + }); + + it("leaves the client jar to the storage worker, and anything else alone", () => { + assert.equal(strategyFor(at("client.jar"), scope), "pass"); + assert.equal(strategyFor(at("shaders.json"), scope), "pass"); + assert.equal(strategyFor(new URL("https://elsewhere.test/incari/boot.js"), scope), "pass"); + assert.equal(strategyFor(new URL("https://example.test/other/boot.js"), scope), "pass"); + assert.equal(strategyFor(at("build.json"), scope, "POST"), "pass"); + }); + + it("leaves the Rust build to its own worker, versioned files and page included", () => { + assert.equal(strategyFor(at("rust/pkg/horizon-client_bg.wasm?v=0123456789abcdef"), scope), "pass"); + assert.equal(strategyFor(at("rust/index.html"), scope), "pass"); + }); +}); + +describe("staleBuildEntries", () => { + it("drops every cached build file the running build doesn't load", () => { + const cached = [at("incari.wasm?v=old").href, at("incari.wasm?v=new").href, at("incari.pack?v=new").href]; + assert.deepEqual(staleBuildEntries(cached, ["incari.wasm?v=new", "incari.pack?v=new"], scope), [ + at("incari.wasm?v=old").href, + ]); + }); +}); diff --git a/incari-client/files/app-web/src/test/ts/features.test.ts b/incari-client/files/app-web/src/test/ts/features.test.ts new file mode 100644 index 0000000..ad80a58 --- /dev/null +++ b/incari-client/files/app-web/src/test/ts/features.test.ts @@ -0,0 +1,71 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; + +import { detectFeatures, type FeatureScope } from "../../main/ts/features.ts"; + +/** JSPI's two members, which TypeScript's WebAssembly types don't have yet. */ +function jspiOf(api: object): { Suspending: unknown; promising: unknown } { + const jspi = api as { Suspending: unknown; promising: unknown }; + return { Suspending: jspi.Suspending, promising: jspi.promising }; +} + +describe("detectFeatures", () => { + it("finds WebAssembly GC in an engine that has it", async () => { + // Node 24+ ships the GC proposal, so the real probe must validate here. + assert.equal((await detectFeatures({ WebAssembly })).wasmGc, true); + }); + + it("finds JSPI in an engine that has it, and none without WebAssembly GC", async () => { + // Node 26 ships JSPI, as Chrome 137+ does. + assert.equal((await detectFeatures({ WebAssembly })).jspi, true); + assert.equal((await detectFeatures({ WebAssembly: { validate: () => true } })).jspi, false); + assert.equal( + ( + await detectFeatures({ + WebAssembly: { ...jspiOf(WebAssembly), validate: () => false } as unknown as typeof WebAssembly, + }) + ).jspi, + false, + ); + }); + + it("reports no WebAssembly GC when the engine rejects the probe", async () => { + const withoutGc: FeatureScope = { WebAssembly: { validate: () => false } }; + assert.equal((await detectFeatures(withoutGc)).wasmGc, false); + }); + + it("treats an engine that throws on the probe as unsupported", async () => { + const throwing: FeatureScope = { + WebAssembly: { + validate: () => { + throw new TypeError("unknown type form"); + }, + }, + }; + assert.equal((await detectFeatures(throwing)).wasmGc, false); + }); + + it("needs both isolation and SharedArrayBuffer for shared memory", async () => { + assert.equal((await detectFeatures({ crossOriginIsolated: true, SharedArrayBuffer })).crossOriginIsolated, true); + assert.equal((await detectFeatures({ crossOriginIsolated: false, SharedArrayBuffer })).crossOriginIsolated, false); + assert.equal((await detectFeatures({ crossOriginIsolated: true })).crossOriginIsolated, false); + }); + + it("reports no WebGL2 without a document, or when no context can be made", async () => { + assert.equal((await detectFeatures({})).webgl2, false); + const noContext = { + createElement: () => ({ getContext: () => null }), + } as unknown as Pick; + assert.equal((await detectFeatures({ document: noContext })).webgl2, false); + }); + + it("finds WebGPU only when it gives an adapter", async () => { + assert.equal((await detectFeatures({})).webgpu, false); + const gpu = (adapter: unknown) => ({ navigator: { gpu: { requestAdapter: () => Promise.resolve(adapter) } } }); + assert.equal((await detectFeatures(gpu({}))).webgpu, true); + // A browser with the API and no GPU it will use. + assert.equal((await detectFeatures(gpu(null))).webgpu, false); + const failing = { navigator: { gpu: { requestAdapter: () => Promise.reject(new Error("no GPU process")) } } }; + assert.equal((await detectFeatures(failing)).webgpu, false); + }); +}); diff --git a/incari-client/files/app-web/src/test/ts/game-worker.test.ts b/incari-client/files/app-web/src/test/ts/game-worker.test.ts new file mode 100644 index 0000000..5372818 --- /dev/null +++ b/incari-client/files/app-web/src/test/ts/game-worker.test.ts @@ -0,0 +1,110 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; + +import { createInbox, serve, startChild, type WorkerFactory, type WorkerScope } from "../../main/ts/game-worker.ts"; + +function envelope(kind: number): { kind: number; data: ArrayBuffer } { + return { kind, data: new ArrayBuffer(kind) }; +} + +describe("game-worker inbox", () => { + it("hands queued messages out in order, then waits for the next", async () => { + const inbox = createInbox(); + inbox.push(envelope(1)); + inbox.push(envelope(2)); + + assert.equal(inbox.take()?.kind, 1); + assert.equal((await inbox.next())?.kind, 2); + assert.equal(inbox.take(), null); + + const waiting = inbox.next(); + inbox.push(envelope(3)); + assert.equal((await waiting)?.kind, 3); + }); + + it("ends with null, and nothing comes after", async () => { + const inbox = createInbox(); + inbox.push(envelope(1)); + inbox.push(null); + inbox.push(envelope(2)); + + assert.equal((await inbox.next())?.kind, 1); + assert.equal(await inbox.next(), null); + }); +}); + +describe("game-worker serve", () => { + it("queues the page's messages for the program", async () => { + const posted: unknown[] = []; + const scope: WorkerScope = { + postMessage: (message) => posted.push(message), + onmessage: null, + close: () => undefined, + console, + }; + serve(scope); + + scope.onmessage?.({ data: envelope(7) }); + const parent = scope.__incariParent; + assert.ok(parent !== undefined); + + assert.equal((await parent.next())?.kind, 7); + assert.deepEqual(posted, []); + + scope.onmessage?.({ data: { kind: -1, data: new ArrayBuffer(0) } }); + assert.equal(await parent.next(), null); + }); +}); + +describe("game-worker endings", () => { + it("closes a terrain helper when its server ends the channel", () => { + let closed = false; + const scope: WorkerScope = { + postMessage: () => undefined, + onmessage: null, + close: () => { + closed = true; + }, + console, + }; + serve(scope); + scope.onmessage?.({ + data: { start: { runtime: "data:text/javascript,", module: "m.wasm", jspi: false, role: "terrain" } }, + }); + scope.onmessage?.({ data: { kind: -1, data: new ArrayBuffer(0) } }); + assert.equal(closed, true); + }); +}); + +describe("game-worker startChild", () => { + it("starts the build in the role, and passes messages both ways until the child ends", async () => { + const posted: unknown[] = []; + let made: { url: string; name: string | undefined } | null = null; + let deliver: ((data: unknown) => void) | null = null; + const factory: WorkerFactory = (url, options) => { + made = { url: url.href, name: options.name }; + return { + postMessage: (message) => posted.push(message), + listen: (onMessage) => { + deliver = onMessage; + }, + terminate: () => undefined, + }; + }; + const build = { runtime: "r.js", module: "m.wasm", jspi: true, role: "server", query: "?x=1" }; + const channel = startChild({ console }, build, "terrain", factory, new URL("https://h/game-worker.js")); + + assert.deepEqual(made, { url: "https://h/game-worker.js", name: "incari-terrain" }); + assert.deepEqual(posted[0], { start: { ...build, role: "terrain" }, storage: null }); + + channel.send(4, new ArrayBuffer(4)); + assert.equal((posted[1] as { kind: number }).kind, 4); + + const toChannel = deliver as ((data: unknown) => void) | null; + assert.ok(toChannel !== null); + toChannel(envelope(5)); + assert.equal((await channel.next())?.kind, 5); + toChannel({ kind: -1, data: new ArrayBuffer(0) }); + assert.equal(await channel.next(), null); + }); +}); diff --git a/incari-client/files/app-web/src/test/ts/jspi.test.ts b/incari-client/files/app-web/src/test/ts/jspi.test.ts new file mode 100644 index 0000000..f4ef5d6 --- /dev/null +++ b/incari-client/files/app-web/src/test/ts/jspi.test.ts @@ -0,0 +1,151 @@ +import assert from "node:assert/strict"; +import { setImmediate } from "node:timers/promises"; +import { describe, it } from "node:test"; + +import { createJspiImports, supportsJspi, type JspiScope } from "../../main/ts/jspi.ts"; + +/** + * A module shaped like a JSPI build's fibers: its `teavm.jspi.run(id)` export waits on promise `id` + * through `teavmJspi.await`, then calls `t.done(id)`. + */ +// prettier-ignore +const FIBER_MODULE = new Uint8Array([ + 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, // "\0asm", version 1 + 0x01, 0x05, 0x01, 0x60, 0x01, 0x7f, 0x00, // types: (func (param i32)) + 0x02, 0x1c, 0x02, // imports, 28 bytes, two: + 0x09, 0x74, 0x65, 0x61, 0x76, 0x6d, 0x4a, 0x73, 0x70, 0x69, // "teavmJspi" + 0x05, 0x61, 0x77, 0x61, 0x69, 0x74, 0x00, 0x00, // "await", func type 0 + 0x01, 0x74, 0x04, 0x64, 0x6f, 0x6e, 0x65, 0x00, 0x00, // "t" "done", func type 0 + 0x03, 0x02, 0x01, 0x00, // functions: one of type 0 + 0x07, 0x12, 0x01, 0x0e, // exports, 18 bytes, one, a 14-byte name: + 0x74, 0x65, 0x61, 0x76, 0x6d, 0x2e, 0x6a, 0x73, 0x70, 0x69, 0x2e, 0x72, 0x75, 0x6e, // "teavm.jspi.run" + 0x00, 0x02, // function 2 + 0x0a, 0x0c, 0x01, 0x0a, 0x00, // code, one body of 10 bytes, no locals: + 0x20, 0x00, 0x10, 0x00, // local.get 0; call await + 0x20, 0x00, 0x10, 0x01, // local.get 0; call done + 0x0b, // end +]); + +/** A scope whose JSPI wrappers record their use, for the bookkeeping alone. */ +function fakeScope(promising: (fn: (id: number) => unknown) => (id: number) => Promise): JspiScope { + return { + WebAssembly: { + Suspending: class { + readonly fn: (id: number) => unknown; + constructor(fn: (id: number) => unknown) { + this.fn = fn; + } + }, + promising, + }, + }; +} + +describe("supportsJspi", () => { + it("finds JSPI in an engine that has it", () => { + // Node 26 ships JSPI, as Chrome 137+ does. + assert.equal(supportsJspi({ WebAssembly }), true); + }); + + it("reports no JSPI without Suspending and promising", () => { + assert.equal(supportsJspi({ WebAssembly: {} }), false); + assert.equal(supportsJspi({}), false); + }); +}); + +describe("createJspiImports", () => { + it("keeps a fiber's stack until its promise resolves (real JSPI)", async () => { + const done: number[] = []; + const jspi = createJspiImports((error) => { + throw error; + }); + const { instance } = await WebAssembly.instantiate(FIBER_MODULE, { + teavmJspi: jspi.module as WebAssembly.ModuleImports, + t: { done: (id: number) => done.push(id) }, + }); + jspi.attach(instance.exports); + const create = jspi.module.create as () => number; + const run = jspi.module.run as (id: number) => void; + const resolve = jspi.module.resolve as (id: number) => void; + + const id = create(); + run(id); + // The fiber waits, and run returned to its caller. + assert.deepEqual(done, []); + assert.equal(jspi.pending(), 1); + + resolve(id); + await setImmediate(); + assert.deepEqual(done, [id]); + assert.equal(jspi.pending(), 0); + }); + + it("ends every waiting fiber when told to, and reports nothing on the way out", async () => { + const done: number[] = []; + const failures: unknown[] = []; + const jspi = createJspiImports((error) => failures.push(error)); + const { instance } = await WebAssembly.instantiate(FIBER_MODULE, { + teavmJspi: jspi.module as WebAssembly.ModuleImports, + t: { done: (id: number) => done.push(id) }, + }); + jspi.attach(instance.exports); + const create = jspi.module.create as () => number; + const run = jspi.module.run as (id: number) => void; + + const first = create(); + const second = create(); + run(first); + run(second); + assert.equal(jspi.pending(), 2); + + jspi.terminate(); + await setImmediate(); + // Both resumed (a real build's fiber then traps); none is left waiting. + assert.deepEqual(done.sort(), [first, second].sort()); + assert.equal(jspi.pending(), 0); + assert.deepEqual(failures, []); + + // A fiber that waits after the end resumes at once. + const late = create(); + run(late); + await setImmediate(); + assert.ok(done.includes(late)); + }); + + it("forgets a promise dropped by a call that completed before waiting", () => { + const jspi = createJspiImports( + () => undefined, + fakeScope(() => () => Promise.resolve()), + ); + const create = jspi.module.create as () => number; + const drop = jspi.module.drop as (id: number) => void; + const first = create(); + const second = create(); + assert.notEqual(first, second); + drop(first); + assert.equal(jspi.pending(), 1); + }); + + it("reports an error that escapes a fiber", async () => { + const failures: unknown[] = []; + const jspi = createJspiImports( + (error) => failures.push(error), + fakeScope(() => () => Promise.reject(new Error("escaped"))), + ); + jspi.attach({ "teavm.jspi.run": () => undefined }); + (jspi.module.run as (id: number) => void)(1); + await setImmediate(); + assert.equal(failures.length, 1); + assert.match(String(failures[0]), /escaped/); + }); + + it("refuses to start a fiber before the exports are attached", () => { + const jspi = createJspiImports( + () => undefined, + fakeScope(() => () => Promise.resolve()), + ); + assert.throws(() => { + (jspi.module.run as (id: number) => void)(1); + }, /before the module's exports/); + }); +}); diff --git a/incari-client/files/app-web/src/test/ts/loader.test.ts b/incari-client/files/app-web/src/test/ts/loader.test.ts new file mode 100644 index 0000000..831c89e --- /dev/null +++ b/incari-client/files/app-web/src/test/ts/loader.test.ts @@ -0,0 +1,212 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; + +import type { BrowserFeatures } from "../../main/ts/features.ts"; +import { + buildFor, + buildName, + buildOptions, + countingResponse, + DEFAULT_MANIFEST, + formatBytes, + initialBuild, + missingWasmGc, + missingWebgl2, + parseManifest, + requestedBuild, + rustPage, + sizeOf, + versioned, + type BuildManifest, +} from "../../main/ts/loader.ts"; + +const everything: BrowserFeatures = { + wasmGc: true, + jspi: true, + crossOriginIsolated: true, + webgl2: true, + webgpu: true, +}; +/** Safari 18.2+ and Chrome 119-136: WebAssembly GC, no JSPI. */ +const noJspi: BrowserFeatures = { ...everything, jspi: false }; + +const manifest: BuildManifest = { + format: 2, + id: "abc", + game: "26.3", + release: true, + fast: { runtime: "incari.wasm-runtime.js", module: "incari-fast.wasm" }, + compatible: { runtime: "incari.wasm-runtime.js", module: "incari.wasm" }, + files: [ + { path: "incari.wasm", size: 1000, sha256: "0123456789abcdef0123456789abcdef" }, + { path: "incari-fast.wasm", size: 2000, sha256: "fedcba9876543210fedcba9876543210" }, + ], +}; + +describe("buildOptions", () => { + it("offers both builds, Fast first, where both can run", () => { + assert.deepEqual(buildOptions(everything, manifest), [ + { kind: "fast", available: true }, + { kind: "compatible", available: true }, + ]); + }); + + it("explains why Fast can't run in a browser without JSPI", () => { + assert.deepEqual(buildOptions(noJspi, manifest), [ + { + kind: "fast", + available: false, + reason: "Fast needs Chrome or Edge 137, Firefox 153 or newer.", + }, + { kind: "compatible", available: true }, + ]); + }); + + it("offers Rust last, only when the copy has it, and says when WebGPU is missing", () => { + const withRust: BuildManifest = { ...manifest, rust: { page: "rust/index.html" } }; + assert.deepEqual(buildOptions(everything, withRust)[2], { kind: "rust", available: true }); + const noWebgpu = buildOptions({ ...everything, webgpu: false }, withRust).find((o) => o.kind === "rust"); + assert.equal(noWebgpu?.available, false); + assert.match(noWebgpu.reason ?? "", /WebGPU/); + }); + + it("marks a build this copy doesn't include", () => { + const fastOnly = { ...manifest, compatible: undefined } as unknown as BuildManifest; + assert.deepEqual(buildOptions(everything, fastOnly), [ + { kind: "fast", available: true }, + { kind: "compatible", available: false, reason: "This copy of the game doesn't include Compatible." }, + ]); + }); +}); + +describe("requestedBuild", () => { + it("reads ?build=fast and ?build=compatible, and nothing else", () => { + assert.equal(requestedBuild("fast"), "fast"); + assert.equal(requestedBuild("compatible"), "compatible"); + assert.equal(requestedBuild("rust"), "rust"); + assert.equal(requestedBuild("wasm"), null); + assert.equal(requestedBuild(null), null); + }); +}); + +describe("initialBuild", () => { + const both = buildOptions(everything, manifest); + + it("starts on Fast, the recommended build", () => { + assert.equal(initialBuild(both, null), "fast"); + }); + + it("never starts on Rust unless it was the last pick or nothing else runs", () => { + const withRust = buildOptions(everything, { ...manifest, rust: { page: "rust/index.html" } }); + assert.equal(initialBuild(withRust, null), "fast"); + assert.equal(initialBuild(withRust, "rust"), "rust"); + const rustOnly = withRust.map((option) => (option.kind === "rust" ? option : { ...option, available: false })); + assert.equal(initialBuild(rustOnly, null), "rust"); + }); + + it("starts on the player's last pick while it can still run", () => { + assert.equal(initialBuild(both, "compatible"), "compatible"); + assert.equal(initialBuild(buildOptions(noJspi, manifest), "fast"), "compatible"); + }); +}); + +describe("buildFor", () => { + it("gives the manifest's entry for a build that can run", () => { + assert.deepEqual(buildFor("fast", buildOptions(everything, manifest), manifest), { + kind: "fast", + target: manifest.fast, + }); + }); + + it("gives the Rust build's page", () => { + const withRust: BuildManifest = { ...manifest, rust: { page: "rust/index.html" } }; + assert.deepEqual(buildFor("rust", buildOptions(everything, withRust), withRust), { + kind: "rust", + target: { page: "rust/index.html" }, + }); + }); + + it("refuses a build that can't run here, with the reason", () => { + const choice = buildFor("fast", buildOptions(noJspi, manifest), manifest); + assert.ok(choice.kind === "unsupported"); + assert.match(choice.reason, /Fast needs/); + }); +}); + +describe("buildName", () => { + it("names the builds as the player sees them", () => { + assert.equal(buildName("fast"), "Fast"); + assert.equal(buildName("compatible"), "Compatible"); + assert.equal(buildName("rust"), "Rust"); + }); +}); + +describe("rustPage", () => { + it("opens Rust's page beside this one, keeping the address options but ?build", () => { + assert.equal( + rustPage({ page: "rust/index.html" }, "https://example.test/incari/?build=rust&args=--world%20T"), + "https://example.test/incari/rust/index.html?args=--world+T", + ); + assert.equal( + rustPage({ page: "rust/index.html" }, "https://example.test/"), + "https://example.test/rust/index.html", + ); + }); +}); + +describe("missingWebgl2 and missingWasmGc", () => { + it("need WebGL 2 and WebAssembly GC for either build", () => { + assert.equal(missingWebgl2(everything), null); + assert.match(missingWebgl2({ ...everything, webgl2: false }) ?? "", /WebGL 2/); + assert.equal(missingWasmGc(everything), null); + assert.match(missingWasmGc({ ...everything, wasmGc: false }) ?? "", /too old to run the game/); + }); +}); + +describe("parseManifest", () => { + it("accepts a manifest the build tool writes", () => { + assert.deepEqual(parseManifest(JSON.parse(JSON.stringify(manifest))), manifest); + }); + + it("refuses another format, a missing file list, and a manifest with nothing to run", () => { + assert.throws(() => parseManifest({ ...manifest, format: 1 }), /format 1/); + assert.throws(() => parseManifest({ format: 2, id: "x" }), /file list/); + assert.throws(() => parseManifest({ format: 2, id: "x", files: [] }), /no build/); + assert.throws(() => parseManifest(null), /isn't an object/); + }); +}); + +describe("versioned", () => { + it("adds the file's hash as its version", () => { + assert.equal(versioned(manifest, "incari.wasm"), "incari.wasm?v=0123456789abcdef"); + }); + + it("leaves a file the manifest doesn't list as it is", () => { + assert.equal(versioned(DEFAULT_MANIFEST, "incari.wasm"), "incari.wasm"); + assert.equal(sizeOf(DEFAULT_MANIFEST, "incari.wasm"), 0); + assert.equal(sizeOf(manifest, "incari-fast.wasm"), 2000); + }); +}); + +describe("countingResponse", () => { + it("reports the bytes read so far and keeps the body and headers", async () => { + const original = new Response(new Blob([new Uint8Array(10), new Uint8Array(5)]), { + headers: { "Content-Type": "application/wasm" }, + }); + const seen: number[] = []; + const counted = countingResponse(original, (received) => seen.push(received)); + assert.equal(counted.headers.get("Content-Type"), "application/wasm"); + const body = new Uint8Array(await counted.arrayBuffer()); + assert.equal(body.byteLength, 15); + assert.equal(seen.at(-1), 15); + }); +}); + +describe("formatBytes", () => { + it("prints sizes as people read them", () => { + assert.equal(formatBytes(512), "512 B"); + assert.equal(formatBytes(1_500), "1.5 kB"); + assert.equal(formatBytes(29_390_000), "29 MB"); + assert.equal(formatBytes(156_500_000), "157 MB"); + }); +}); diff --git a/incari-client/files/app-web/src/test/ts/offline.test.ts b/incari-client/files/app-web/src/test/ts/offline.test.ts new file mode 100644 index 0000000..f03e03f --- /dev/null +++ b/incari-client/files/app-web/src/test/ts/offline.test.ts @@ -0,0 +1,325 @@ +import assert from "node:assert/strict"; +import { resolveObjectURL } from "node:buffer"; +import { afterEach, beforeEach, describe, it } from "node:test"; + +import { + installFiles, + quietBeacons, + shimSource, + startWorker, + type FileScope, + type FileSetup, + type StartScope, +} from "../../main/ts/offline.ts"; + +const BASE = "file:///home/player/"; + +/** The shim replaces URL's Blob URL functions in its realm; each test gets the originals back. */ +const createObjectURL = URL.createObjectURL.bind(URL); +const revokeObjectURL = URL.revokeObjectURL.bind(URL); + +afterEach(() => { + URL.createObjectURL = createObjectURL; + URL.revokeObjectURL = revokeObjectURL; +}); + +async function textAt(url: string): Promise { + const blob = resolveObjectURL(url); + assert.ok(blob !== undefined, `${url} is a Blob URL`); + return blob.text(); +} + +function script(source: string): Blob { + return new Blob([source], { type: "text/javascript" }); +} + +function setup(blobs: Record, paths: string[] = Object.keys(blobs)): FileSetup { + return { base: BASE, paths, blobs, shim: "/* shim */" }; +} + +/** A realm whose fetch records what reached the network. */ +function scope(): FileScope & { fetched: string[] } { + const fetched: string[] = []; + return { + fetched, + fetch: (input) => { + fetched.push(input instanceof Request ? input.url : String(input)); + return Promise.resolve(new Response("from the network")); + }, + }; +} + +describe("offline files: fetch", () => { + it("serves embedded files by relative, absolute and versioned URLs", async () => { + const realm = scope(); + installFiles(realm, setup({ "build.json": new Blob(["{}"], { type: "application/json" }) })); + + for (const url of ["build.json", `${BASE}build.json`, "build.json?v=0123456789abcdef", "./build.json#x"]) { + const response = await realm.fetch(url); + assert.equal(response.status, 200); + assert.equal(response.headers.get("content-type"), "application/json"); + assert.equal(await response.text(), "{}"); + } + assert.deepEqual(realm.fetched, []); + }); + + it("leaves every other URL to the real fetch", async () => { + const realm = scope(); + installFiles(realm, setup({ "build.json": new Blob(["{}"]) })); + + await realm.fetch("assets/objects/ab/abcdef"); + await realm.fetch("https://example.com/build.json"); + await realm.fetch("data:text/plain,hi"); + + assert.deepEqual(realm.fetched, [ + "assets/objects/ab/abcdef", + "https://example.com/build.json", + "data:text/plain,hi", + ]); + }); + + it("decodes a file once, when it's first fetched", async () => { + const realm = scope(); + const decoded: string[] = []; + installFiles(realm, setup({}, ["client.jar", "missing.bin"]), (path) => { + decoded.push(path); + return Promise.resolve(path === "client.jar" ? new Blob(["jar"]) : null); + }); + + const [first, second] = await Promise.all([realm.fetch("client.jar"), realm.fetch("client.jar?v=1")]); + assert.equal(await first.text(), "jar"); + assert.equal(await second.text(), "jar"); + assert.equal((await realm.fetch("missing.bin")).status, 404); + assert.deepEqual(decoded, ["client.jar", "missing.bin"]); + }); +}); + +describe("offline files: scripts", () => { + it("points a module's relative imports at Blob URLs of the imported files", async () => { + const realm = scope(); + const files = installFiles( + realm, + setup({ + "boot.js": script('import { a } from "./loader.js";\nimport "./jspi.js";\nconst b = import("./other.js");'), + "loader.js": script('import { c } from "./jspi.js";\nexport const a = c;'), + "jspi.js": script("export const c = 1;"), + }), + ); + + const boot = await textAt(await files.moduleUrl("boot.js")); + const imported = [...boot.matchAll(/"(blob:[^"]+)"/g)].map((match) => match[1] ?? ""); + assert.equal(imported.length, 2); + assert.match(await textAt(imported[0] ?? ""), /^import \{ c \} from "blob:/); + assert.equal(await textAt(imported[1] ?? ""), "export const c = 1;"); + // Not an embedded file: left as it was. + assert.match(boot, /import\("\.\/other\.js"\)/); + // One Blob URL per module, however many import it. + assert.equal(await files.moduleUrl("jspi.js"), imported[1]); + }); + + it("gives an embedded script's Blob URL for loading, and any other URL back", () => { + const realm = scope(); + const files = installFiles(realm, setup({ "incari.wasm-runtime.js": script("var TeaVM = {};") })); + + assert.match(files.url(`${BASE}incari.wasm-runtime.js?v=1`), /^blob:/); + assert.equal(files.url("https://example.com/x.js"), "https://example.com/x.js"); + assert.equal(realm.incariFiles, files); + }); + + it("loads embedded scripts through importScripts from Blob URLs", () => { + const loaded: string[] = []; + const realm: FileScope = { + ...scope(), + importScripts: (...urls) => { + loaded.push(...urls); + }, + }; + installFiles(realm, setup({ "mesher.wasm-runtime.js": script("") })); + + realm.importScripts?.(`${BASE}mesher.wasm-runtime.js?v=2`, "https://example.com/other.js"); + + assert.equal(loaded.length, 2); + assert.match(loaded[0] ?? "", /^blob:/); + assert.equal(loaded[1], "https://example.com/other.js"); + }); +}); + +/** The shim's `Worker`, which a realm with workers always gets. */ +function workerClass(realm: FileScope): NonNullable { + const Worker = realm.Worker; + assert.ok(Worker !== undefined); + return Worker; +} + +/** A worker as the shim starts it: what it was made with and the messages posted to it. */ +interface MadeWorker { + url: string; + options: WorkerOptions | undefined; + posted: { message: unknown; transfer: Transferable[] | undefined }[]; +} + +describe("offline files: workers", () => { + let made: MadeWorker[]; + let realm: FileScope & { fetched: string[] }; + + afterEach(() => { + // Open ports keep Node running. + for (const worker of made) { + (worker.posted[0]?.message as { incariFiles?: FileSetup } | undefined)?.incariFiles?.port?.close(); + } + }); + + beforeEach(() => { + made = []; + realm = scope(); + realm.Worker = function (url: string | URL, options?: WorkerOptions) { + const worker: MadeWorker = { url: String(url), options, posted: [] }; + made.push(worker); + return { + postMessage: (message: unknown, transfer?: Transferable[]) => worker.posted.push({ message, transfer }), + } as unknown as Worker; + } as unknown as NonNullable; + }); + + function setupPosted(worker: MadeWorker | undefined): FileSetup { + const message = worker?.posted[0]?.message as { incariFiles?: FileSetup } | undefined; + assert.ok(message?.incariFiles !== undefined, "the shim's files are the first message"); + return message.incariFiles; + } + + it("starts an embedded module worker as a classic one that runs the shim, then the module", () => { + installFiles(realm, setup({ "game-worker.js": script("export {};"), "client.jar": new Blob(["jar"]) })); + new (workerClass(realm))(new URL("game-worker.js", BASE), { type: "module", name: "incari-server" }); + + const worker = made[0]; + assert.match(worker?.url ?? "", /^blob:/); + assert.deepEqual(worker?.options, { name: "incari-server" }); + const files = setupPosted(worker); + assert.deepEqual(files.script === undefined ? null : { path: files.script.path, module: files.script.module }, { + path: "game-worker.js", + module: true, + }); + assert.deepEqual(Object.keys(files.blobs).sort(), ["client.jar", "game-worker.js"]); + assert.equal(files.base, BASE); + }); + + it("starts a worker from a script Blob this realm made with the shim, as a classic worker", async () => { + installFiles(realm, setup({})); + const source = script("onmessage = () => {};"); + const url = URL.createObjectURL(source); + + new (workerClass(realm))(url, { name: "incari-storage" }); + + const files = setupPosted(made[0]); + assert.equal(files.script?.path, null); + assert.equal(files.script.module, false); + assert.equal(await files.script.blob.text(), "onmessage = () => {};"); + }); + + it("leaves any other worker alone", () => { + installFiles(realm, setup({})); + + new (workerClass(realm))("https://example.com/worker.js", { type: "module" }); + + assert.deepEqual(made[0], { url: "https://example.com/worker.js", options: { type: "module" }, posted: [] }); + }); + + it("answers a worker's request for a file it doesn't have yet", async () => { + installFiles(realm, setup({}, ["incari-fast.wasm", "program.js"]), (path) => + Promise.resolve(path === "incari-fast.wasm" ? new Blob(["module"]) : script("")), + ); + await realm.fetch("program.js"); + + new (workerClass(realm))("program.js"); + const port = setupPosted(made[0]).port; + assert.ok(port !== undefined); + const reply = new Promise<{ id: number; blob: Blob | null }>((resolve) => { + port.onmessage = (event: MessageEvent<{ id: number; blob: Blob | null }>) => { + resolve(event.data); + }; + }); + port.postMessage({ id: 7, path: "incari-fast.wasm" }); + + const answer = await reply; + assert.equal(answer.id, 7); + assert.equal(await answer.blob?.text(), "module"); + }); +}); + +/** A worker's global scope, enough for startWorker. */ +class FakeWorkerScope extends EventTarget { + readonly imported: string[] = []; + readonly heard: unknown[] = []; + fetch: FileScope["fetch"] = () => Promise.resolve(new Response(null)); + importScripts = (...urls: string[]): void => { + this.imported.push(...urls); + // The real script listens once it runs. + this.addEventListener("message", (event) => { + this.heard.push((event as MessageEvent).data); + }); + }; + setTimeout = (handler: () => void, timeout: number): unknown => setTimeout(handler, timeout); +} + +function init(files: Partial): MessageEvent { + return new MessageEvent("message", { + data: { incariFiles: { base: BASE, paths: [], blobs: {}, shim: "", ...files } }, + }); +} + +describe("offline files: a worker's start", () => { + it("runs the real script, which then hears the page's messages", async () => { + const worker = new FakeWorkerScope(); + startWorker(worker as unknown as StartScope, installFiles); + + worker.dispatchEvent(init({ script: { path: null, blob: script(""), module: false } })); + // A message is a task of its own: the start's promise has settled before the next one comes. + // (A module's import takes longer; messages before it are held, which the browser checks see.) + await new Promise((resolve) => setTimeout(resolve, 0)); + worker.dispatchEvent(new MessageEvent("message", { data: "first" })); + worker.dispatchEvent(new MessageEvent("message", { data: "second" })); + + assert.equal(worker.imported.length, 1); + assert.match(worker.imported[0] ?? "", /^blob:/); + assert.deepEqual(worker.heard, ["first", "second"]); + }); + + it("works from its own source alone, as a worker gets it", async () => { + const worker = new FakeWorkerScope(); + // eslint-disable-next-line @typescript-eslint/no-implied-eval -- the worker's shim is source text by design + (new Function("self", shimSource()) as (self: unknown) => void)(worker); + + worker.dispatchEvent( + init({ + paths: ["runtime.js"], + blobs: { "runtime.js": script("") }, + script: { path: null, blob: script(""), module: false }, + }), + ); + await new Promise((resolve) => setTimeout(resolve, 0)); + + assert.equal(worker.imported.length, 1); + assert.equal(typeof (worker as unknown as FileScope).incariFiles?.url, "function"); + const response = await worker.fetch("runtime.js"); + assert.equal(response.headers.get("content-type"), "text/javascript"); + }); +}); + +describe("quietBeacons", () => { + it("answers false where the browser throws, and passes the rest through", () => { + const sent: string[] = []; + const navigator = { + sendBeacon(url: string | URL): boolean { + if (String(url).startsWith("file:")) { + throw new TypeError("Beacons are only supported over HTTP(S)."); + } + sent.push(String(url)); + return true; + }, + }; + quietBeacons(navigator); + assert.equal(navigator.sendBeacon("file:///home/player/log"), false); + assert.equal(navigator.sendBeacon("https://example.com/log"), true); + assert.deepEqual(sent, ["https://example.com/log"]); + }); +}); diff --git a/incari-client/files/app-web/src/test/ts/wakeups.test.ts b/incari-client/files/app-web/src/test/ts/wakeups.test.ts new file mode 100644 index 0000000..0dec313 --- /dev/null +++ b/incari-client/files/app-web/src/test/ts/wakeups.test.ts @@ -0,0 +1,217 @@ +import assert from "node:assert/strict"; +import { setTimeout as sleep } from "node:timers/promises"; +import { afterEach, describe, it } from "node:test"; + +import { + createAsyncImports, + createPageAsyncImports, + createPageTimer, + RUN_DUE_LIMIT, + type PageTimer, + type TimerWorker, + type WakeupScope, +} from "../../main/ts/wakeups.ts"; + +/** Channels the tests made: an open port keeps Node running, so each test closes them. */ +const channels: MessageChannel[] = []; + +class ClosableChannel extends MessageChannel { + constructor() { + super(); + channels.push(this); + } +} + +/** Node's own channel and timers, with a clock the test sets. */ +function scope(now: () => number): WakeupScope & { timers: number } { + const result = { + MessageChannel: ClosableChannel, + timers: 0, + setTimeout(handler: () => void, delay: number): number { + result.timers++; + return setTimeout(handler, delay) as unknown as number; + }, + clearTimeout(id: number): void { + clearTimeout(id); + }, + now, + }; + return result; +} + +/** Waits until the channel's messages have been handled. */ +async function drain(): Promise { + await sleep(20); +} + +describe("wakeups", () => { + afterEach(() => { + for (const channel of channels.splice(0)) { + channel.port1.close(); + channel.port2.close(); + } + }); + + it("runs events due now in the order offered, without timers", async () => { + const s = scope(() => 1000); + const imports = createAsyncImports(s); + const ran: string[] = []; + for (const name of ["a", "b", "c"]) { + imports.offer(name, (instance) => ran.push(instance as string), 1000); + } + assert.deepEqual(ran, []); + await drain(); + assert.deepEqual(ran, ["a", "b", "c"]); + assert.equal(s.timers, 0); + }); + + it("runs an event due later on a timer", async () => { + const s = scope(() => 1000); + const imports = createAsyncImports(s); + const ran: string[] = []; + const id = imports.offer("later", (instance) => ran.push(instance as string), 1005); + assert.ok(id > 0); + assert.equal(s.timers, 1); + await sleep(30); + assert.deepEqual(ran, ["later"]); + }); + + it("cancels either kind", async () => { + const s = scope(() => 1000); + const imports = createAsyncImports(s); + const ran: string[] = []; + const now = imports.offer("now", (instance) => ran.push(instance as string), 900); + const kept = imports.offer("kept", (instance) => ran.push(instance as string), 1000); + const later = imports.offer("later", (instance) => ran.push(instance as string), 1010); + assert.ok(now < 0 && kept < 0); + imports.kill(now); + imports.kill(later); + await sleep(40); + assert.deepEqual(ran, ["kept"]); + // The cancelled event's message ran nothing extra. + imports.offer("after", (instance) => ran.push(instance as string), 1000); + await drain(); + assert.deepEqual(ran, ["kept", "after"]); + }); + + it("keeps up with a chain of events each offering the next", async () => { + const imports = createAsyncImports(scope(() => 0)); + let count = 0; + const started = performance.now(); + await new Promise((resolve) => { + const step = (): void => { + if (++count === 500) { + resolve(); + } else { + imports.offer(null, step, 0); + } + }; + imports.offer(null, step, 0); + }); + // Timers clamped to 1 ms or more would take half a second at least. + const elapsed = performance.now() - started; + assert.ok(elapsed < 400, `${elapsed.toFixed(0)} ms`); + }); + + it("leaves a visible page on plain timers, and times a hidden one in the worker", async () => { + const s = scope(() => 1000); + let hidden = false; + const set: number[] = []; + const cleared: number[] = []; + const timer: PageTimer = { + set(handler, delay) { + set.push(delay); + setTimeout(handler, 1); + return set.length; + }, + clear(id) { + cleared.push(id); + }, + }; + const imports = createPageAsyncImports({ ...s, hidden: () => hidden, timer }); + const ran: string[] = []; + const visible = imports.offer("visible", (instance) => ran.push(instance as string), 1000); + assert.ok(visible > 0 && visible < 2 ** 30); + assert.equal(s.timers, 1); + hidden = true; + const now = imports.offer("now", (instance) => ran.push(instance as string), 900); + const later = imports.offer("later", (instance) => ran.push(instance as string), 1500); + assert.ok(now >= 2 ** 30 && later >= 2 ** 30); + assert.deepEqual(set, [0, 500]); + assert.equal(s.timers, 1); + imports.kill(later); + assert.deepEqual(cleared, [2]); + await sleep(30); + assert.deepEqual([...ran].sort(), ["later", "now", "visible"]); + }); + + it("runs the events a wake offers at once, each only once, and leaves the rest to their timers", async () => { + const s = scope(() => 1000); + const imports = createPageAsyncImports({ ...s, hidden: () => false, timer: null }); + const ran: string[] = []; + const offer = (name: string, time: number): number => + imports.offer(name, (instance) => ran.push(instance as string), time); + offer("older", 1000); + imports.runWoken(() => { + offer("woken", 1000); + const killed = offer("killed", 990); + offer("later", 1010); + imports.kill(killed); + imports.offer( + "chained", + (instance) => { + ran.push(instance as string); + offer("chain's own", 1000); + }, + 1000, + ); + }); + assert.deepEqual(ran, ["woken", "chained", "chain's own"]); + await sleep(40); + // The older event and the later one come on their own timers; the woken ones' find nothing. + assert.deepEqual(ran, ["woken", "chained", "chain's own", "older", "later"]); + }); + + it("stops after its limit when the woken events keep offering more", async () => { + const s = scope(() => 0); + const imports = createPageAsyncImports({ ...s, hidden: () => false, timer: null }); + const count = { runs: 0 }; + let stopped = false; + const again = (): void => { + count.runs++; + if (!stopped) { + imports.offer(null, again, 0); + } + }; + imports.runWoken(() => { + imports.offer(null, again, 0); + }); + assert.equal(count.runs, RUN_DUE_LIMIT); + // The rest are still on their timers. + const runsSoFar = (): number => count.runs; + const stop = runsSoFar(); + await sleep(5); + stopped = true; + assert.ok(runsSoFar() > stop); + await sleep(5); + }); + + it("times a page timer in its worker and cancels it there", () => { + const posted: unknown[] = []; + const worker: TimerWorker = { + postMessage(message) { + posted.push(message); + }, + onmessage: null, + }; + const timer = createPageTimer(worker); + const ran: number[] = []; + const first = timer.set(() => ran.push(1), 250); + const second = timer.set(() => ran.push(2), -5); + timer.clear(second); + assert.deepEqual(posted, [{ id: first, delay: 250 }, { id: second, delay: 0 }, { id: second }]); + worker.onmessage?.({ data: second }); + worker.onmessage?.({ data: first }); + assert.deepEqual(ran, [1]); + }); +}); diff --git a/incari-client/files/build.gradle.kts b/incari-client/files/build.gradle.kts new file mode 100644 index 0000000..e613bfe --- /dev/null +++ b/incari-client/files/build.gradle.kts @@ -0,0 +1,128 @@ +import com.diffplug.gradle.spotless.SpotlessExtension +import net.ltgt.gradle.errorprone.CheckSeverity +import net.ltgt.gradle.errorprone.errorprone + +// Shared conventions for every Incari JVM module. Module-specific settings live in each +// module's own build.gradle.kts. Warnings fail the build everywhere Incari code is compiled. + +plugins { + alias(libs.plugins.spotless) apply false + alias(libs.plugins.errorprone) apply false +} + +/** + * Modules whose sources are all Incari code. `:client` is the exception: it compiles the + * vendor tree together with Incari's adapters, so it configures its own compiler flags. + */ +val mixedVendorModules = setOf(":client") + +subprojects { + plugins.withType { + apply(plugin = "com.diffplug.spotless") + apply(plugin = "net.ltgt.errorprone") + + extensions.configure { + // Minecraft 26.x targets Java 25, and TeaVM 0.16 reads class files of at least Java 25. + toolchain.languageVersion = JavaLanguageVersion.of(25) + } + + dependencies { + "errorprone"(rootProject.libs.errorprone.core) + "errorprone"(rootProject.libs.nullaway) + "compileOnly"(rootProject.libs.jspecify) + "testCompileOnly"(rootProject.libs.jspecify) + } + + tasks.withType().configureEach { + options.release = 25 + options.encoding = "UTF-8" + if (project.path !in mixedVendorModules) { + // -classfile: third-party jars (Guava in Mojang's set) reference annotation classes + // they don't ship; javac's complaint about that isn't about Incari code. + options.compilerArgs.addAll(listOf("-Xlint:all,-classfile", "-Werror")) + } + options.errorprone { + // Null-safety is part of every Incari signature: unannotated means non-null, + // and @Nullable (JSpecify) marks the exceptions. + check("NullAway", if (name.contains("Test")) CheckSeverity.OFF else CheckSeverity.ERROR) + option("NullAway:AnnotatedPackages", "incari") + option("NullAway:JSpecifyMode", "true") + } + } + + tasks.withType().configureEach { + useJUnitPlatform() + } + + configure { + java { + // Incari sources only. The vendor tree lives in work/ and is never reformatted. + target("src/*/java/**/*.java") + palantirJavaFormat(rootProject.libs.versions.palantir.java.format.get()) + removeUnusedImports() + trimTrailingWhitespace() + endWithNewline() + } + } + } +} + +// --------------------------------------------------------------------------------------------- +// Module boundaries: gradle/module-boundaries.txt is the single list of allowed dependencies. +// --------------------------------------------------------------------------------------------- + +val boundariesFile = layout.projectDirectory.file("gradle/module-boundaries.txt") + +evaluationDependsOnChildren() + +val declaredProjectDependencies: Provider>> = provider { + subprojects.filter { it.buildFile.exists() }.associate { p -> + p.path to p.configurations.flatMap { configuration -> + configuration.dependencies.withType().map { it.path } + }.filter { it != p.path }.toSet() + } +} + +val checkModuleBoundaries = tasks.register("checkModuleBoundaries") { + group = "verification" + description = "Fails if a module depends on one gradle/module-boundaries.txt doesn't allow." + val boundaries = providers.fileContents(boundariesFile).asText + val declared = declaredProjectDependencies + inputs.property("declared", declared) + inputs.file(boundariesFile) + doLast { + val allowed = boundaries.get().lineSequence() + .map { it.substringBefore('#').trim() } + .filter { it.isNotEmpty() } + .associate { line -> + val parts = line.split(Regex("\\s+")) + parts[0] to parts.drop(1).filter { it != "-" }.toSet() + } + val problems = mutableListOf() + for ((module, dependencies) in declared.get().toSortedMap()) { + val allowedForModule = allowed[module] + if (allowedForModule == null) { + problems += "$module isn't listed in gradle/module-boundaries.txt" + continue + } + for (dependency in dependencies.sorted()) { + if (dependency !in allowedForModule) { + problems += "$module may not depend on $dependency (allowed: ${allowedForModule.sorted().ifEmpty { listOf("nothing") }.joinToString()})" + } + } + } + if (problems.isNotEmpty()) { + throw GradleException( + "Module boundary violations (see gradle/module-boundaries.txt and ARCHITECTURE.md):\n" + + problems.joinToString("\n") { " - $it" }) + } + logger.lifecycle("Module boundaries hold for ${declared.get().size} modules.") + } +} + +// `./gradlew check` runs this and every module's own `check`. +tasks.register("check") { + group = "verification" + description = "Runs the repo-wide module boundary check." + dependsOn(checkModuleBoundaries) +} diff --git a/incari-client/files/client/AGENTS.md b/incari-client/files/client/AGENTS.md new file mode 100644 index 0000000..47d1aa9 --- /dev/null +++ b/incari-client/files/client/AGENTS.md @@ -0,0 +1,18 @@ +# client + +- Game changes are patches: edit `work/client`, commit there (`:

`), run + `./incari rebuild`. Never edit `patches/` by hand. +- A patch is a one- or two-line hook into Incari code, wrapped in `// Incari start: ` and + `// Incari end`. Decompile fixes (`decompile:` subsystem) are the only unmarked patches. +- Incari code in `src/main/java` is adapters only: logic goes in a strict module. It may use game + types and `platform-api`, never LWJGL or TeaVM (`BoundaryTest`). +- Test: `./gradlew :client:check` (needs `./incari setup`). +- Incari's screens get their widgets from `incari.client.ui` (`Ui`, `Theme`, `ControlList`, + `ListScreen`), never by making the game's widgets themselves: the restyle changes that + package and the screens follow. Colors and sizes come from `Theme`, not literals. +- The game's own screens are changed with `ScreenEdits` (ADR 0047): `edit` to move, remove or add + widgets after each layout, `replace` to show an Incari screen instead. Prefer that to a new patch + per screen. How the GUI looks is a `GuiSkin` (`Skins.use`), never per-screen drawing code; skin + methods are hot paths. +- Feature logic lives in `features/*` (ADR 0046); `incari.client.modules` only adapts the game to + `:framework`. diff --git a/incari-client/files/client/README.md b/incari-client/files/client/README.md new file mode 100644 index 0000000..14717c1 --- /dev/null +++ b/incari-client/files/client/README.md @@ -0,0 +1,52 @@ +# client: the game + +## Purpose + +Builds Minecraft from the patched vendor tree in `work/client`, together with the Incari code the +patches call. It's one compilation because the calls go both ways (ARCHITECTURE.md). + +## Entry points + +- The vendor tree: `work/client/src/main/java`, generated by `./incari setup`. +- Replacement classes: `src/main/java/com/mojang/...`, Incari's versions of the vendor classes + `patches/classes.txt` replaces (the window, event pump, audio...). They keep the game's API and + delegate to `platform-api`; the build compiles them instead of the vendor copies. +- Incari's code: `src/main/java/incari/client`, the adapters between the game, the platform and + Incari's strict modules. Each package's `package-info.java` says what it holds. + +| Package | What it holds | +| --- | --- | +| `platform` | Hooks the patches call into the installed platform: window, input, lifecycle, graphics backends; `OnlineServices` turns Realms and Mojang's services off (ADR 0074); `PlatformNotices` shows the platform's notices (saves not kept) and, once, the browser's Ctrl+W hint | +| `net` | Joining servers: WebSocket addresses (ADR 0009), each join's pipeline and the server's version (`ServerConnections`, `VersionRetry`, `JoinFailures`; Via off unless turned on per server, on the edit-server screen or Direct Connect (`DirectJoinVia`), with `ViaHint` on a refusal (not for featured servers) and "Needs Via" in the list for an Eagler server known to run another version; ADR 0017, 0018, 0071), the packet handoff (ADR 0033), featured servers (ADR 0062), Reconnect and Auto Reconnect on the disconnection screen (`Reconnect`), and Connection Details there (`ConnectionDetailsScreen`, from `ConnectionReport`) | +| `eagler`, `skins` | Eagler servers' extras: passwords, cookies, redirects, voice chat (ADR 0019), Eagler skins (ADR 0016); `SkinDownloads` fetches profiles' skins, capes and custom heads through the platform; `ProfileTextures` reads them with Mojang's services off (ADR 0074) | +| `relay` | Worlds shared through Eagler relays, joined and hosted (ADR 0019, 0062) | +| `legacy` | Playing older servers as their clients did, 1.8 above all (ADR 0020) | +| `singleplayer` | Singleplayer's server in a Web Worker (ADR 0039 to 0043); it saves when the page is hidden or closed (`SAVE`, posted by the page itself) | +| `audio`, `resources` | Sounds through the platform's decoder (ADR 0013); resources fetched from the asset index (ADR 0037); `PackDownloads` fetches servers' resource packs in a page (hosts must allow CORS) | +| `render`, `gui`, `particle`, `world` | Performance work in the game's own paths (ADR 0022 to 0034) | +| `memory`, `datafix`, `startup`, `tier` | The memory diet (ADR 0025), start-up (ADR 0026), the device's quality tier | +| `profiler` | The F9 profiler overlay (ADR 0021) | +| `modules` | The game's side of the module framework (ADR 0046): events, keybinds, the HUD, the module menu | +| `ui`, `look` | Incari's UI kit, screen edits and skins (ADR 0047), and the Frost look (ADR 0048) | +| `online`, `cosmetics` | Account and chat screens (ADR 0058, 0059); cosmetics, the Wardrobe and emotes (ADR 0061) | +| `settings`, `recorder`, `credits`, `profile` | Incari Settings and the screen recorder (ADR 0062), the credits, Edit Profile (ADR 0029) | +| `account` | Microsoft sign-in (ADR 0070): the saved account, its screen, the handshake's session join, chat keys | +| `IncariKeys`, `IncariTicks`, `TickPacing` | Incari's key mappings, its once-a-tick work, catch-up ticks paced (ADR 0032) | + +## Invariants + +- **Incari code here is platform-neutral**: the `incari.client` packages and every replacement + class reach the machine only through `platform-api` (`BoundaryTest`), never LWJGL or TeaVM. +- **Replacements are written fresh**, never adapted from the decompiled class (`./incari copycheck`). +- **Vendor code is compiled as-is**: lint off, never edited to silence a warning. Incari's sources + are rechecked with the full gates by `strictCompile`. +- **Screens fit the smallest GUI the game allows, 320x240**, in Incari's font and the pixel font: + widgets trim their own text (`Ui.fit`), list rows narrow with the screen. `smokeLayout` checks. +- **The build needs `./incari setup` first**; it fails with that hint otherwise. +- **Output matches the jar**: every class Mojang ships is compiled from source (11,383 for 26.3). + +## How to test + +```sh +./gradlew :client:check # compiles ~11,000 classes, then strictCompile and the tests +``` diff --git a/incari-client/files/client/build.gradle.kts b/incari-client/files/client/build.gradle.kts new file mode 100644 index 0000000..43ae22c --- /dev/null +++ b/incari-client/files/client/build.gradle.kts @@ -0,0 +1,254 @@ +import java.util.Properties +import net.ltgt.gradle.errorprone.errorprone + +plugins { + `java-library` +} + +// The game: the patched vendor tree in work/client (generated by `./incari setup`, never +// tracked) compiled together with the Incari code in src/main/java that vendor patches call. +// They are one compilation because the dependency runs both ways: patches call Incari hooks, +// and the hooks use game types. + +val repoRoot = rootProject.layout.projectDirectory +val minecraftVersion: String = Properties().run { + repoRoot.file("incari.properties").asFile.reader().use { load(it) } + getProperty("minecraft.version") +} +val vendorSources = repoRoot.dir("work/client/src/main/java") +val vendorClasspathList = repoRoot.file("work/cache/versions/$minecraftVersion/classpath.txt") + +/** Mojang's libraries for this version, as `incari fetch` downloaded and checked them. */ +val vendorLibraries = run { + // A local, not the script property: a lambda capturing the script can't be cached. + val root = repoRoot.asFile + providers.fileContents(vendorClasspathList).asText.map { text -> + text.lines().filter { it.isNotBlank() }.map { root.resolve(it.trim()) } + }.orElse(emptyList()) +} + +val clientJar = repoRoot.file("work/cache/versions/$minecraftVersion/client.jar") + +// The game's own resources (textures, models, data packs, version.json) from Mojang's jar, next +// to the classes compiled from source. Kept in build/, which is never tracked or published. +val gameResources = tasks.register("gameResources") { + description = "Extracts the non-class files of Mojang's client jar." + from(zipTree(clientJar)) { + exclude("**/*.class") + // Mojang's signature covers Mojang's classes, not these; a partial signature breaks loading. + exclude("META-INF/**") + } + into(layout.buildDirectory.dir("game-resources")) +} + +/** + * Vendor files that patches/classes.txt deletes or replaces. Replacements are Incari sources in + * this module's src/main/java (`./incari apply` also copies them into work/client, so the tree + * is complete on its own); the build compiles them from here and skips the vendor path. + */ +val manifestOwnedFiles: Set = repoRoot.file("patches/classes.txt").asFile.readLines() + .map { it.substringBefore('#').trim() } + .filter { it.isNotEmpty() } + .map { it.split(Regex("\\s+"))[1].replace('.', '/') + ".java" } + .toSet() + +// The online service's URL (ADR 0058), built in: `-Pincari.online.url=`, else +// incari.properties' `incari.online.url`; empty turns accounts off. A URL, never a key or secret: +// anything in a page can be read by whoever opens it. The page's ?online= and the desktop's +// -Dincari.online.url override it for testing against a local service. +val onlineUrl: String = providers.gradleProperty("incari.online.url").orNull ?: Properties().run { + repoRoot.file("incari.properties").asFile.reader().use { load(it) } + getProperty("incari.online.url", "") +} +val onlineUrlSource = tasks.register("onlineUrlSource") { + description = "Writes the online service's URL into a generated source." + val url = onlineUrl + val out = layout.buildDirectory.dir("generated/sources/online") + inputs.property("url", url) + outputs.dir(out) + doLast { + val file = out.get().file("incari/client/online/OnlineUrl.java").asFile + file.parentFile.mkdirs() + val quoted = url.replace("\\", "\\\\").replace("\"", "\\\"") + file.writeText( + """ + |package incari.client.online; + | + |/** Generated by :client's onlineUrlSource from incari.online.url. */ + |final class OnlineUrl { + | static final String BUILT_IN = "$quoted"; + | + | private OnlineUrl() {} + |} + |""".trimMargin()) + } +} + +// This build's Incari version, public repository and game version (incari.properties), and whether it's a release +// build (`-Pteavm.release`, as `./incari build` makes): only those show the title screen's update +// notice. Dev builds never do, except for tests (-Dincari.updates=on, the page's ?updates=on). +val incariProperties = Properties().apply { + repoRoot.file("incari.properties").asFile.reader().use { load(it) } +} +val buildInfoSource = tasks.register("buildInfoSource") { + description = "Writes this build's Incari version, repository, featured servers, game version and release flag into a generated source." + val version = incariProperties.getProperty("incari.version", "") + val minecraftVersion = incariProperties.getProperty("minecraft.version", "") + val repository = incariProperties.getProperty("incari.repository", "") + val featured = incariProperties.getProperty("incari.featured", "") + val release = providers.gradleProperty("teavm.release").isPresent + val out = layout.buildDirectory.dir("generated/sources/build-info") + inputs.property("version", version) + inputs.property("repository", repository) + inputs.property("featured", featured) + inputs.property("minecraftVersion", minecraftVersion) + inputs.property("release", release) + outputs.dir(out) + doLast { + val file = out.get().file("incari/client/IncariBuild.java").asFile + file.parentFile.mkdirs() + fun quoted(text: String) = "\"" + text.replace("\\", "\\\\").replace("\"", "\\\"") + "\"" + file.writeText( + """ + |package incari.client; + | + |/** Generated by :client's buildInfoSource from incari.properties and -Pteavm.release. */ + |public final class IncariBuild { + | /** This build's Incari Client version. */ + | public static final String VERSION = ${quoted(version)}; + | /** The public repository, where the update notice leads. */ + | public static final String REPOSITORY = ${quoted(repository)}; + | /** The featured servers built in, as "name|address" joined by ";" (ADR 0062). */ + | public static final String FEATURED = ${quoted(featured)}; + | /** + | * The Minecraft release this tree targets ("26.3"). For code that runs before the game's + | * own SharedConstants can be read, such as the page naming its cached client jar. + | */ + | public static final String MINECRAFT_VERSION = ${quoted(minecraftVersion)}; + | /** Whether this is a release build, the kind players are given. */ + | public static final boolean RELEASE = $release; + | + | private IncariBuild() {} + |} + |""".trimMargin()) + } +} + +sourceSets.main { + java.srcDir(onlineUrlSource) + java.srcDir(buildInfoSource) + java.srcDir(vendorSources) + // Locals, not script properties: a lambda capturing the script can't be cached. + val vendorRoot = vendorSources.asFile + val ownedByManifest = manifestOwnedFiles + java.exclude { element -> element.file.startsWith(vendorRoot) && element.relativePath.pathString in ownedByManifest } + output.dir(mapOf("builtBy" to gameResources), layout.buildDirectory.dir("game-resources")) +} + +dependencies { + api(project(":platform-api")) + api(project(":net")) + api(project(":via")) + // Incari's terrain mesher: the game's section compiles go to it through incari.client.render.mesher. + api(project(":mesher")) + // The module framework (ADR 0046): incari.client.modules adapts the game to it, and lists + // the features below. + api(project(":framework")) + // Incari accounts and the online service (ADR 0058): incari.client.online draws the account + // screens and feeds it the world. + api(project(":online")) + implementation(project(":features:togglesprint")) + implementation(project(":features:lowfire")) + implementation(project(":features:nohurtcam")) + implementation(project(":features:clearchat")) + implementation(project(":features:armorpotionview")) + implementation(project(":features:customscoreboard")) + implementation(project(":features:waypoints")) + implementation(project(":features:minimap")) + implementation(project(":features:fpsdisplay")) + implementation(project(":features:cps")) + implementation(project(":features:reachdisplay")) + implementation(project(":features:keystrokes")) + implementation(project(":features:coordinates")) + implementation(project(":features:shieldtotem")) + implementation(project(":features:cooldownindicator")) + implementation(project(":features:crosshair")) + implementation(project(":features:freelook")) + implementation(project(":features:zoom")) + implementation(project(":features:saturation")) + implementation(project(":features:weatherchanger")) + implementation(project(":features:lowshield")) + implementation(project(":features:shortitems")) + implementation(project(":features:oldtextures")) + implementation(project(":features:blockoutline")) + implementation(project(":features:hitcolor")) + implementation(project(":features:glintcolor")) + implementation(project(":features:hiteffects")) + implementation(project(":features:fullbright")) + implementation(project(":features:customsky")) + implementation(project(":features:hitboxes")) + implementation(project(":features:schematics")) + implementation(project(":features:norender")) + implementation(project(":features:fastcrystal")) + implementation(project(":features:oldanimations")) + implementation(project(":features:shulkertooltips")) + implementation(project(":features:theme")) + api(files(vendorLibraries)) + // Annotations Mojang compiled against but doesn't ship in the game's libraries. + compileOnlyApi(libs.jetbrains.annotations) + compileOnlyApi(libs.jsr305) + + testImplementation(platform(libs.junit.bom)) + testImplementation(libs.junit.jupiter) + testImplementation(libs.assertj) + testImplementation(libs.archunit) + testImplementation(testFixtures(project(":online"))) + testRuntimeOnly(libs.junit.launcher) +} + +tasks.compileJava { + val tree = vendorSources.asFile + val classpathList = vendorClasspathList.asFile + doFirst { + if (!tree.isDirectory || !classpathList.isFile) { + throw GradleException("The client tree isn't set up yet. Run: ./incari setup") + } + } + // Roughly 9,000 vendor files in one compilation. + options.isFork = true + options.forkOptions.memoryMaximumSize = "6g" + // Vendor code is compiled as-is and never edited to silence a warning, so this compilation + // allows warnings. Incari's sources get the strict treatment in strictCompile below. + options.compilerArgs.add("-Xlint:none") + options.errorprone { + // Error Prone and NullAway check Incari's code here, never Mojang's. + excludedPaths = ".*/work/client/.*" + } +} + +// Recompiles only Incari's sources in this module, against the full build, with the flags every +// other Incari module uses: -Xlint:all -Werror plus Error Prone and NullAway. The output is +// thrown away; this is a check, and `check` runs it. +val strictCompile = tasks.register("strictCompile") { + group = "verification" + description = "Compiles Incari's own sources in :client with warnings as errors." + source = fileTree("src/main/java") + classpath = files(tasks.compileJava.flatMap { it.destinationDirectory }) + sourceSets.main.get().compileClasspath + destinationDirectory = layout.buildDirectory.dir("strict-compile") + javaCompiler = javaToolchains.compilerFor { languageVersion = JavaLanguageVersion.of(25) } + options.compilerArgs.addAll(listOf("-Xlint:all,-classfile", "-Werror")) +} + +tasks.check { + dependsOn(strictCompile) +} + +tasks.test { + // Game classes loaded by tests write logs/ into the working directory; keep that in build/. + val runDir = layout.buildDirectory.dir("test-run").get().asFile + workingDir = runDir + systemProperty("incari.repoRoot", rootDir.path) + // ArchUnit imports the whole game to check the replacement classes. + maxHeapSize = "3g" + doFirst { runDir.mkdirs() } +} diff --git a/incari-client/files/client/src/main/java/com/mojang/blaze3d/Blaze3D.java b/incari-client/files/client/src/main/java/com/mojang/blaze3d/Blaze3D.java new file mode 100644 index 0000000..0032ff1 --- /dev/null +++ b/incari-client/files/client/src/main/java/com/mojang/blaze3d/Blaze3D.java @@ -0,0 +1,54 @@ +package com.mojang.blaze3d; + +import incari.client.platform.ClientPlatform; +import incari.client.world.FolderDownloads; +import java.net.URI; +import java.nio.file.Path; + +/** Incari's replacement for Mojang's {@code Blaze3D} helpers (patches/classes.txt), over the platform. */ +public class Blaze3D { + + private static final double NANOS_PER_SECOND = 1_000_000_000.0; + + private Blaze3D() {} + + /** The debug crash: kills the process the way a native bug would, to test crash handling. */ + public static void youJustLostTheGame() { + ClientPlatform.get().crashNatively(); + } + + /** Seconds on the platform's monotonic clock. The game's frame timing is built on it. */ + public static double getTime() { + return ClientPlatform.get().nanoTime() / NANOS_PER_SECOND; + } + + /** Opens a link in the player's browser, without waiting for it. */ + public static void openUri(final URI uri) { + ClientPlatform.get().shell().open(uri); + } + + /** + * Opens a folder or file in the system's file manager. In the browser a file downloads, a + * folder the player adds files to (the pack folders) offers the file picker + * ({@code PlatformShell.openPath}), and any other folder (a world, the backups) downloads as a + * zip ({@link FolderDownloads}). + */ + public static void openPath(final Path path) { + Path absolute = path.toAbsolutePath().normalize(); + if (FolderDownloads.shouldDownload(absolute)) { + FolderDownloads.download(absolute); + return; + } + ClientPlatform.get().shell().openPath(absolute.toString()); + } + + /** + * Opens a folder for the player to put files in: the system's file manager, or in the browser + * the file picker, whose files reach the game as a drop. Incari's own folders (skins, capes). + */ + public static void openFolderToAddFiles(final Path folder) { + ClientPlatform.get() + .shell() + .openPath(folder.toAbsolutePath().normalize().toString()); + } +} diff --git a/incari-client/files/client/src/main/java/com/mojang/blaze3d/audio/CallbackDeviceTracker.java b/incari-client/files/client/src/main/java/com/mojang/blaze3d/audio/CallbackDeviceTracker.java new file mode 100644 index 0000000..316a762 --- /dev/null +++ b/incari-client/files/client/src/main/java/com/mojang/blaze3d/audio/CallbackDeviceTracker.java @@ -0,0 +1,50 @@ +package com.mojang.blaze3d.audio; + +import incari.platform.api.Platforms; +import incari.platform.api.audio.PlatformAudio; + +/** + * Incari replacement: tracks device changes the platform announces, instead of polling. The + * platform's notice only raises a flag; the list itself is re-read on the game's next tick, as + * {@link AbstractDeviceTracker} does for every tracker. + */ +public class CallbackDeviceTracker extends AbstractDeviceTracker { + + /** Written by the platform's notification thread, read and cleared by the game's tick. */ + private volatile boolean updateRequested; + + public CallbackDeviceTracker(final DeviceList deviceList) { + super(deviceList); + } + + @Override + protected boolean isUpdateRequested() { + return updateRequested; + } + + @Override + protected void discardUpdateRequest() { + updateRequested = false; + } + + /** Whether the running platform announces device changes. */ + public static boolean isSupported() { + return Platforms.current().audio().reportsDeviceChanges(); + } + + /** A tracker that the running platform's announcements flag for an update. */ + public static CallbackDeviceTracker createAndInstall(final DeviceList deviceList) { + return createAndInstall(Platforms.current().audio(), deviceList); + } + + static CallbackDeviceTracker createAndInstall(final PlatformAudio audio, final DeviceList deviceList) { + CallbackDeviceTracker tracker = new CallbackDeviceTracker(deviceList); + audio.setDeviceChangeListener(tracker::requestUpdate); + return tracker; + } + + // Must not block or touch the game: it runs on the platform's notification thread. + private void requestUpdate() { + updateRequested = true; + } +} diff --git a/incari-client/files/client/src/main/java/com/mojang/blaze3d/audio/Channel.java b/incari-client/files/client/src/main/java/com/mojang/blaze3d/audio/Channel.java new file mode 100644 index 0000000..037444e --- /dev/null +++ b/incari-client/files/client/src/main/java/com/mojang/blaze3d/audio/Channel.java @@ -0,0 +1,206 @@ +package com.mojang.blaze3d.audio; + +import com.mojang.logging.LogUtils; +import incari.client.audio.CompressedSoundStream; +import incari.platform.api.audio.AudioBuffer; +import incari.platform.api.audio.AudioDevice; +import incari.platform.api.audio.AudioException; +import incari.platform.api.audio.AudioSource; +import incari.platform.api.audio.PcmFormat; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.concurrent.atomic.AtomicBoolean; +import javax.sound.sampled.AudioFormat; +import net.minecraft.client.sounds.AudioStream; +import net.minecraft.world.phys.Vec3; +import org.jspecify.annotations.Nullable; +import org.slf4j.Logger; + +/** + * Incari replacement: one playing sound, over a platform {@link AudioSource}. + * + *

It plays either a whole decoded {@link SoundBuffer} or an {@link AudioStream} (music, long + * records), which is decoded a second at a time into a short queue of buffers and topped up by + * {@link #updateStream} as they finish; or, on a device that streams compressed files itself (the + * browser's), is handed over whole. All calls come from the sound thread. + */ +public class Channel { + + private static final Logger LOGGER = LogUtils.getLogger(); + + /** Buffers kept queued ahead while streaming: enough to ride out a slow sound-thread tick. */ + private static final int STREAM_QUEUE_LENGTH = 4; + + public static final int BUFFER_DURATION_SECONDS = 1; + + private final AudioDevice device; + private final AudioSource source; + private final AtomicBoolean initialized = new AtomicBoolean(true); + private @Nullable AudioStream stream; + private @Nullable PcmFormat streamFormat; + private int streamChunkBytes; + + /** A new channel on {@code device}, or null if it has no free source. */ + static @Nullable Channel create(final AudioDevice device) { + AudioSource source = device.createSource(); + return source == null ? null : new Channel(device, source); + } + + private Channel(final AudioDevice device, final AudioSource source) { + this.device = device; + this.source = source; + } + + /** Stops, closes the stream if any, and frees the source. Only the first call does anything. */ + public void destroy() { + if (!initialized.compareAndSet(true, false)) { + return; + } + source.stop(); + AudioStream current = stream; + if (current != null) { + try { + current.close(); + } catch (IOException e) { + LOGGER.error("Failed to close audio stream", e); + } + stream = null; + } + // Frees the queued stream buffers too. A static buffer belongs to its SoundBuffer. + source.close(); + } + + public void play() { + if (initialized.get()) { + source.play(); + } + } + + private AudioSource.State state() { + return initialized.get() ? source.state() : AudioSource.State.STOPPED; + } + + public void pause() { + if (state() == AudioSource.State.PLAYING) { + source.pause(); + } + } + + public void unpause() { + if (state() == AudioSource.State.PAUSED) { + source.play(); + } + } + + public void stop() { + if (initialized.get()) { + source.stop(); + } + } + + public boolean playing() { + return state() == AudioSource.State.PLAYING; + } + + /** + * Whether it has finished (or was destroyed). A channel that was set up but never played is + * not stopped, so the game doesn't reclaim it before its first {@link #play}. + */ + public boolean stopped() { + return state() == AudioSource.State.STOPPED; + } + + public void setSelfPosition(final Vec3 newPosition) { + source.setPosition(newPosition.x, newPosition.y, newPosition.z); + } + + public void setPitch(final float pitch) { + source.setPitch(pitch); + } + + public void setLooping(final boolean looping) { + source.setLooping(looping); + } + + public void setVolume(final float volume) { + source.setGain(volume); + } + + public void disableAttenuation() { + source.disableAttenuation(); + } + + public void linearAttenuation(final float maxDistance) { + source.setLinearAttenuation(maxDistance); + } + + public void setRelative(final boolean relative) { + source.setRelative(relative); + } + + public void attachStaticBuffer(final SoundBuffer buffer) { + AudioBuffer uploaded = buffer.bufferOn(device); + if (uploaded != null) { + source.setBuffer(uploaded); + } + } + + public void attachBufferStream(final AudioStream stream) { + if (stream instanceof CompressedSoundStream compressed && device.streamsOggVorbis()) { + this.stream = stream; + try { + source.streamOggVorbis(compressed.file(), compressed.looping()); + } catch (AudioException e) { + LOGGER.error("Can't stream audio: {}", e.getMessage()); + } + return; + } + AudioFormat format = stream.getFormat(); + this.stream = stream; + this.streamChunkBytes = bytesPerSeconds(format, BUFFER_DURATION_SECONDS); + try { + this.streamFormat = SoundBuffer.toPcmFormat(format); + } catch (IllegalArgumentException e) { + LOGGER.error("Can't stream audio: {}", e.getMessage()); + this.streamFormat = null; + return; + } + queueChunks(STREAM_QUEUE_LENGTH); + } + + /** How many bytes of {@code format} last {@code seconds}. */ + static int bytesPerSeconds(final AudioFormat format, final int seconds) { + float bytesPerSample = format.getSampleSizeInBits() / 8.0F; + return (int) (seconds * format.getSampleRate() * format.getChannels() * bytesPerSample); + } + + /** Refills the stream's queue with as many chunks as finished playing since the last call. */ + public void updateStream() { + if (stream != null) { + queueChunks(source.releaseProcessedBuffers()); + } + } + + /** Decodes up to {@code count} more chunks of the stream and queues them. */ + private void queueChunks(final int count) { + AudioStream current = stream; + PcmFormat format = streamFormat; + if (current == null || format == null) { + return; + } + try { + for (int i = 0; i < count; i++) { + ByteBuffer chunk = current.read(streamChunkBytes); + // The decoder hands back an empty buffer at the end; queueing nothing is fine. + if (!chunk.hasRemaining()) { + continue; + } + source.queue(device.createBuffer(chunk, format)); + } + } catch (IOException e) { + LOGGER.error("Failed to read from audio stream", e); + } catch (AudioException e) { + LOGGER.error("Failed to queue audio stream data: {}", e.getMessage()); + } + } +} diff --git a/incari-client/files/client/src/main/java/com/mojang/blaze3d/audio/DeviceList.java b/incari-client/files/client/src/main/java/com/mojang/blaze3d/audio/DeviceList.java new file mode 100644 index 0000000..24f838b --- /dev/null +++ b/incari-client/files/client/src/main/java/com/mojang/blaze3d/audio/DeviceList.java @@ -0,0 +1,25 @@ +package com.mojang.blaze3d.audio; + +import incari.platform.api.Platforms; +import incari.platform.api.audio.AudioDeviceList; +import java.util.List; +import org.jspecify.annotations.Nullable; + +/** + * Incari replacement: the output devices the platform offers, in the game's own type. The options + * screen lists {@link #allDevices}; the sound engine compares snapshots to notice changes, which + * is why this stays a record (value equality). + */ +public record DeviceList(@Nullable String defaultDevice, List allDevices) { + + public static final DeviceList EMPTY = new DeviceList(null, List.of()); + + /** Asks the platform now. May be slow on the desktop (it probes the system), so the game calls it off the render thread. */ + public static DeviceList query() { + return from(Platforms.current().audio().devices()); + } + + static DeviceList from(final AudioDeviceList devices) { + return new DeviceList(devices.defaultDevice(), devices.all()); + } +} diff --git a/incari-client/files/client/src/main/java/com/mojang/blaze3d/audio/Library.java b/incari-client/files/client/src/main/java/com/mojang/blaze3d/audio/Library.java new file mode 100644 index 0000000..055eef8 --- /dev/null +++ b/incari-client/files/client/src/main/java/com/mojang/blaze3d/audio/Library.java @@ -0,0 +1,252 @@ +package com.mojang.blaze3d.audio; + +import com.mojang.logging.LogUtils; +import incari.platform.api.Platforms; +import incari.platform.api.audio.AudioDevice; +import incari.platform.api.audio.AudioException; +import incari.platform.api.audio.PlatformAudio; +import java.util.ArrayList; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import net.minecraft.SharedConstants; +import org.jspecify.annotations.Nullable; +import org.slf4j.Logger; + +/** + * Incari replacement: the sound engine's output, over the platform's {@link PlatformAudio}. + * + *

It owns the open device and hands out {@link Channel}s from two pools, so that a burst of + * short sounds can never take the sources music and records need: most sources go to + * {@link Pool#STATIC} sounds, and a few (about the square root of the total) are kept for + * {@link Pool#STREAMING} ones. + */ +public class Library { + + private static final Logger LOGGER = LogUtils.getLogger(); + + /** What {@link #currentDeviceName} reports while nothing is open. */ + private static final String NO_DEVICE_NAME = "(None)"; + + private static final int MIN_STREAMING = 2; + private static final int MAX_STREAMING = 8; + private static final int MIN_STATIC = 8; + private static final int MAX_STATIC = 255; + + private @Nullable AudioDevice device; + private String currentDeviceName = NO_DEVICE_NAME; + private ChannelPool staticChannels = ChannelPool.NONE; + private ChannelPool streamingChannels = ChannelPool.NONE; + private final Listener listener = new Listener(); + + /** + * Opens a device: the player's choice, else the system default the game last saw, else + * whatever the platform picks. + * + * @param preferredDevice the device from the options, or null to use the default + * @param currentDevices the devices as the game last listed them + * @param useHrtf whether to spatialize with HRTF ("Directional Audio") + * @throws IllegalStateException if no device can be opened + */ + public void init(final @Nullable String preferredDevice, final DeviceList currentDevices, final boolean useHrtf) { + init(Platforms.current().audio(), preferredDevice, currentDevices, useHrtf); + } + + void init( + final PlatformAudio audio, + final @Nullable String preferredDevice, + final DeviceList currentDevices, + final boolean useHrtf) { + currentDeviceName = NO_DEVICE_NAME; + AudioDevice opened = openWithFallback(audio, preferredDevice, currentDevices.defaultDevice(), useHrtf); + device = opened; + currentDeviceName = opened.name(); + + int total = opened.maxSources(); + int streaming = streamingPoolSize(total); + staticChannels = new ChannelPool(opened, staticPoolSize(total, streaming)); + streamingChannels = new ChannelPool(opened, streaming); + listener.attach(opened.listener()); + LOGGER.info("Sound output opened on device {}", currentDeviceName); + } + + /** Sources kept for streams: the square root of the total, between 2 and 8. */ + static int streamingPoolSize(final int totalSources) { + int root = (int) Math.sqrt(totalSources); + return Math.clamp(root, MIN_STREAMING, MAX_STREAMING); + } + + /** + * Sources for everything else: the rest, between 8 and 255. The floor can promise more than a + * tiny device has; then acquiring just fails early, as the device runs out. + */ + static int staticPoolSize(final int totalSources, final int streamingSources) { + return Math.clamp(totalSources - streamingSources, MIN_STATIC, MAX_STATIC); + } + + /** + * Tries each candidate in turn, skipping repeats, and returns the first that opens. A failed + * one is only logged: an unplugged favourite shouldn't leave the game silent. + */ + static AudioDevice openWithFallback( + final PlatformAudio audio, + final @Nullable String preferredDevice, + final @Nullable String systemDefault, + final boolean useHrtf) { + List<@Nullable String> candidates = new ArrayList<>(3); + if (preferredDevice != null) { + candidates.add(preferredDevice); + } + if (systemDefault != null && !systemDefault.equals(preferredDevice)) { + candidates.add(systemDefault); + } + candidates.add(null); // The platform's own default. + + @Nullable AudioException lastFailure = null; + for (String candidate : candidates) { + try { + return audio.open(candidate, useHrtf); + } catch (AudioException e) { + LOGGER.warn( + "Couldn't open sound device {}: {}", + candidate == null ? "(default)" : candidate, + e.getMessage()); + lastFailure = e; + } + } + throw new IllegalStateException("Failed to open a sound device", lastFailure); + } + + public @Nullable String currentDeviceName() { + return currentDeviceName; + } + + /** Frees every channel and closes the device. Safe to call with nothing open. */ + public void cleanup() { + staticChannels.cleanup(); + streamingChannels.cleanup(); + // Nothing more can be handed out until the next init: the device is going away. + staticChannels = ChannelPool.NONE; + streamingChannels = ChannelPool.NONE; + listener.attach(null); + AudioDevice open = device; + if (open != null) { + open.close(); + } + device = null; + } + + public Listener getListener() { + return listener; + } + + /** A channel from {@code pool}, or null if the pool or the device is out of sources. */ + public @Nullable Channel acquireChannel(final Pool pool) { + return (pool == Pool.STREAMING ? streamingChannels : staticChannels).acquire(); + } + + /** + * Destroys a channel and returns its slot to its pool. + * + * @throws IllegalStateException if it didn't come from this library's current pools + */ + public void releaseChannel(final Channel channel) { + if (!staticChannels.release(channel) && !streamingChannels.release(channel)) { + throw new IllegalStateException("Tried to release unknown channel"); + } + } + + /** The "Sounds:" line of the debug screen: used/size of the static then the streaming pool. */ + public String getChannelDebugString() { + return String.format( + Locale.ROOT, + "Sounds: %d/%d + %d/%d", + staticChannels.usedCount(), + staticChannels.limit(), + streamingChannels.usedCount(), + streamingChannels.limit()); + } + + public boolean isCurrentDeviceDisconnected() { + AudioDevice open = device; + return open != null && open.isDisconnected(); + } + + /** + * A tracker for the device list: pushed changes when the platform announces them, polling + * otherwise. + */ + public static DeviceTracker createDeviceTracker() { + PlatformAudio audio = Platforms.current().audio(); + DeviceList devices = DeviceList.from(audio.devices()); + if (audio.reportsDeviceChanges()) { + LOGGER.debug("Tracking audio device changes through platform notifications"); + return CallbackDeviceTracker.createAndInstall(audio, devices); + } + LOGGER.debug("Tracking audio device changes by polling"); + return new PollingDeviceTracker(devices); + } + + /** A capped set of live channels on one device. */ + static final class ChannelPool { + + /** Before the first device opens and after it closes: hands out nothing. */ + static final ChannelPool NONE = new ChannelPool(null, 0); + + private final @Nullable AudioDevice device; + private final int limit; + private final Set active = Collections.newSetFromMap(new IdentityHashMap<>()); + + ChannelPool(final @Nullable AudioDevice device, final int limit) { + this.device = device; + this.limit = limit; + } + + @Nullable + Channel acquire() { + AudioDevice target = device; + if (target == null) { + return null; + } + if (active.size() >= limit) { + if (SharedConstants.IS_RUNNING_IN_IDE) { + LOGGER.warn("Maximum sound pool size {} reached", limit); + } + return null; + } + Channel channel = Channel.create(target); + if (channel != null) { + active.add(channel); + } + return channel; + } + + boolean release(final Channel channel) { + if (!active.remove(channel)) { + return false; + } + channel.destroy(); + return true; + } + + void cleanup() { + active.forEach(Channel::destroy); + active.clear(); + } + + int limit() { + return limit; + } + + int usedCount() { + return active.size(); + } + } + + public enum Pool { + STATIC, + STREAMING + } +} diff --git a/incari-client/files/client/src/main/java/com/mojang/blaze3d/audio/Listener.java b/incari-client/files/client/src/main/java/com/mojang/blaze3d/audio/Listener.java new file mode 100644 index 0000000..817fbcb --- /dev/null +++ b/incari-client/files/client/src/main/java/com/mojang/blaze3d/audio/Listener.java @@ -0,0 +1,49 @@ +package com.mojang.blaze3d.audio; + +import incari.platform.api.audio.AudioListener; +import net.minecraft.world.phys.Vec3; +import org.jspecify.annotations.Nullable; + +/** + * Incari replacement: the player's ears, forwarded to the open device's {@link AudioListener}. + * + *

The game creates this once, before any device is open, and keeps it across device changes. + * So it remembers the transform itself, and {@link Library} points it at each new device's + * listener as it opens. + */ +public class Listener { + + private ListenerTransform transform = ListenerTransform.INITIAL; + private @Nullable AudioListener target; + + public void setTransform(final ListenerTransform transform) { + this.transform = transform; + push(); + } + + public void reset() { + setTransform(ListenerTransform.INITIAL); + } + + public ListenerTransform getTransform() { + return transform; + } + + /** Sends every later transform to {@code target}, starting with the current one; null for no device. */ + void attach(final @Nullable AudioListener target) { + this.target = target; + push(); + } + + private void push() { + AudioListener out = target; + if (out == null) { + return; // No device open: the transform is kept for the next one. + } + Vec3 position = transform.position(); + Vec3 forward = transform.forward(); + Vec3 up = transform.up(); + out.setPosition(position.x, position.y, position.z); + out.setOrientation(forward.x, forward.y, forward.z, up.x, up.y, up.z); + } +} diff --git a/incari-client/files/client/src/main/java/com/mojang/blaze3d/audio/SoundBuffer.java b/incari-client/files/client/src/main/java/com/mojang/blaze3d/audio/SoundBuffer.java new file mode 100644 index 0000000..44c8814 --- /dev/null +++ b/incari-client/files/client/src/main/java/com/mojang/blaze3d/audio/SoundBuffer.java @@ -0,0 +1,128 @@ +package com.mojang.blaze3d.audio; + +import com.mojang.logging.LogUtils; +import incari.platform.api.audio.AudioBuffer; +import incari.platform.api.audio.AudioDevice; +import incari.platform.api.audio.AudioException; +import incari.platform.api.audio.DecodedAudio; +import incari.platform.api.audio.PcmFormat; +import java.nio.ByteBuffer; +import java.util.Objects; +import javax.sound.sampled.AudioFormat; +import org.jspecify.annotations.Nullable; +import org.slf4j.Logger; + +/** + * Incari replacement: a fully decoded sound, uploaded to the device the first time a channel + * plays it. + * + *

Decoding happens off the sound thread, before any device may be open, so the samples are + * held here until then: PCM from the game's decoder, or what the platform's own decoder produced + * (the browser's, ADR 0013). Once uploaded, the device copy is the only one: the samples are + * dropped to save memory, and {@link #discardAlBuffer} ends the buffer's life. + */ +public class SoundBuffer { + + private static final Logger LOGGER = LogUtils.getLogger(); + + private @Nullable ByteBuffer data; + private @Nullable DecodedAudio decoded; + private final AudioFormat format; + private final int size; + private @Nullable AudioBuffer uploaded; + private @Nullable AudioDevice uploadedTo; + + public SoundBuffer(final ByteBuffer data, final AudioFormat format) { + this.data = data; + this.format = format; + this.size = data.limit(); + } + + /** A sound the platform decoded: 32-bit float samples, as far as the game's statistics tell. */ + public SoundBuffer(final DecodedAudio decoded) { + this.decoded = decoded; + int frameSize = decoded.channels() * Float.BYTES; + this.format = new AudioFormat( + AudioFormat.Encoding.PCM_FLOAT, + decoded.sampleRate(), + Float.SIZE, + decoded.channels(), + frameSize, + decoded.sampleRate(), + false); + this.size = decoded.sizeInBytes(); + } + + /** + * The device copy of these samples, uploading them on first use. + * + * @return null if the upload failed (logged, and retried next time), or if the samples went + * to another device and were dropped here, or after {@link #discardAlBuffer} + */ + @Nullable + AudioBuffer bufferOn(final AudioDevice device) { + AudioBuffer buffer = uploaded; + if (buffer != null) { + return device.equals(uploadedTo) ? buffer : null; + } + ByteBuffer samples = data; + DecodedAudio platformSamples = decoded; + if (samples == null && platformSamples == null) { + return null; + } + try { + buffer = samples != null + ? device.createBuffer(samples, toPcmFormat(format)) + : device.createBuffer(Objects.requireNonNull(platformSamples)); + } catch (AudioException | IllegalArgumentException e) { + LOGGER.error("Couldn't upload a sound buffer: {}", e.getMessage()); + return null; + } + uploaded = buffer; + uploadedTo = device; + data = null; + decoded = null; + return buffer; + } + + /** Frees the device copy. The samples were dropped when it was made, so this buffer is spent. */ + public void discardAlBuffer() { + AudioBuffer buffer = uploaded; + if (buffer != null) { + buffer.close(); + } + uploaded = null; + uploadedTo = null; + } + + public AudioFormat format() { + return format; + } + + public int size() { + return size; + } + + /** Whether it can still be played: the samples are held here or on a device. */ + public boolean isValid() { + return data != null || decoded != null || uploaded != null; + } + + /** + * The platform's description of {@code format}. Only uncompressed PCM, mono or stereo, 8 or + * 16 bits: what the game's Ogg decoder produces. + * + * @throws IllegalArgumentException for anything else + */ + static PcmFormat toPcmFormat(final AudioFormat format) { + AudioFormat.Encoding encoding = format.getEncoding(); + if (!AudioFormat.Encoding.PCM_SIGNED.equals(encoding) && !AudioFormat.Encoding.PCM_UNSIGNED.equals(encoding)) { + throw new IllegalArgumentException("Not uncompressed PCM: " + format); + } + try { + return new PcmFormat((int) format.getSampleRate(), format.getChannels(), format.getSampleSizeInBits()); + } catch (AudioException e) { + throw new IllegalArgumentException("Unsupported audio format: " + format, e); + } + } +} diff --git a/incari-client/files/client/src/main/java/com/mojang/blaze3d/platform/ClipboardManager.java b/incari-client/files/client/src/main/java/com/mojang/blaze3d/platform/ClipboardManager.java new file mode 100644 index 0000000..6cd8d4f --- /dev/null +++ b/incari-client/files/client/src/main/java/com/mojang/blaze3d/platform/ClipboardManager.java @@ -0,0 +1,19 @@ +package com.mojang.blaze3d.platform; + +import incari.client.platform.ClientPlatform; +import net.minecraft.util.StringDecomposer; + +/** Incari's replacement for Mojang's clipboard access (patches/classes.txt), over the platform shell. */ +public class ClipboardManager { + + /** The clipboard's text, or "" if it holds none or can't be read (the platform logs why). */ + public String getClipboard() { + String text = ClientPlatform.get().shell().clipboardText(); + // Other programs can put lone surrogates on the clipboard; the game's text code can't take them. + return text == null ? "" : StringDecomposer.filterBrokenSurrogates(text); + } + + public void setClipboard(final String text) { + ClientPlatform.get().shell().setClipboardText(text); + } +} diff --git a/incari-client/files/client/src/main/java/com/mojang/blaze3d/platform/MacosUtil.java b/incari-client/files/client/src/main/java/com/mojang/blaze3d/platform/MacosUtil.java new file mode 100644 index 0000000..48993e8 --- /dev/null +++ b/incari-client/files/client/src/main/java/com/mojang/blaze3d/platform/MacosUtil.java @@ -0,0 +1,40 @@ +package com.mojang.blaze3d.platform; + +import incari.client.platform.ClientPlatform; +import incari.platform.api.window.PlatformWindow; +import incari.platform.api.window.SystemBehavior; +import net.minecraft.util.Util; + +/** + * Incari's replacement for Mojang's macOS helpers (patches/classes.txt). The two options the + * player controls go to the platform window; elsewhere they do nothing. + */ +public final class MacosUtil { + + public static final boolean IS_MACOS = Util.getPlatform() == Util.OS.OSX; + + private MacosUtil() {} + + /** + * Mojang hides the "Close Window" menu item, which would close the game without saving. + * Incari's desktop runtime doesn't drive the macOS menu (it would need the Objective-C bridge + * the browser build leaves out), so the item stays; Command+W then asks the game to close, + * which saves as usual. + */ + public static void disableCloseWindowMenuItem() {} + + public static void setFullscreenMenuVisibility(final boolean visible) { + setBehavior(SystemBehavior.MENU_BAR_IN_FULLSCREEN, visible); + } + + public static void setCtrlClickEmulatesRightClick(final boolean enabled) { + setBehavior(SystemBehavior.CTRL_CLICK_IS_RIGHT_CLICK, enabled); + } + + private static void setBehavior(final SystemBehavior behavior, final boolean enabled) { + PlatformWindow window = ClientPlatform.window(); + if (IS_MACOS && window != null) { + window.setSystemBehavior(behavior, enabled); + } + } +} diff --git a/incari-client/files/client/src/main/java/com/mojang/blaze3d/platform/MessageBox.java b/incari-client/files/client/src/main/java/com/mojang/blaze3d/platform/MessageBox.java new file mode 100644 index 0000000..ebc5b27 --- /dev/null +++ b/incari-client/files/client/src/main/java/com/mojang/blaze3d/platform/MessageBox.java @@ -0,0 +1,21 @@ +package com.mojang.blaze3d.platform; + +import incari.client.platform.ClientPlatform; + +/** + * Incari's replacement for Mojang's native message boxes (patches/classes.txt): the dialogs shown + * when something fails before or outside the game's own UI. + */ +public class MessageBox { + + private static final String TITLE = "Minecraft"; + + public static void error(final String message) { + ClientPlatform.get().shell().showErrorDialog(TITLE, message, false); + } + + /** Shows the error with Yes/No buttons; true if the player chose to continue. */ + public static boolean errorWithContinue(final String message) { + return ClientPlatform.get().shell().showErrorDialog(TITLE, message, true); + } +} diff --git a/incari-client/files/client/src/main/java/com/mojang/blaze3d/platform/Monitor.java b/incari-client/files/client/src/main/java/com/mojang/blaze3d/platform/Monitor.java new file mode 100644 index 0000000..1449370 --- /dev/null +++ b/incari-client/files/client/src/main/java/com/mojang/blaze3d/platform/Monitor.java @@ -0,0 +1,68 @@ +package com.mojang.blaze3d.platform; + +import com.mojang.logging.LogUtils; +import incari.client.platform.ClientPlatform; +import incari.client.platform.DisplayModes; +import incari.platform.api.window.DisplayInfo; +import incari.platform.api.window.DisplayMode; +import java.util.List; +import java.util.Locale; +import java.util.Optional; +import org.jspecify.annotations.Nullable; +import org.slf4j.Logger; + +/** + * Incari's replacement for Mojang's monitor record (patches/classes.txt): one display and the + * fullscreen modes the game offers on it, built from what the platform reports. + */ +public record Monitor( + String name, int id, List videoModes, VideoMode currentMode, int x, int y, int w, int h) { + + private static final Logger LOGGER = LogUtils.getLogger(); + + /** The display with this id, or null (and a warning) if the platform can't describe it. */ + public static @Nullable Monitor tryCreate(final int id) { + DisplayInfo display = ClientPlatform.get().displays().get(id); + if (display == null) { + LOGGER.warn("Failed to query monitor {}", id); + return null; + } + // The game's fullscreen resolutions need true colour; anything less isn't offered. + List modes = display.fullscreenModes().stream() + .filter(mode -> mode.redBits() >= 8 && mode.greenBits() >= 8 && mode.blueBits() >= 8) + .map(DisplayModes::toVideoMode) + .toList(); + DisplayMode desktop = display.desktopMode(); + return new Monitor( + display.name() + "[0x" + Integer.toHexString(id).toUpperCase(Locale.ROOT) + "]", + id, + modes, + DisplayModes.toVideoMode(desktop), + display.x(), + display.y(), + display.width(), + display.height()); + } + + /** The player's chosen mode if this monitor has it, otherwise the desktop's. */ + public VideoMode getPreferredVideoMode(final Optional chosen) { + return chosen.filter(this.videoModes::contains).orElse(this.currentMode); + } + + public int indexOfMode(final VideoMode mode) { + return this.videoModes.indexOf(mode); + } + + public VideoMode mode(final int index) { + return this.videoModes.get(index); + } + + public int modeCount() { + return this.videoModes.size(); + } + + @Override + public String toString() { + return this.name + "(" + this.currentMode + " at (" + this.x + "," + this.y + "))"; + } +} diff --git a/incari-client/files/client/src/main/java/com/mojang/blaze3d/platform/MonitorManager.java b/incari-client/files/client/src/main/java/com/mojang/blaze3d/platform/MonitorManager.java new file mode 100644 index 0000000..e9d713a --- /dev/null +++ b/incari-client/files/client/src/main/java/com/mojang/blaze3d/platform/MonitorManager.java @@ -0,0 +1,65 @@ +package com.mojang.blaze3d.platform; + +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.logging.LogUtils; +import incari.client.platform.ClientPlatform; +import incari.platform.api.window.DisplayInfo; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import org.jspecify.annotations.Nullable; +import org.slf4j.Logger; + +/** + * Incari's replacement for Mojang's monitor list (patches/classes.txt): the connected displays by + * platform id, kept current by the platform's display events on the render thread. + */ +public class MonitorManager { + + private static final Logger LOGGER = LogUtils.getLogger(); + private final Int2ObjectMap byId = new Int2ObjectOpenHashMap<>(); + + public MonitorManager() { + for (DisplayInfo display : ClientPlatform.get().displays().all()) { + this.update(display.id(), "found"); + } + } + + // Display events arrive on the render thread, which also owns the map. + + public void onDisplayConnected(final int id) { + RenderSystem.assertOnRenderThread(); + this.update(id, "connected"); + } + + public void onDisplayModeChanged(final int id) { + RenderSystem.assertOnRenderThread(); + this.update(id, "changed mode"); + } + + public void onDisplayDisconnected(final int id) { + RenderSystem.assertOnRenderThread(); + Monitor gone = this.byId.remove(id); + if (gone != null) { + LOGGER.debug("Display {} disconnected; displays now {}", gone, this.byId.values()); + } + } + + /** Re-reads one display from the platform; one that can't be read is left out. */ + private void update(final int id, final String what) { + Monitor fresh = Monitor.tryCreate(id); + if (fresh == null) { + return; + } + this.byId.put(id, fresh); + LOGGER.debug("Display {} {}; displays now {}", fresh, what, this.byId.values()); + } + + public @Nullable Monitor getMonitor(final int id) { + return this.byId.get(id); + } + + /** The monitor the window is mostly on. */ + public @Nullable Monitor findBestMonitor(final Window window) { + return this.byId.get(window.platformWindow().displayId()); + } +} diff --git a/incari-client/files/client/src/main/java/com/mojang/blaze3d/platform/SDLEventHandler.java b/incari-client/files/client/src/main/java/com/mojang/blaze3d/platform/SDLEventHandler.java new file mode 100644 index 0000000..ce0c169 --- /dev/null +++ b/incari-client/files/client/src/main/java/com/mojang/blaze3d/platform/SDLEventHandler.java @@ -0,0 +1,247 @@ +package com.mojang.blaze3d.platform; + +import incari.client.modules.IncariModules; +import incari.client.platform.ClientPlatform; +import incari.client.platform.PlatformNotices; +import incari.platform.api.PlatformNotice; +import incari.platform.api.input.KeyAction; +import incari.platform.api.input.KeyModifiers; +import incari.platform.api.window.PlatformEventListener; +import java.util.List; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.screens.options.controls.KeyBindsScreen; +import net.minecraft.client.input.InputQuirks; +import net.minecraft.client.input.KeyEvent; +import net.minecraft.client.input.MouseButtonInfo; +import net.minecraft.client.input.PreeditEvent; +import net.minecraft.client.server.IntegratedServer; +import org.jspecify.annotations.Nullable; + +/** + * Incari's replacement for Mojang's SDL event pump (patches/classes.txt). The name stays because + * the game refers to it; the events now come from the platform, and go to the same handlers. + * + *

Window events update the {@link Window} at once. Input events are handed to the game through + * {@link Minecraft#execute}, as before, so they run in the game's task order. + */ +public class SDLEventHandler implements PlatformEventListener { + + /** The game's key action codes (see {@code KeyEvent.Action}). */ + private static final int ACTION_RELEASE = 0; + + private static final int ACTION_PRESS = 1; + private static final int ACTION_REPEAT = -1; + + private final Minecraft minecraft; + private final Window window; + /** The game loop has run a pass, so frames have begun ({@link #pumpEvents}). */ + private boolean looping; + + /** The game's one handler, for Incari's own wait loops (singleplayer's server in a worker). */ + private static @Nullable SDLEventHandler current; + + public SDLEventHandler(final Minecraft minecraft, final Window window) { + this.minecraft = minecraft; + this.window = window; + current = this; + } + + /** The game's handler, once its window exists; null before. */ + public static @Nullable SDLEventHandler current() { + return current; + } + + /** + * Once per pass of the game loop ({@code Minecraft.run}): ends the frame, which lets a browser + * page run (its input, drawing and timers happen between the game's frames), then handles the + * events that arrived. + */ + public void pollEvents() { + looping = true; + ClientPlatform.get().endFrame(); + ClientPlatform.get().pollEvents(this); + // In a world, closing the page loses what the last save didn't keep (a browser asks first), + // and Ctrl+W, sprinting forward, is the browser's close-tab shortcut. + this.window.platformWindow().setLeaveWarning(this.minecraft.level != null); + PlatformNotices.tick(this.minecraft); + } + + /** + * Drops input queued during a stall, then handles what's left (window events). The game's wait + * loops call it between the frames they draw themselves (loading a singleplayer world, saving + * one on the way out), so once the game loop runs it ends the frame too: in the page, a loop + * that never ends its frame never lets the integrated server and the background pool run, + * which only get the page's thread between frames (world creation waited forever for its + * first chunk). Before the first frame (start-up) it only handles events. + */ + public void pumpEvents() { + if (looping) { + ClientPlatform.get().endFrame(); + } + this.flushInputEvents(); + ClientPlatform.get().pollEvents(this); + } + + public void flushInputEvents() { + ClientPlatform.get().flushInputEvents(); + } + + // --- Window --- + + @Override + public void closeRequested() { + this.window.onCloseRequested(); + } + + @Override + public void terminating() { + this.window.onTerminating(); + } + + @Override + public void windowMoved(final int x, final int y) { + this.window.onMoved(x, y); + } + + @Override + public void windowResized(final int width, final int height) { + this.window.onResized(width, height); + } + + @Override + public void framebufferResized(final int width, final int height) { + this.window.onFramebufferResized(width, height); + } + + @Override + public void minimizedChanged(final boolean minimized) { + if (minimized) { + // A hidden page may be closed next, with nothing run after. + IncariModules.saveNow(); + // Singleplayer's server on the page saves now too, as it does when the game pauses (a + // world in a worker is told by the page itself: PlatformChannel.sendWhenLeaving). + IntegratedServer server = this.minecraft.getSingleplayerServer(); + if (server != null) { + server.execute(() -> server.saveEverything(true, false, false)); + } + } + this.window.onMinimized(minimized); + } + + @Override + public void focusChanged(final boolean focused) { + this.window.onFocusChanged(focused); + } + + @Override + public void cursorEnteredOrLeft() { + this.window.onCursorEnteredOrLeft(); + } + + @Override + public void displayChanged() { + this.window.onDisplayChanged(); + } + + @Override + public void fullscreenChanged(final boolean fullscreen) { + this.window.onFullscreenChanged(); + } + + @Override + public void displayAdded(final int displayId) { + this.window.onDisplayAdded(displayId); + } + + @Override + public void displayRemoved(final int displayId) { + this.window.onDisplayRemoved(displayId); + } + + @Override + public void displayModeChanged(final int displayId) { + this.window.onDisplayModeChanged(displayId); + } + + // --- Keyboard --- + + @Override + public void key(final int scancode, final int keyCode, final int modifiers, final KeyAction action) { + int gameAction = + switch (action) { + case PRESS -> ACTION_PRESS; + case RELEASE -> ACTION_RELEASE; + case REPEAT -> ACTION_REPEAT; + }; + KeyEvent event = new KeyEvent(scancode, keyCode, modifiers); + long handle = this.window.handle(); + this.minecraft.execute(() -> this.minecraft.keyboardHandler.keyPress(handle, gameAction, event)); + } + + @Override + public void keymapChanged() { + // Key names depend on the layout: refresh them where they're shown (the modules' HUD + // names keys too, Keystrokes). + this.minecraft.execute(() -> { + IncariModules.keymapChanged(); + if (this.minecraft.gui.screen() instanceof KeyBindsScreen keyBinds) { + keyBinds.refreshKeybindLabels(); + } + }); + } + + @Override + public void textInput(final String text) { + long handle = this.window.handle(); + this.minecraft.execute(() -> this.minecraft.keyboardHandler.textInput(handle, text)); + } + + @Override + public void textEditing(final String text, final int start, final int length) { + PreeditEvent preedit = PreeditEvent.fromSdlTextEditing(text, start, length); + long handle = this.window.handle(); + this.minecraft.execute(() -> this.minecraft.keyboardHandler.textEditing(handle, preedit)); + } + + // --- Mouse --- + + @Override + public void mouseMoved(final double x, final double y, final double dx, final double dy) { + long handle = this.window.handle(); + this.minecraft.execute(() -> this.minecraft.mouseHandler.onMove(handle, x, y, dx, dy)); + } + + @Override + public void mouseButton(final int button, final boolean pressed, final int modifiers) { + MouseButtonInfo info = new MouseButtonInfo(button, modifiers); + int action = pressed ? ACTION_PRESS : ACTION_RELEASE; + long handle = this.window.handle(); + this.minecraft.execute(() -> this.minecraft.mouseHandler.onButton(handle, info, action)); + } + + @Override + public void mouseWheel(final double dx, final double dy, final int modifiers) { + double scrollX = dx; + double scrollY = dy; + // macOS turns Shift+wheel into horizontal scrolling; the game wants it vertical again. + if (InputQuirks.SHIFT_INVERTS_SCROLL_AXIS && dy == 0.0 && dx != 0.0 && (modifiers & KeyModifiers.SHIFT) != 0) { + scrollX = 0.0; + scrollY = -dx; + } + double finalX = scrollX; + double finalY = scrollY; + long handle = this.window.handle(); + this.minecraft.execute(() -> this.minecraft.mouseHandler.onScroll(handle, finalX, finalY)); + } + + @Override + public void notice(final PlatformNotice notice) { + PlatformNotices.show(this.minecraft, notice); + } + + @Override + public void filesDropped(final List paths) { + long handle = this.window.handle(); + this.minecraft.execute(() -> this.minecraft.mouseHandler.onDrop(handle, paths)); + } +} diff --git a/incari-client/files/client/src/main/java/com/mojang/blaze3d/platform/TextInputManager.java b/incari-client/files/client/src/main/java/com/mojang/blaze3d/platform/TextInputManager.java new file mode 100644 index 0000000..3182bf3 --- /dev/null +++ b/incari-client/files/client/src/main/java/com/mojang/blaze3d/platform/TextInputManager.java @@ -0,0 +1,76 @@ +package com.mojang.blaze3d.platform; + +import java.util.Objects; +import org.jspecify.annotations.Nullable; + +/** + * Incari's replacement for Mojang's text input manager (patches/classes.txt): turns text input on + * for whichever widget has focus, and tells the input method where that widget is. + */ +public class TextInputManager { + + private final Window window; + /** The widget text input is on for; only it may turn it off again. */ + private @Nullable Object owner; + + private boolean active; + private @Nullable Area area; + + /** The text area in window coordinates. */ + private record Area(int x, int y, int width, int height) {} + + public TextInputManager(final Window window) { + this.window = window; + } + + /** + * Sets where the text being edited is, in GUI coordinates (corners x0,y0 and x1,y1). The + * platform wants window coordinates: GUI units times the GUI scale gives pixels, and pixels + * over the pixel density gives window coordinates. + */ + public void setTextInputArea(final int x0, final int y0, final int x1, final int y1) { + double toWindow = this.window.getGuiScale() / (double) this.window.getPixelDensity(); + Area updated = new Area( + (int) Math.round(x0 * toWindow), + (int) Math.round(y0 * toWindow), + Math.max(1, (int) Math.round((x1 - x0) * toWindow)), + Math.max(1, (int) Math.round((y1 - y0) * toWindow))); + if (!Objects.equals(updated, this.area)) { + this.area = updated; + this.window.platformWindow().setTextInputArea(updated.x(), updated.y(), updated.width(), updated.height()); + } + } + + public void startTextInput(final Object newOwner) { + this.owner = newOwner; + if (!this.active) { + this.active = true; + this.window.platformWindow().startTextInput(); + } + } + + /** Turns text input off, if {@code previousOwner} is the widget that turned it on. */ + // Identity is the point: the owner is one particular widget, whatever its equals says. + @SuppressWarnings("ReferenceEquality") + public void stopTextInput(final Object previousOwner) { + if (this.owner == previousOwner) { + this.stopTextInput(); + } + } + + public void stopTextInput() { + this.owner = null; + if (this.active) { + this.active = false; + this.window.platformWindow().stopTextInput(); + } + } + + public void onTextInputFocusChange(final Object widget, final boolean focused) { + if (focused) { + this.startTextInput(widget); + } else { + this.stopTextInput(widget); + } + } +} diff --git a/incari-client/files/client/src/main/java/com/mojang/blaze3d/platform/Window.java b/incari-client/files/client/src/main/java/com/mojang/blaze3d/platform/Window.java new file mode 100644 index 0000000..005845d --- /dev/null +++ b/incari-client/files/client/src/main/java/com/mojang/blaze3d/platform/Window.java @@ -0,0 +1,602 @@ +package com.mojang.blaze3d.platform; + +import com.mojang.blaze3d.platform.cursor.CursorType; +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.logging.LogUtils; +import com.mojang.renderpearl.api.device.GpuBackend; +import incari.client.platform.ClientPlatform; +import incari.client.platform.DisplayModes; +import incari.platform.api.window.DisplayMode; +import incari.platform.api.window.IconImage; +import incari.platform.api.window.PlatformWindow; +import incari.platform.api.window.WindowSpec; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import net.minecraft.CrashReport; +import net.minecraft.CrashReportCategory; +import net.minecraft.ReportedException; +import net.minecraft.client.Minecraft; +import net.minecraft.client.input.InputQuirks; +import net.minecraft.client.main.SilentInitException; +import net.minecraft.server.packs.PackMetadataResources; +import org.jspecify.annotations.Nullable; +import org.slf4j.Logger; + +/** + * Incari's replacement for Mojang's window (patches/classes.txt). It keeps the game-facing state + * and rules (sizes, GUI scale, the fullscreen request, crash details) and leaves the operating + * system to a {@link PlatformWindow}: SDL on the desktop, the canvas in the browser. + */ +public final class Window implements AutoCloseable { + + private static final Logger LOGGER = LogUtils.getLogger(); + public static final int MIN_WINDOW_WIDTH = WindowSpec.MIN_WIDTH; + public static final int MIN_WINDOW_HEIGHT = WindowSpec.MIN_HEIGHT; + /** The GUI's design size at scale 1: the scale grows while a whole multiple of it still fits. */ + public static final int BASE_WIDTH = 320; + + public static final int BASE_HEIGHT = 240; + + private final WindowEventHandler eventHandler; + private final MonitorManager monitorManager; + private final PlatformWindow platformWindow; + + /** Where the window goes back to when it leaves fullscreen. */ + private int restoreX; + + private int restoreY; + private int restoreWidth; + private int restoreHeight; + + private int screenX; + private int screenY; + private int screenWidth; + private int screenHeight; + private int pixelWidth; + private int pixelHeight; + private int scaleFactor; + private int scaledWidth; + private int scaledHeight; + + private Optional preferredFullscreenVideoMode; + private boolean exclusiveFullscreen; + /** Whether the game wants fullscreen; {@link #fullscreen} is whether the window is. */ + private boolean fullscreenRequested; + + private boolean fullscreen; + private boolean fullscreenModeDirty; + + private String errorSection = "Startup"; + private boolean minimized; + private boolean hasFocus = true; + private boolean shouldClose; + private @Nullable Runnable closeCallback; + private boolean allowCursorChanges; + private boolean quitShortcuts; + private CursorType currentCursor = CursorType.DEFAULT; + + public Window( + final WindowEventHandler handler, + final DisplayData startup, + final @Nullable String savedFullscreenMode, + final boolean wantExclusive, + final String windowTitle, + final MonitorManager monitors, + final GpuBackend gpuBackend) { + this(handler, startup, savedFullscreenMode, wantExclusive, windowTitle, monitors, gpuBackend, 0); + } + + /** + * @param sizeLimit the largest the window may be in either dimension, or 0 for no limit + */ + public Window( + final WindowEventHandler handler, + final DisplayData startup, + final @Nullable String savedFullscreenMode, + final boolean wantExclusive, + final String windowTitle, + final MonitorManager monitors, + final GpuBackend gpuBackend, + final int sizeLimit) { + this.eventHandler = handler; + this.monitorManager = monitors; + this.exclusiveFullscreen = wantExclusive; + this.preferredFullscreenVideoMode = initialFullscreenMode(savedFullscreenMode, startup); + this.fullscreenRequested = startup.isFullscreen(); + + this.screenWidth = Math.max(startup.width(), MIN_WINDOW_WIDTH); + this.screenHeight = Math.max(startup.height(), MIN_WINDOW_HEIGHT); + this.restoreWidth = this.screenWidth; + this.restoreHeight = this.screenHeight; + WindowSpec spec = new WindowSpec(windowTitle, this.screenWidth, this.screenHeight, sizeLimit); + this.platformWindow = ClientPlatform.get().createWindow(spec, gpuBackend::createWindow); + ClientPlatform.windowCreated(this.platformWindow); + MacosUtil.disableCloseWindowMenuItem(); + + // Start centred on the primary display; where the platform can't say, keep where it put us. + Monitor primary = monitors.getMonitor(ClientPlatform.get().displays().primaryId()); + this.screenX = primary == null ? this.platformWindow.x() : primary.x() + (primary.w() - this.screenWidth) / 2; + this.screenY = primary == null ? this.platformWindow.y() : primary.y() + (primary.h() - this.screenHeight) / 2; + this.restoreX = this.screenX; + this.restoreY = this.screenY; + + this.applyRequestedMode(); + this.refreshFramebufferSize(); + } + + private static Optional initialFullscreenMode( + final @Nullable String fromOptions, final DisplayData startup) { + Optional saved = VideoMode.read(fromOptions); + if (saved.isPresent()) { + return saved; + } + if (startup.fullscreenWidth().isPresent() && startup.fullscreenHeight().isPresent()) { + // Sizes from the command line: assume the everyday 24-bit, 60 Hz mode. + return Optional.of(new VideoMode( + startup.fullscreenWidth().getAsInt(), + startup.fullscreenHeight().getAsInt(), + 8, + 8, + 8, + 60)); + } + return Optional.empty(); + } + + /** The platform's name for crash reports, for example "SDL on Linux (wayland)". */ + public static String getPlatform() { + return ClientPlatform.get().description(); + } + + /** The platform window behind this one, for Incari code that needs more than the game uses. */ + public PlatformWindow platformWindow() { + return this.platformWindow; + } + + public @Nullable VideoMode getActiveVideoMode() { + RenderSystem.assertOnRenderThread(); + DisplayMode mode = this.platformWindow.currentDisplayMode(); + return mode == null ? null : DisplayModes.toVideoMode(mode); + } + + public boolean shouldClose() { + return this.shouldClose; + } + + // --- Events from the platform, delivered by SDLEventHandler on the render thread --- + + void onCloseRequested() { + // The system's quit shortcut (Alt+F4, Command+Q) closes the game only when the player + // hasn't bound it to something else. + if (this.quitShortcuts || !InputQuirks.isQuitShortcutDown()) { + this.requestClose(); + } + } + + void onTerminating() { + this.requestClose(); + } + + void onDisplayAdded(final int displayId) { + this.monitorManager.onDisplayConnected(displayId); + } + + void onDisplayRemoved(final int displayId) { + this.monitorManager.onDisplayDisconnected(displayId); + } + + void onDisplayModeChanged(final int displayId) { + this.monitorManager.onDisplayModeChanged(displayId); + this.refreshFramebufferSize(); + this.eventHandler.framebufferSizeChanged(); + } + + void onDisplayChanged() { + this.eventHandler.framebufferSizeChanged(); + } + + void onMoved(final int newX, final int newY) { + this.screenX = newX; + this.screenY = newY; + if (!this.platformWindow.isFullscreen()) { + this.restoreX = newX; + this.restoreY = newY; + } + } + + void onResized(final int newWidth, final int newHeight) { + this.screenWidth = newWidth; + this.screenHeight = newHeight; + if (!this.platformWindow.isFullscreen()) { + this.restoreWidth = Math.max(newWidth, MIN_WINDOW_WIDTH); + this.restoreHeight = Math.max(newHeight, MIN_WINDOW_HEIGHT); + } + // Keep the pointer lock centred in the new size. + if (Minecraft.getInstance().mouseHandler.isMouseGrabbed()) { + InputConstants.grabMouse(this, this.getScreenWidth() / 2.0, this.getScreenHeight() / 2.0); + } + } + + void onFramebufferResized(final int pixelWidth, final int pixelHeight) { + if (pixelWidth <= 0 || pixelHeight <= 0) { + return; + } + int previousWidth = this.pixelWidth; + int previousHeight = this.pixelHeight; + this.pixelWidth = pixelWidth - this.platformWindow.unusedWidth(); + this.pixelHeight = pixelHeight; + try { + this.eventHandler.framebufferSizeChanged(); + } catch (Exception e) { + CrashReport report = CrashReport.forThrowable(e, "Window resize"); + CrashReportCategory sizes = report.addCategory("Window Dimensions"); + sizes.setDetail("Old", previousWidth + "x" + previousHeight); + sizes.setDetail("New", pixelWidth + "x" + pixelHeight); + throw new ReportedException(report); + } + } + + void onMinimized(final boolean minimized) { + this.minimized = minimized; + Minecraft.getInstance().invalidateSurfaceConfiguration(); + } + + void onFocusChanged(final boolean hasFocus) { + this.hasFocus = hasFocus; + } + + void onCursorEnteredOrLeft() { + this.eventHandler.cursorEntered(); + } + + void onFullscreenChanged() { + this.syncFullscreenState(); + } + + private void syncFullscreenState() { + boolean nowFullscreen = this.platformWindow.isFullscreen(); + if (nowFullscreen != this.fullscreen) { + this.fullscreen = nowFullscreen; + this.eventHandler.fullscreenStateChanged(nowFullscreen); + } + } + + private void requestClose() { + this.shouldClose = true; + if (this.closeCallback != null) { + this.closeCallback.run(); + } + } + + // --- Icon --- + + /** Incari's icon in each size the window can pick from (tools/icon), in the Incari pack. */ + private static final int[] ICON_SIZES = {16, 32, 48, 128, 256}; + + /** + * Shows Incari's icon, not the game's: {@code resources} and {@code iconSet} name the game's, + * and are left unread. + */ + public void setIcon(final PackMetadataResources resources, final IconSet iconSet) throws IOException { + List sizes = new ArrayList<>(ICON_SIZES.length); + for (int size : ICON_SIZES) { + String path = "/incari-pack/assets/incari/textures/gui/icon_" + size + ".png"; + try (InputStream in = Window.class.getResourceAsStream(path)) { + if (in == null) { + throw new IOException("Incari's pack has no " + path); + } + try (NativeImage image = NativeImage.read(in)) { + sizes.add(new IconImage(image.getWidth(), image.getHeight(), rgbaBytes(image))); + } + } + } + this.platformWindow.setIcon(sizes); + } + + /** The image's pixels as R, G, B, A bytes, row by row. */ + private static byte[] rgbaBytes(final NativeImage image) { + int width = image.getWidth(); + int height = image.getHeight(); + byte[] rgba = new byte[width * height * 4]; + int at = 0; + for (int row = 0; row < height; row++) { + for (int column = 0; column < width; column++) { + // NativeImage.getPixel is ARGB. + int argb = image.getPixel(column, row); + rgba[at++] = (byte) (argb >> 16); + rgba[at++] = (byte) (argb >> 8); + rgba[at++] = (byte) argb; + rgba[at++] = (byte) (argb >>> 24); + } + } + return rgba; + } + + // --- Crash reporting --- + + public String getErrorSection() { + return this.errorSection; + } + + public void setErrorSection(final String section) { + this.errorSection = section; + } + + @Override + public void close() { + RenderSystem.assertOnRenderThread(); + ClientPlatform.windowClosed(); + this.platformWindow.close(); + } + + // --- Size and mode --- + + private void refreshFramebufferSize() { + FramebufferSize size = this.queryFramebufferSize(); + this.pixelWidth = size.width() - this.platformWindow.unusedWidth(); + this.pixelHeight = size.height(); + } + + /** The whole drawable surface in pixels, which is what the graphics surface is sized to. */ + public FramebufferSize queryFramebufferSize() { + return new FramebufferSize( + Math.max(this.platformWindow.framebufferWidth(), 1), + Math.max(this.platformWindow.framebufferHeight(), 1)); + } + + public void updateFullscreenIfChanged() { + RenderSystem.assertOnRenderThread(); + if (this.fullscreenRequested != this.fullscreen) { + this.applyRequestedMode(); + this.eventHandler.framebufferSizeChanged(); + } + } + + public Optional getPreferredFullscreenVideoMode() { + return this.preferredFullscreenVideoMode; + } + + public void setPreferredFullscreenVideoMode(final Optional mode) { + if (!mode.equals(this.preferredFullscreenVideoMode)) { + this.preferredFullscreenVideoMode = mode; + this.fullscreenModeDirty = true; + } + } + + public void changeFullscreenVideoMode() { + RenderSystem.assertOnRenderThread(); + if (this.fullscreenRequested && this.fullscreenModeDirty) { + this.fullscreenModeDirty = false; + this.applyRequestedMode(); + this.eventHandler.framebufferSizeChanged(); + } + } + + /** Puts the window into the mode the game asked for: windowed, borderless or exclusive. */ + private void applyRequestedMode() { + RenderSystem.assertOnRenderThread(); + if (this.fullscreenRequested && !this.fullscreen) { + // Remember the windowed placement to come back to. + this.restoreX = this.screenX; + this.restoreY = this.screenY; + this.restoreWidth = Math.max(this.screenWidth, MIN_WINDOW_WIDTH); + this.restoreHeight = Math.max(this.screenHeight, MIN_WINDOW_HEIGHT); + } + + boolean applied; + if (this.fullscreenRequested) { + applied = this.platformWindow.setFullscreen(this.exclusiveFullscreen ? this.exclusiveTarget() : null); + } else { + int windowWidth = Math.max(this.restoreWidth, MIN_WINDOW_WIDTH); + int windowHeight = Math.max(this.restoreHeight, MIN_WINDOW_HEIGHT); + applied = this.platformWindow.setWindowed(this.restoreX, this.restoreY, windowWidth, windowHeight); + if (applied) { + this.screenX = this.restoreX; + this.screenY = this.restoreY; + this.screenWidth = windowWidth; + this.screenHeight = windowHeight; + } + } + + if (!applied) { + LOGGER.error("Couldn't {} fullscreen", this.fullscreenRequested ? "enter" : "leave"); + this.fullscreenRequested = this.fullscreen; + this.eventHandler.fullscreenStateChanged(this.fullscreen); + return; + } + if (this.fullscreenRequested) { + this.screenX = this.platformWindow.x(); + this.screenY = this.platformWindow.y(); + this.screenWidth = this.platformWindow.width(); + this.screenHeight = this.platformWindow.height(); + } + this.syncFullscreenState(); + this.refreshFramebufferSize(); + if (this.exclusiveFullscreen && this.fullscreen && !this.platformWindow.isExclusiveFullscreen()) { + LOGGER.info("Exclusive fullscreen request resolved to borderless desktop"); + } + } + + /** The display mode exclusive fullscreen asks for: the player's choice if this monitor has it. */ + private @Nullable DisplayMode exclusiveTarget() { + Monitor monitor = this.monitorManager.findBestMonitor(this); + if (monitor == null) { + LOGGER.warn( + "Failed to find suitable monitor for exclusive fullscreen, falling back to borderless fullscreen"); + return null; + } + VideoMode mode = monitor.getPreferredVideoMode(this.preferredFullscreenVideoMode); + LOGGER.info("Exclusive target {} on monitor {}", mode, monitor); + return DisplayModes.toPlatform(mode); + } + + public boolean isExclusiveFullscreen() { + return this.platformWindow.isExclusiveFullscreen(); + } + + public void setExclusiveFullscreen(final boolean exclusive) { + if (this.exclusiveFullscreen != exclusive) { + this.exclusiveFullscreen = exclusive; + if (this.fullscreenRequested) { + this.applyRequestedMode(); + this.eventHandler.framebufferSizeChanged(); + } + } + } + + public void setWindowed(final int windowWidth, final int windowHeight) { + this.restoreWidth = Math.max(windowWidth, MIN_WINDOW_WIDTH); + this.restoreHeight = Math.max(windowHeight, MIN_WINDOW_HEIGHT); + this.fullscreenRequested = false; + this.applyRequestedMode(); + } + + /** + * The largest GUI scale up to {@code maxScale} (0 for no limit) at which the GUI's base size + * still fits the framebuffer; with {@code enforceUnicode}, rounded up to even so the Unicode + * font's half-pixel glyphs land on whole pixels. + */ + public int calculateScale(final int maxScale, final boolean enforceUnicode) { + int fitsWidth = Math.max(1, this.pixelWidth / BASE_WIDTH); + int fitsHeight = Math.max(1, this.pixelHeight / BASE_HEIGHT); + int scale = Math.min(fitsWidth, fitsHeight); + if (maxScale > 0) { + scale = Math.min(scale, maxScale); + } + if (enforceUnicode && scale % 2 != 0) { + scale++; + } + return scale; + } + + public void setTitle(final String title) { + this.platformWindow.setTitle(title); + } + + public void setWindowMaxSize(final int maxWidth, final int maxHeight) { + this.platformWindow.setMaximumSize(maxWidth, maxHeight); + } + + /** The id input events carry, so handlers can tell this window's events apart. */ + public long handle() { + return this.platformWindow.nativeHandle(); + } + + // Framebuffer, in pixels: what rendering uses. + + public int getWidth() { + return this.pixelWidth; + } + + public int getHeight() { + return this.pixelHeight; + } + + public void setWidth(final int pixels) { + this.pixelWidth = pixels; + } + + public void setHeight(final int pixels) { + this.pixelHeight = pixels; + } + + // The window on the desktop, in screen coordinates. + + public int getX() { + return this.screenX; + } + + public int getY() { + return this.screenY; + } + + public int getScreenWidth() { + return this.screenWidth; + } + + public int getScreenHeight() { + return this.screenHeight; + } + + // The GUI: pixels divided by the GUI scale. + + public int getGuiScale() { + return this.scaleFactor; + } + + public int getGuiScaledWidth() { + return this.scaledWidth; + } + + public int getGuiScaledHeight() { + return this.scaledHeight; + } + + public void setGuiScale(final int scale) { + this.scaleFactor = scale; + // Round up so the GUI always covers the whole framebuffer. + this.scaledWidth = (this.pixelWidth + scale - 1) / scale; + this.scaledHeight = (this.pixelHeight + scale - 1) / scale; + } + + // State. + + public boolean isIconified() { + return this.minimized; + } + + public boolean isFocused() { + return this.hasFocus; + } + + public void setFullscreen(final boolean wanted) { + this.fullscreenRequested = wanted; + } + + public float getPixelDensity() { + return this.platformWindow.pixelDensity(); + } + + public @Nullable Monitor findBestMonitor() { + return this.monitorManager.findBestMonitor(this); + } + + public void setWindowCloseCallback(final Runnable task) { + this.closeCallback = task; + } + + public void setAllowCursorChanges(final boolean allow) { + this.allowCursorChanges = allow; + } + + public void setQuitShortcuts(final boolean enabled) { + this.quitShortcuts = enabled; + this.platformWindow.setQuitShortcutEnabled(enabled); + } + + public void selectCursor(final CursorType cursor) { + CursorType wanted = this.allowCursorChanges ? cursor : CursorType.DEFAULT; + if (!wanted.equals(this.currentCursor)) { + this.currentCursor = wanted; + wanted.select(); + } + } + + /** Outline width for debug shapes: 2.5 at 1080p and below, scaling up with the framebuffer. */ + public float getAppropriateLineWidth() { + return Math.max(2.5F, this.getWidth() / 1920.0F * 2.5F); + } + + public record FramebufferSize(int width, int height) {} + + public static class WindowInitFailed extends SilentInitException { + private static final long serialVersionUID = 1L; + + public WindowInitFailed(final String message) { + super(message); + } + } +} diff --git a/incari-client/files/client/src/main/java/com/mojang/blaze3d/platform/cursor/CursorType.java b/incari-client/files/client/src/main/java/com/mojang/blaze3d/platform/cursor/CursorType.java new file mode 100644 index 0000000..942f2e6 --- /dev/null +++ b/incari-client/files/client/src/main/java/com/mojang/blaze3d/platform/cursor/CursorType.java @@ -0,0 +1,55 @@ +package com.mojang.blaze3d.platform.cursor; + +import incari.client.platform.ClientPlatform; +import incari.platform.api.window.PlatformWindow; +import incari.platform.api.window.SystemCursor; + +/** + * Incari's replacement for Mojang's cursor type (patches/classes.txt). A cursor is one of the + * platform's standard shapes; the platform creates the native cursor when it's first shown. + */ +public class CursorType { + + public static final CursorType DEFAULT = new CursorType("default", SystemCursor.DEFAULT); + + private final String name; + private final SystemCursor cursor; + + private CursorType(final String name, final SystemCursor cursor) { + this.name = name; + this.cursor = cursor; + } + + public void select() { + PlatformWindow window = ClientPlatform.window(); + if (window != null) { + window.setCursor(this.cursor); + } + } + + @Override + public String toString() { + return this.name; + } + + /** + * Makes a cursor from one of the standard shapes {@code CursorTypes} names by SDL's + * {@code SDL_SystemCursor} number; a shape the platform can't show falls back to + * {@code fallback}. + */ + public static CursorType createStandardCursor(final int shape, final String name, final CursorType fallback) { + SystemCursor cursor = + switch (shape) { + case 0 -> SystemCursor.ARROW; + case 1 -> SystemCursor.TEXT; + case 3 -> SystemCursor.CROSSHAIR; + case 7 -> SystemCursor.RESIZE_EW; + case 8 -> SystemCursor.RESIZE_NS; + case 9 -> SystemCursor.RESIZE_ALL; + case 10 -> SystemCursor.NOT_ALLOWED; + case 11 -> SystemCursor.POINTING_HAND; + default -> null; + }; + return cursor == null ? fallback : new CursorType(name, cursor); + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/IncariKeys.java b/incari-client/files/client/src/main/java/incari/client/IncariKeys.java new file mode 100644 index 0000000..3ea8902 --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/IncariKeys.java @@ -0,0 +1,51 @@ +package incari.client; + +import net.minecraft.client.KeyMapping; + +/** + * Incari's key mappings, added to the game's list by one hook in {@code Options} so they show in + * the controls screen and are saved with the rest. + * + *

The names are shown as they are: the game translates a key mapping's name, and Incari has no + * language files yet, so an English name is its own fallback. A name is also the key's line in + * {@code options.txt} ({@code key_:}), which the game splits at the first colon, so a + * name must have none: with one, the bind was read back as an unknown option on every start and + * went back to its default. + */ +public final class IncariKeys { + + /** Voice chat: held to talk. B, as in Eagler's clients. */ + public static final KeyMapping PUSH_TO_TALK = + new KeyMapping("Voice - Push to Talk", 5, KeyMapping.Category.MULTIPLAYER); + + /** + * The profiler overlay, on and off. F9: the game leaves it free, and browsers don't take + * it for themselves. + */ + public static final KeyMapping PROFILER_OVERLAY = new KeyMapping("Profiler Overlay", 66, KeyMapping.Category.DEBUG); + + /** + * The module menu. Right Shift, as in other clients; the game leaves it free. Modules' own + * binds aren't here: they're in each module's settings and its profile ({@code GameKeys}). + */ + public static final KeyMapping MODULE_MENU = new KeyMapping("Incari - Modules", 229, KeyMapping.Category.MISC); + + /** + * The emote wheel (ADR 0061), held open. G: the game leaves it free, and B is push to talk's. + */ + public static final KeyMapping EMOTE_WHEEL = new KeyMapping("Incari - Emote Wheel", 10, KeyMapping.Category.MISC); + + /** + * The screen recorder, on and off (ADR 0062; the browser only). F8: the game leaves it free, and + * Chrome takes F6 and F7 for itself. + */ + public static final KeyMapping RECORD_SCREEN = + new KeyMapping("Incari - Record Screen", 65, KeyMapping.Category.MISC); + + /** Every Incari key mapping, as a new array for the game's list. */ + public static KeyMapping[] all() { + return new KeyMapping[] {PUSH_TO_TALK, PROFILER_OVERLAY, MODULE_MENU, EMOTE_WHEEL, RECORD_SCREEN}; + } + + private IncariKeys() {} +} diff --git a/incari-client/files/client/src/main/java/incari/client/IncariTicks.java b/incari-client/files/client/src/main/java/incari/client/IncariTicks.java new file mode 100644 index 0000000..befcbf2 --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/IncariTicks.java @@ -0,0 +1,46 @@ +package incari.client; + +import incari.client.cosmetics.Cosmetics; +import incari.client.eagler.EaglerVoice; +import incari.client.legacy.LegacyRules; +import incari.client.look.Looks; +import incari.client.modules.IncariModules; +import incari.client.net.ServerConnections; +import incari.client.online.IncariOnline; +import incari.client.profiler.Profiling; +import incari.client.recorder.ScreenRecorder; +import incari.client.render.mesher.ChestBaking; +import incari.client.singleplayer.QuickWorlds; +import net.minecraft.client.Minecraft; + +/** + * What Incari does once a client tick, from one hook in {@code Minecraft.tick} (after the GUI's + * tick, before key bindings): the legacy behaviour layer follows the server's version, voice + * chat runs, the profiler overlay's key is read, the benchmark's quick worlds are made and left, and + * the Incari account's connection runs, and the modules tick (their keybinds, then their listeners). The first tick also puts on the client's + * look. Game thread. + */ +public final class IncariTicks { + + private IncariTicks() {} + + public static void tick(Minecraft minecraft) { + Looks.start(minecraft); + // A join that reached a world: a kick from here on isn't a refusal of its version. + ServerConnections.tick(minecraft); + // First: the rest of the tick moves the player by the rules of the server it's on. + LegacyRules.update(minecraft); + // Push to talk works with no screen open, as other keys do, and while chat is closed. + boolean pushToTalk = minecraft.gui.screen() == null && IncariKeys.PUSH_TO_TALK.isDown(); + EaglerVoice.tick(minecraft, pushToTalk); + Profiling.tick(); + ScreenRecorder.tick(minecraft); + ChestBaking.tick(minecraft.level); + QuickWorlds.tick(minecraft); + // Before the modules: they read who's an Incari player (ADR 0058). + IncariOnline.tick(minecraft); + // Cosmetics read the service's emotes and what Incari players wear (ADR 0061). + Cosmetics.tick(minecraft); + IncariModules.tick(minecraft); + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/TickPacing.java b/incari-client/files/client/src/main/java/incari/client/TickPacing.java new file mode 100644 index 0000000..370ee81 --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/TickPacing.java @@ -0,0 +1,69 @@ +package incari.client; + +/** + * Catch-up ticks spread over frames (ADR 0032). After a slow frame the game runs every tick it + * missed back to back, up to ten, in the next frame, which makes that frame slow as well: on the + * floor stand-in the slowest 1% of frames were mostly these runs. Here the ticks due are owed + * instead, and each frame runs as many as the frame rate needs on average, rounded up, so the debt + * drains a tick a frame over the next few frames. The game still runs every tick it would have (up to + * the ten it would run at once; it drops the rest, and so does this), a few frames later. + * + *

While the debt drains the game runs a little behind the clock: entities move a tick a frame + * until it's paid. A debt of more than two frames' worth runs one tick more a frame. The debt never + * exceeds the ten ticks the game would run at once, so after a long stall no more ticks run than the + * game would run (an earlier version kept a second's worth, and after the stalls of a busy fight + * ran twice the game's ticks, each a heavy one); bursts that come back to back can then drop a few + * ticks the game would have run. Off unless the page turns it on ({@code ?ticks=game} leaves it off, to compare); the + * desktop runs the game's way. Game thread. + */ +public final class TickPacing { + + /** The most ticks the game runs in one frame; it drops any more. */ + private static final int GAME_LIMIT = 10; + + /** The weight of each frame in the average of ticks due a frame. */ + private static final float SMOOTHING = 1.0F / 16.0F; + + private static boolean enabled; + + private static int debt; + + // Ticks due a frame, averaged: one at 20 fps, a third at 60. + private static float average = 1.0F; + + private TickPacing() {} + + public static void setEnabled(boolean on) { + enabled = on; + debt = 0; + average = 1.0F; + } + + /** + * Hook ({@code Minecraft.runTick}, after the ticks due are worked out): how many of the ticks due + * to run this frame. {@code advancing} is whether game time moves at all; while it doesn't, the + * debt waits. + */ + public static int ticksToRun(int due, boolean advancing) { + if (!enabled) { + return due; + } + if (!advancing) { + return 0; + } + average += (due - average) * SMOOTHING; + debt = Math.min(GAME_LIMIT, debt + Math.min(GAME_LIMIT, due)); + int limit = Math.max(1, (int) Math.ceil(average)); + if (debt > 2 * limit) { + limit++; + } + int run = Math.min(debt, limit); + debt -= run; + return run; + } + + /** The ticks owed to later frames. */ + public static int debt() { + return debt; + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/account/MicrosoftAccounts.java b/incari-client/files/client/src/main/java/incari/client/account/MicrosoftAccounts.java new file mode 100644 index 0000000..f5771ba --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/account/MicrosoftAccounts.java @@ -0,0 +1,204 @@ +package incari.client.account; + +import com.mojang.logging.LogUtils; +import incari.client.net.WispServers; +import incari.client.platform.ClientPlatform; +import incari.net.https.HttpsClient; +import incari.net.msa.MicrosoftAccount; +import incari.net.msa.MicrosoftEndpoints; +import incari.net.msa.MicrosoftSignIn; +import incari.net.tls.Transport; +import incari.platform.api.net.PlatformNetwork; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.AtomicMoveNotSupportedException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.attribute.PosixFilePermission; +import java.util.EnumSet; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import net.minecraft.client.User; +import org.jspecify.annotations.Nullable; +import org.slf4j.Logger; + +/** + * The Microsoft account the player signed in with (ADR 0070), if any: kept in + * {@code incari/microsoft-account.json} in the game directory (the browser's own storage for the + * page), and answered as the player wherever the game asks ({@code PlayerName.user}). + * + *

The file holds the Minecraft token and Microsoft's refresh token, so it never leaves this + * device: nothing logs it, and signing out deletes it. Sign-in's requests go straight to the hosts + * on the desktop and through the player's Wisp proxy in a browser, end-to-end encrypted either way. + */ +public final class MicrosoftAccounts { + + private static final Logger LOGGER = LogUtils.getLogger(); + private static final String FILE = "microsoft-account.json"; + + // Set once, on the first question. + private static @Nullable Path file; + private static volatile @Nullable MicrosoftAccount account; + private static volatile @Nullable User user; + /** The account's chat keys, made when it's first asked for. */ + private static volatile @Nullable MicrosoftProfileKeys keys; + + private MicrosoftAccounts() {} + + /** Reads the saved account, once, from {@code gameDirectory}. */ + public static synchronized void load(Path gameDirectory) { + if (file != null) { + return; + } + Path saved = gameDirectory.resolve("incari").resolve(FILE); + file = saved; + if (!Files.isRegularFile(saved)) { + return; + } + try { + MicrosoftAccount read = MicrosoftAccount.fromJson(Files.readString(saved, StandardCharsets.UTF_8)); + if (read == null) { + LOGGER.warn("Ignoring {}: it isn't a saved account", saved); + return; + } + use(read); + LOGGER.info("Playing as Microsoft account {}", read.name()); + } catch (IOException e) { + LOGGER.warn("Couldn't read {}: {}", saved, e.toString()); + } + } + + /** The signed-in account, or null. */ + public static @Nullable MicrosoftAccount account() { + return account; + } + + /** The player as the game knows them while signed in, or null when not. */ + public static @Nullable User user() { + return user; + } + + /** Signs in as {@code signedIn} and keeps it for the next start. */ + public static synchronized void signedIn(MicrosoftAccount signedIn) { + MicrosoftAccount previous = account; + use(signedIn); + if (previous == null || !previous.id().equals(signedIn.id())) { + keys = null; + } + save(signedIn); + } + + /** Signs out and deletes the saved tokens. */ + public static synchronized void signOut() { + account = null; + user = null; + keys = null; + Path target = file; + if (target != null) { + try { + Files.deleteIfExists(target); + } catch (IOException e) { + LOGGER.warn("Couldn't delete {}: {}", target, e.toString()); + } + } + } + + /** + * The account with a Minecraft token good for a while yet, renewed through Microsoft if it was + * about to expire (and saved). Fails if there's no account or the renewal was refused. + */ + public static CompletableFuture fresh() { + MicrosoftAccount current = account; + if (current == null) { + return CompletableFuture.failedFuture(new IOException("Not signed in")); + } + return signIn().renew(current).thenApply(renewed -> { + if (!renewed.equals(current)) { + synchronized (MicrosoftAccounts.class) { + // Only if nobody signed out or in meanwhile. + if (current.equals(account)) { + signedIn(renewed); + } + } + } + return renewed; + }); + } + + /** A sign-in client over this platform's route: a socket, or the Wisp proxy in a browser. */ + public static MicrosoftSignIn signIn() { + PlatformNetwork network = ClientPlatform.get().network(); + Transport transport = network.canOpenSockets() + ? Transport.direct(network) + : Transport.wisp(network, WispServers.signInProxy()); + return new MicrosoftSignIn(HttpsClient.pinned(transport, MicrosoftEndpoints.HOSTS), System::currentTimeMillis); + } + + /** How sign-in reaches Microsoft, for the screen: "directly", or the proxy's address. */ + public static String route() { + return ClientPlatform.get().network().canOpenSockets() ? "directly" : "through " + WispServers.signInProxy(); + } + + /** The chat keys for the signed-in account, or null when signed out. */ + static @Nullable MicrosoftProfileKeys keys() { + MicrosoftAccount current = account; + if (current == null) { + return null; + } + MicrosoftProfileKeys made = keys; + if (made == null || !made.isFor(current)) { + made = new MicrosoftProfileKeys(current.id()); + keys = made; + } + return made; + } + + private static void use(MicrosoftAccount signedIn) { + account = signedIn; + user = new User( + signedIn.name(), + UUID.fromString(signedIn.dashedId()), + signedIn.minecraftToken(), + Optional.empty(), + Optional.empty()); + } + + private static void save(MicrosoftAccount signedIn) { + Path target = file; + if (target == null) { + return; + } + // Owner-only (it's a refresh token: on a shared machine, others could take the account + // with it), and written beside then moved over, so a crash never leaves half a file. + Path temporary = target.resolveSibling(FILE + ".tmp"); + try { + Files.createDirectories(target.getParent()); + Files.deleteIfExists(temporary); + Files.createFile(temporary); + try { + Files.setPosixFilePermissions( + temporary, EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE)); + } catch (UnsupportedOperationException e) { + // Windows: the user's profile folder is already private. + } + Files.writeString(temporary, signedIn.toJson(), StandardCharsets.UTF_8); + try { + Files.move(temporary, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + } catch (AtomicMoveNotSupportedException e) { + Files.move(temporary, target, StandardCopyOption.REPLACE_EXISTING); + } + } catch (IOException e) { + LOGGER.warn("Couldn't save the Microsoft account: {}", e.toString()); + } + } + + /** Forgets everything, as a new start would. Tests only. */ + public static synchronized void reset() { + file = null; + account = null; + user = null; + keys = null; + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/account/MicrosoftProfileKeys.java b/incari-client/files/client/src/main/java/incari/client/account/MicrosoftProfileKeys.java new file mode 100644 index 0000000..0a0b771 --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/account/MicrosoftProfileKeys.java @@ -0,0 +1,96 @@ +package incari.client.account; + +import com.mojang.logging.LogUtils; +import incari.net.msa.MicrosoftAccount; +import incari.net.msa.ProfileCertificates; +import java.time.Duration; +import java.time.Instant; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import net.minecraft.client.multiplayer.ProfileKeyPairManager; +import net.minecraft.util.Crypt; +import net.minecraft.util.CryptException; +import net.minecraft.world.entity.player.ProfileKeyPair; +import net.minecraft.world.entity.player.ProfilePublicKey; +import org.slf4j.Logger; + +/** + * The signed-in account's chat-signing keys, as the game asks for them (ADR 0070): fetched from + * Mojang through Incari's sign-in client, kept in memory only, and fetched again once Mojang says + * they're due. Servers that enforce secure chat refuse players without them. + * + *

The game polls the future from the render thread only once it's done, so it never waits. + */ +public final class MicrosoftProfileKeys implements ProfileKeyPairManager { + + private static final Logger LOGGER = LogUtils.getLogger(); + /** At most one fetch an hour, as the game's own manager, whatever happens. */ + private static final Duration MINIMUM_REFRESH = Duration.ofHours(1); + + private final String accountId; + private CompletableFuture> keyPair = CompletableFuture.completedFuture(Optional.empty()); + private Instant nextFetch = Instant.EPOCH; + + MicrosoftProfileKeys(String accountId) { + this.accountId = accountId; + } + + /** Hook ({@code Minecraft.getProfileKeyPairManager}): these keys while signed in, else the game's. */ + public static ProfileKeyPairManager manager(ProfileKeyPairManager vanilla) { + MicrosoftProfileKeys keys = MicrosoftAccounts.keys(); + return keys != null ? keys : vanilla; + } + + boolean isFor(MicrosoftAccount account) { + return accountId.equals(account.id()); + } + + @Override + public synchronized CompletableFuture> prepareKeyPair() { + Optional current = keyPair.getNow(Optional.empty()); + boolean fetching = !keyPair.isDone(); + if (fetching || (current.isPresent() && !current.get().dueRefresh())) { + return keyPair; + } + nextFetch = Instant.now().plus(MINIMUM_REFRESH); + keyPair = MicrosoftAccounts.fresh() + .thenCompose(account -> MicrosoftAccounts.signIn().certificates(account)) + .thenApply(MicrosoftProfileKeys::keyPair) + .exceptionally(failure -> { + LOGGER.warn("Couldn't get the chat key: {}", reason(failure)); + return current; + }); + return keyPair; + } + + @Override + public synchronized boolean shouldRefreshKeyPair() { + if (!keyPair.isDone() || Instant.now().isBefore(nextFetch)) { + return false; + } + return keyPair.getNow(Optional.empty()).map(ProfileKeyPair::dueRefresh).orElse(true); + } + + private static Optional keyPair(ProfileCertificates certificates) { + try { + ProfilePublicKey.Data publicKey = new ProfilePublicKey.Data( + Instant.parse(certificates.expiresAt()), + Crypt.stringToRsaPublicKey(certificates.publicKeyPem()), + certificates.publicKeySignature()); + return Optional.of(new ProfileKeyPair( + Crypt.stringToPemRsaPrivateKey(certificates.privateKeyPem()), + new ProfilePublicKey(publicKey), + Instant.parse(certificates.refreshedAfter()))); + } catch (CryptException | RuntimeException e) { + // Never the key itself in the message: just what kind of failure. + throw new IllegalStateException( + "Mojang's chat key can't be read (" + e.getClass().getSimpleName() + ")"); + } + } + + private static String reason(Throwable failure) { + Throwable cause = failure.getCause() != null ? failure.getCause() : failure; + String message = cause.getMessage(); + return message != null ? message : cause.getClass().getSimpleName(); + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/account/MicrosoftScreen.java b/incari-client/files/client/src/main/java/incari/client/account/MicrosoftScreen.java new file mode 100644 index 0000000..8ddc739 --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/account/MicrosoftScreen.java @@ -0,0 +1,325 @@ +package incari.client.account; + +import incari.client.ui.Theme; +import incari.net.msa.DeviceCode; +import incari.net.msa.MicrosoftAccount; +import incari.net.msa.MicrosoftSignIn; +import incari.net.msa.SignInException; +import java.net.URI; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.function.Consumer; +import net.minecraft.ChatFormatting; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.components.MultiLineTextWidget; +import net.minecraft.client.gui.components.StringWidget; +import net.minecraft.client.gui.layouts.HeaderAndFooterLayout; +import net.minecraft.client.gui.layouts.LinearLayout; +import net.minecraft.client.gui.screens.ConfirmLinkScreen; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.CommonComponents; +import net.minecraft.network.chat.Component; +import org.jspecify.annotations.Nullable; + +/** + * Microsoft sign-in (ADR 0070), opened from Edit Profile: the device-code flow, so the password is + * typed on Microsoft's own page, on any device, never into the game. Shows the code, waits for the + * player to enter it, then signs in to Minecraft; or shows who's signed in, with Sign Out. + * + *

English only for now; Incari's screens don't have language files yet. + */ +public final class MicrosoftScreen extends Screen { + + private static final int TEXT_WIDTH = 300; + private static final int BUTTON_WIDTH = 150; + + private enum State { + IDLE, + REQUESTING, + CODE, + SIGNING_IN + } + + private final Screen parent; + /** Made again on each init: the screen rebuilds itself as the sign-in moves on. */ + private HeaderAndFooterLayout layout = new HeaderAndFooterLayout(this); + + private State state = State.IDLE; + private Component message = CommonComponents.EMPTY; + private @Nullable DeviceCode code; + private @Nullable MicrosoftSignIn signIn; + /** Bumped when a sign-in is started or abandoned, so a late answer for an old one is dropped. */ + private int attempt; + + private boolean polling; + private long nextPollMillis; + private int intervalSeconds; + /** Polls in a row that didn't get through: retried, further apart, until {@link #MAX_POLL_FAILURES}. */ + private int pollFailures; + + /** Polls in a row that may fail to get through before the sign-in gives up: minutes of trying. */ + private static final int MAX_POLL_FAILURES = 8; + /** The longest wait between polls that didn't get through. */ + private static final long MAX_RETRY_MILLIS = 30_000; + + public MicrosoftScreen(Screen parent) { + super(Component.literal("Microsoft Account")); + this.parent = parent; + } + + @Override + protected void init() { + layout = new HeaderAndFooterLayout(this); + layout.addTitleHeader(this.title, this.font); + LinearLayout contents = layout.addToContents(LinearLayout.vertical().spacing(Theme.GAP)); + contents.defaultCellSetting().alignHorizontallyCenter(); + LinearLayout footer = layout.addToFooter(LinearLayout.horizontal().spacing(8)); + MicrosoftAccount account = MicrosoftAccounts.account(); + boolean inWorld = this.minecraft.level != null; + + switch (state) { + case IDLE -> { + if (account != null) { + contents.addChild(text(Component.literal("Signed in as ") + .append(Component.literal(account.name()).withStyle(ChatFormatting.YELLOW)))); + contents.addChild( + text( + Component.literal( + "Servers that check accounts see you as this player. Your password never passes through Incari."))); + Button signOut = footer.addChild(Button.builder(Component.literal("Sign Out"), button -> signOut()) + .build()); + signOut.active = !inWorld; + } else { + contents.addChild(text(Component.literal( + "Sign in to join servers that check Minecraft accounts (online mode). You sign in on" + + " Microsoft's own page, on this or any other device."))); + contents.addChild(text( + Component.literal("Sign-in goes " + MicrosoftAccounts.route() + ", encrypted end to end.") + .withStyle(ChatFormatting.GRAY))); + Button start = footer.addChild(Button.builder(Component.literal("Sign In"), button -> start()) + .build()); + start.active = !inWorld; + } + if (inWorld) { + contents.addChild(text(Component.literal("Leave the world to change accounts.") + .withStyle(ChatFormatting.GRAY))); + } + footer.addChild(Button.builder(CommonComponents.GUI_DONE, button -> onClose()) + .build()); + } + case REQUESTING -> { + contents.addChild(text(Component.literal("Asking Microsoft for a sign-in code..."))); + footer.addChild(Button.builder(CommonComponents.GUI_CANCEL, button -> cancel()) + .build()); + } + case CODE -> { + DeviceCode current = code; + if (current != null) { + contents.addChild( + text(Component.literal("On any device, open microsoft.com/link and enter this code:"))); + contents.addChild(new StringWidget( + Component.literal(current.userCode()).withStyle(ChatFormatting.YELLOW, ChatFormatting.BOLD), + this.font)); + LinearLayout actions = + contents.addChild(LinearLayout.horizontal().spacing(8)); + actions.addChild(Button.builder( + Component.literal("Open Page"), + ConfirmLinkScreen.confirmLink(this, URI.create(current.pageWithCode()))) + .width(BUTTON_WIDTH / 2 + 20) + .build()); + actions.addChild(Button.builder(Component.literal("Copy Code"), button -> { + this.minecraft.keyboardHandler.setClipboard(current.userCode()); + message = Component.literal("Code copied."); + rebuildWidgets(); + }) + .width(BUTTON_WIDTH / 2 + 20) + .build()); + contents.addChild(text( + Component.literal("Waiting for you to sign in...").withStyle(ChatFormatting.GRAY))); + } + footer.addChild(Button.builder(CommonComponents.GUI_CANCEL, button -> cancel()) + .build()); + } + case SIGNING_IN -> { + contents.addChild(text(Component.literal("Signing in to Minecraft..."))); + footer.addChild(Button.builder(CommonComponents.GUI_CANCEL, button -> cancel()) + .build()); + } + } + if (!message.equals(CommonComponents.EMPTY)) { + contents.addChild(text(message)); + } + + layout.visitWidgets(this::addRenderableWidget); + repositionElements(); + } + + private MultiLineTextWidget text(Component text) { + return new MultiLineTextWidget(text, this.font) + .setMaxWidth(Math.min(TEXT_WIDTH, this.width - 20)) + .setMaxRows(4) + .setCentered(true); + } + + @Override + protected void repositionElements() { + layout.arrangeElements(); + } + + // --- The flow ------------------------------------------------------------------------------ + + private void start() { + int mine = ++attempt; + MicrosoftSignIn client = MicrosoftAccounts.signIn(); + signIn = client; + message = CommonComponents.EMPTY; + show(State.REQUESTING); + whenDone(client.requestCode(), mine, requested -> { + code = requested; + pollFailures = 0; + intervalSeconds = requested.intervalSeconds(); + nextPollMillis = System.currentTimeMillis() + intervalSeconds * 1000L; + show(State.CODE); + }); + } + + @Override + public void tick() { + DeviceCode current = code; + MicrosoftSignIn client = signIn; + if (state != State.CODE || current == null || client == null || polling) { + return; + } + if (System.currentTimeMillis() < nextPollMillis) { + return; + } + polling = true; + int mine = attempt; + // Not whenDone: a poll that didn't get through (school Wi-Fi, the proxy) is tried again, and + // only Microsoft's own answer (expired, declined) ends the sign-in. + var _ = client.poll(current).handle((poll, failure) -> { + this.minecraft.execute(() -> { + if (mine != attempt) { + return; + } + if (failure != null) { + pollFailed(failure); + } else { + polled(poll, client, mine); + } + }); + return null; + }); + } + + private void polled(MicrosoftSignIn.Poll poll, MicrosoftSignIn client, int mine) { + polling = false; + if (pollFailures > 0) { + pollFailures = 0; + message = CommonComponents.EMPTY; + rebuildWidgets(); + } + switch (poll.state()) { + case WAITING -> nextPollMillis = System.currentTimeMillis() + intervalSeconds * 1000L; + case SLOW_DOWN -> { + intervalSeconds += 5; + nextPollMillis = System.currentTimeMillis() + intervalSeconds * 1000L; + } + case DONE -> { + MicrosoftSignIn.MicrosoftTokens tokens = poll.tokens(); + if (tokens != null) { + show(State.SIGNING_IN); + whenDone(client.signIn(tokens), mine, this::signedIn); + } + } + } + } + + /** A poll failed: tried again later if it only didn't get through, else the sign-in ends. */ + private void pollFailed(Throwable failure) { + Throwable cause = unwrap(failure); + if (cause instanceof SignInException signInFailure + && signInFailure.temporary() + && ++pollFailures <= MAX_POLL_FAILURES) { + polling = false; + long wait = Math.min(MAX_RETRY_MILLIS, (intervalSeconds * 1000L) << Math.min(pollFailures, 4)); + nextPollMillis = System.currentTimeMillis() + wait; + message = Component.literal("Can't reach Microsoft right now. Still trying...") + .withStyle(ChatFormatting.GRAY); + rebuildWidgets(); + return; + } + failed(failure); + } + + private static Throwable unwrap(Throwable failure) { + Throwable cause = failure; + while (cause instanceof CompletionException && cause.getCause() != null) { + cause = cause.getCause(); + } + return cause; + } + + private void signedIn(MicrosoftAccount account) { + MicrosoftAccounts.signedIn(account); + code = null; + message = Component.literal("Signed in.").withStyle(ChatFormatting.GREEN); + show(State.IDLE); + } + + private void signOut() { + MicrosoftAccounts.signOut(); + message = Component.literal("Signed out. Your saved sign-in was deleted."); + show(State.IDLE); + } + + private void cancel() { + attempt++; + code = null; + polling = false; + message = CommonComponents.EMPTY; + show(State.IDLE); + } + + /** Runs {@code then} on the game thread once {@code future} succeeds, unless the attempt was abandoned. */ + private void whenDone(CompletableFuture future, int mine, Consumer then) { + // Answers arrive on the transport's thread; the screen changes on the game's. + var _ = future.handle((value, failure) -> { + this.minecraft.execute(() -> { + if (mine != attempt) { + return; + } + if (failure != null) { + failed(failure); + } else { + then.accept(value); + } + }); + return null; + }); + } + + private void failed(Throwable failure) { + Throwable cause = unwrap(failure); + String reason = cause instanceof SignInException && cause.getMessage() != null + ? cause.getMessage() + : "Sign-in failed. Try again."; + attempt++; + code = null; + polling = false; + pollFailures = 0; + message = Component.literal(reason).withStyle(ChatFormatting.RED); + show(State.IDLE); + } + + private void show(State next) { + state = next; + rebuildWidgets(); + } + + @Override + public void onClose() { + attempt++; + this.minecraft.gui.setScreen(parent); + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/account/ServerJoins.java b/incari-client/files/client/src/main/java/incari/client/account/ServerJoins.java new file mode 100644 index 0000000..72b804f --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/account/ServerJoins.java @@ -0,0 +1,81 @@ +package incari.client.account; + +import com.mojang.logging.LogUtils; +import incari.client.profile.PlayerName; +import incari.net.msa.JoinResult; +import incari.net.msa.MicrosoftAccount; +import incari.net.msa.SignInException; +import java.util.concurrent.CompletionException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import net.minecraft.network.chat.Component; +import org.jspecify.annotations.Nullable; +import org.slf4j.Logger; + +/** + * Online-mode joins (ADR 0070): when a server asks the client to prove who it is, tell Mojang's + * session server through Incari's sign-in client, so the server finds the player there. Without an + * account, say how to get one instead of the game's bare "invalid session". + * + *

Runs on the game's IO pool, where the handshake already waits for the session server; in a + * browser that thread suspends, so the page carries on. + */ +public final class ServerJoins { + + private static final Logger LOGGER = LogUtils.getLogger(); + /** Renewing the token and joining: a few requests through a proxy at most. */ + private static final long TIMEOUT_SECONDS = 60; + + private ServerJoins() {} + + /** + * Hook ({@code ClientHandshakePacketListenerImpl.authenticateServer}): whether Incari answers + * this join. Not for a launcher's own account (the desktop launched with a real token), which the + * game's session service answers as before. + */ + public static boolean handles() { + return MicrosoftAccounts.account() != null || PlayerName.launchedOffline(); + } + + /** + * Hook (same): joins the server whose hash is {@code serverHash} as the signed-in account. + * + * @return null when joined, else why not, for the disconnect screen + */ + public static @Nullable Component authenticate(String serverHash) { + if (MicrosoftAccounts.account() == null) { + return failed(Component.literal( + "This server checks Minecraft accounts. Sign in with Microsoft in Edit Profile to join it.")); + } + try { + MicrosoftAccount account = MicrosoftAccounts.fresh().get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + JoinResult result = + MicrosoftAccounts.signIn().join(account, serverHash).get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + return switch (result) { + case OK -> null; + case INVALID_SESSION -> failed(Component.translatable("disconnect.loginFailedInfo.invalidSession")); + case INSUFFICIENT_PRIVILEGES -> + failed(Component.translatable("disconnect.loginFailedInfo.insufficientPrivileges")); + case BANNED -> failed(Component.translatable("disconnect.loginFailedInfo.userBanned")); + case UNAVAILABLE -> failed(Component.translatable("disconnect.loginFailedInfo.serversUnavailable")); + }; + } catch (ExecutionException | CompletionException e) { + Throwable cause = e.getCause() != null ? e.getCause() : e; + if (cause instanceof SignInException && cause.getMessage() != null) { + return failed(Component.literal(cause.getMessage())); + } + LOGGER.warn("Joining with the Microsoft account failed: {}", cause.toString()); + return failed(Component.translatable("disconnect.loginFailedInfo.serversUnavailable")); + } catch (TimeoutException e) { + return failed(Component.literal("Mojang's session server took too long to answer.")); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return failed(Component.translatable("disconnect.loginFailedInfo.serversUnavailable")); + } + } + + private static Component failed(Component reason) { + return Component.translatable("disconnect.loginFailedInfo", reason); + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/account/package-info.java b/incari-client/files/client/src/main/java/incari/client/account/package-info.java new file mode 100644 index 0000000..6df9ed9 --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/account/package-info.java @@ -0,0 +1,9 @@ +/** + * Microsoft accounts for online-mode servers (ADR 0070): the signed-in account and its file, the + * sign-in screen, the handshake's session join and the chat-signing keys. The protocol work is in + * {@code incari.net.msa}; this package adapts it to the game. + */ +@NullMarked +package incari.client.account; + +import org.jspecify.annotations.NullMarked; diff --git a/incari-client/files/client/src/main/java/incari/client/audio/CompressedSoundStream.java b/incari-client/files/client/src/main/java/incari/client/audio/CompressedSoundStream.java new file mode 100644 index 0000000..2a9dd3e --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/audio/CompressedSoundStream.java @@ -0,0 +1,68 @@ +package incari.client.audio; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import javax.sound.sampled.AudioFormat; +import net.minecraft.client.sounds.AudioStream; +import net.minecraft.client.sounds.JOrbisAudioStream; +import net.minecraft.client.sounds.LoopingAudioStream; +import org.jspecify.annotations.Nullable; + +/** + * A whole Ogg Vorbis file, handed to the device to stream (music, records) instead of being + * decoded a second at a time on the game's side. A device that can't stream compressed files still + * gets PCM: the game's own decoder starts on the first {@link #read}. + */ +public final class CompressedSoundStream implements AudioStream { + + private final byte[] file; + private final boolean looping; + private @Nullable AudioStream decoder; + + public CompressedSoundStream(byte[] file, boolean looping) { + this.file = file; + this.looping = looping; + } + + /** The whole file, not a copy (a track of music is megabytes): the caller mustn't change it. */ + public byte[] file() { + return file; + } + + public boolean looping() { + return looping; + } + + @Override + public AudioFormat getFormat() { + try { + return decoder().getFormat(); + } catch (IOException e) { + throw new IllegalStateException("Can't read the sound's header", e); + } + } + + @Override + public ByteBuffer read(final int expectedSize) throws IOException { + return decoder().read(expectedSize); + } + + private AudioStream decoder() throws IOException { + AudioStream current = decoder; + if (current == null) { + ByteArrayInputStream input = new ByteArrayInputStream(file); + current = looping ? new LoopingAudioStream(JOrbisAudioStream::new, input) : new JOrbisAudioStream(input); + decoder = current; + } + return current; + } + + @Override + public void close() throws IOException { + AudioStream current = decoder; + if (current != null) { + current.close(); + } + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/audio/DecodedSoundBudget.java b/incari-client/files/client/src/main/java/incari/client/audio/DecodedSoundBudget.java new file mode 100644 index 0000000..e3165f5 --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/audio/DecodedSoundBudget.java @@ -0,0 +1,68 @@ +package incari.client.audio; + +import com.mojang.blaze3d.audio.SoundBuffer; +import incari.client.tier.DeviceTier; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import net.minecraft.resources.Identifier; + +/** + * How much decoded sound the platform's cache keeps (ADR 0025). The game keeps every sound it + * has decoded until the next resource reload; the browser's are 32-bit float samples at the output + * rate, about 190 kB a second of mono sound, held by the page outside the JavaScript heap but in the + * tab's memory all the same. Past the tier's budget, the sounds played longest ago leave the cache: + * one still playing finishes (its source holds the samples), and the next time it's played it's + * decoded again from the file, which the service worker keeps. + */ +final class DecodedSoundBudget { + + /** Decoded sounds by when they were last asked for, oldest first; sizes in bytes. */ + private final LinkedHashMap sizes = new LinkedHashMap<>(64, 0.75f, true); + + private long total; + + /** The bytes of decoded sound kept at {@code tier}. */ + static long budget(DeviceTier tier) { + return switch (tier) { + case POTATO -> 16L << 20; + case STANDARD -> 32L << 20; + case HIGH -> 96L << 20; + }; + } + + /** {@code location} was asked for again. */ + synchronized void used(Identifier location) { + sizes.get(location); + } + + /** {@code location} finished decoding into {@code bytes} bytes. */ + synchronized void decoded(Identifier location, int bytes) { + Integer previous = sizes.put(location, bytes); + total += bytes - (previous == null ? 0 : previous); + } + + /** Bytes of decoded sound counted now. */ + synchronized long total() { + return total; + } + + /** + * Drops the sounds asked for longest ago from {@code cache} until what's left is within + * {@code budget}, never {@code keep} (the sound being asked for now). + */ + synchronized void trim(Map> cache, Identifier keep, long budget) { + Iterator> oldest = sizes.entrySet().iterator(); + while (total > budget && oldest.hasNext()) { + Map.Entry entry = oldest.next(); + if (entry.getKey().equals(keep)) { + continue; + } + oldest.remove(); + total -= entry.getValue(); + // Gone already if the game cleared its cache (a resource reload). + cache.remove(entry.getKey()); + } + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/audio/PlatformSoundLoading.java b/incari-client/files/client/src/main/java/incari/client/audio/PlatformSoundLoading.java new file mode 100644 index 0000000..918a5d8 --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/audio/PlatformSoundLoading.java @@ -0,0 +1,167 @@ +package incari.client.audio; + +import com.mojang.blaze3d.audio.SoundBuffer; +import com.mojang.logging.LogUtils; +import incari.client.tier.DeviceTier; +import incari.platform.api.Platforms; +import incari.platform.api.audio.AudioDecoder; +import incari.platform.api.audio.AudioException; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.ByteBuffer; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import javax.sound.sampled.AudioFormat; +import net.minecraft.client.sounds.AudioStream; +import net.minecraft.client.sounds.JOrbisAudioStream; +import net.minecraft.resources.Identifier; +import net.minecraft.server.packs.resources.ResourceProvider; +import org.jspecify.annotations.Nullable; +import org.slf4j.Logger; + +/** + * Loads the game's sounds through the platform's own decoder, where it has one (the browser, + * ADR 0013). {@code SoundBufferLibrary} asks here first; null sends it down its own path, the + * game's Java decoder, which is all the desktop ever uses. + * + *

Whole sounds are decoded by the platform (natively, off the page's thread) and cached as the + * game caches them, within the tier's budget ({@link DecodedSoundBudget}). Streams (music, records) aren't decoded here at all: the file goes to the + * device, which decodes it as it plays ({@link CompressedSoundStream}). Files the page only has a + * placeholder for are fetched first ({@link RemoteSounds}). + * + *

A sound that can't be read (its download failed: a dropped connection, a host refusing a burst + * of requests) is played as a moment of silence and fetched again the next time it's asked for, a + * few seconds later. The game only plays a channel once its buffer arrives and only reclaims a + * channel that has played, so a failed future would leave that sound silent until the next + * resource reload and hold one of its channels for good; enough of them and no new sound plays. + */ +public final class PlatformSoundLoading { + + private static final Logger LOGGER = LogUtils.getLogger(); + + private static final SoundLoader LOADER = new SoundLoader(); + + static final DecodedSoundBudget BUDGET = new DecodedSoundBudget(); + + /** How long a sound that couldn't be read stays silent before it's tried again. */ + static final long RETRY_MILLIS = 5000; + + private PlatformSoundLoading() {} + + /** + * The decoded sound at {@code location}, cached in the game's own {@code cache}; null if the + * platform leaves decoding to the game. + */ + public static @Nullable CompletableFuture completeBuffer( + final Map> cache, + final ResourceProvider resources, + final Identifier location) { + return completeBuffer(Platforms.current().audio().decoder(), cache, resources, location); + } + + static @Nullable CompletableFuture completeBuffer( + final @Nullable AudioDecoder decoder, + final Map> cache, + final ResourceProvider resources, + final Identifier location) { + if (decoder == null) { + return null; + } + CompletableFuture buffer = cache.get(location); + if (buffer != null + && buffer.getNow(null) instanceof Silence silence + && System.currentTimeMillis() - silence.failedAt >= RETRY_MILLIS) { + buffer = null; + } + if (buffer == null) { + buffer = CompletableFuture.supplyAsync(() -> decode(decoder, resources, location), LOADER) + .exceptionally(failure -> { + LOGGER.warn("Couldn't load the sound {}; trying again when it next plays", location, failure); + return new Silence(System.currentTimeMillis()); + }); + cache.put(location, buffer); + var _ = buffer.thenAccept(decoded -> BUDGET.decoded(location, decoded.size())); + } else { + BUDGET.used(location); + } + BUDGET.trim(cache, location, DecodedSoundBudget.budget(DeviceTier.current())); + return buffer; + } + + /** + * What a sound that couldn't be read plays instead: a hundredth of a second of silence, so its + * channel plays, finishes and goes back to the pool. + */ + static final class Silence extends SoundBuffer { + + private static final int FRAMES = 480; + + final long failedAt; + + Silence(long failedAt) { + super( + ByteBuffer.allocate(FRAMES * 2), + new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 48000, 16, 1, 2, 48000, false)); + this.failedAt = failedAt; + } + } + + /** + * The file at {@code location} as a stream the device plays compressed; null if the platform + * leaves decoding to the game. + */ + public static @Nullable CompletableFuture stream( + final ResourceProvider resources, final Identifier location, final boolean looping) { + return stream(Platforms.current().audio().decoder(), resources, location, looping); + } + + static @Nullable CompletableFuture stream( + final @Nullable AudioDecoder decoder, + final ResourceProvider resources, + final Identifier location, + final boolean looping) { + if (decoder == null) { + return null; + } + return CompletableFuture.supplyAsync( + () -> new CompressedSoundStream(read(resources, location), looping), LOADER); + } + + private static SoundBuffer decode( + final AudioDecoder decoder, final ResourceProvider resources, final Identifier location) { + byte[] file = read(resources, location); + try { + return new SoundBuffer(decoder.decodeOggVorbis(file)); + } catch (AudioException e) { + // A browser without Ogg Vorbis (older Safari): the game's decoder still can. + LOGGER.warn("The platform couldn't decode {} ({}); decoding it in Java", location, e.getMessage()); + } + try (JOrbisAudioStream stream = new JOrbisAudioStream(new ByteArrayInputStream(file))) { + ByteBuffer samples = stream.readAll(); + return new SoundBuffer(samples, stream.getFormat()); + } catch (IOException e) { + throw new UncheckedIOException("Couldn't decode " + location, e); + } + } + + /** The file's bytes, fetched first if the page has only a placeholder for it. */ + private static byte[] read(final ResourceProvider resources, final Identifier location) { + try { + byte[] file; + try (InputStream in = resources.open(location)) { + file = in.readAllBytes(); + } + if (file.length == 0) { + byte[] fetched = RemoteSounds.fetch(location.getNamespace() + "/" + location.getPath()); + if (fetched != null) { + return fetched; + } + } + return file; + } catch (IOException e) { + throw new UncheckedIOException("Couldn't read " + location, e); + } + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/audio/RemoteSounds.java b/incari-client/files/client/src/main/java/incari/client/audio/RemoteSounds.java new file mode 100644 index 0000000..1424607 --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/audio/RemoteSounds.java @@ -0,0 +1,41 @@ +package incari.client.audio; + +import java.io.IOException; +import org.jspecify.annotations.Nullable; + +/** + * Where sound files come from when the page has only a placeholder for them. The browser build + * lists every sound of the asset index in its file system without downloading them (they're + * hundreds of megabytes); a placeholder is an empty file, and its contents are fetched the first + * time the sound plays. The entry point installs the source; the desktop has the real files and + * installs none. + */ +public final class RemoteSounds { + + /** Fetches an asset's contents by its name in the asset index. */ + @FunctionalInterface + public interface Source { + + /** + * The contents of {@code assetName} (like {@code minecraft/sounds/random/click.ogg}), or null + * if it isn't an asset this source has. Waits for the download: only the sound loader's + * threads call it. + */ + byte @Nullable [] fetch(String assetName) throws IOException; + } + + private static volatile @Nullable Source source; + + private RemoteSounds() {} + + /** Installs the source; null removes it. */ + public static void install(@Nullable Source remote) { + source = remote; + } + + /** The asset's contents from the installed source, or null if there's none or it doesn't have it. */ + static byte @Nullable [] fetch(String assetName) throws IOException { + Source current = source; + return current == null ? null : current.fetch(assetName); + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/audio/SoundLoader.java b/incari-client/files/client/src/main/java/incari/client/audio/SoundLoader.java new file mode 100644 index 0000000..45c5745 --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/audio/SoundLoader.java @@ -0,0 +1,54 @@ +package incari.client.audio; + +import java.util.ArrayDeque; +import java.util.concurrent.Executor; + +/** + * A few threads of its own that read and decode sounds for the platform's decoder. They aren't + * the game's I/O pool because in the browser that pool runs tasks inline on the game's thread (the + * platform reports no background threads), and decoding waits for the browser: a wait there + * would stall the frame. Here it suspends only this thread's coroutine. + */ +final class SoundLoader implements Executor { + + /** Enough that a long file (a track of music) being fetched doesn't hold up short ones. */ + private static final int THREADS = 3; + + private final ArrayDeque tasks = new ArrayDeque<>(); + private boolean started; + + @Override + public void execute(Runnable task) { + synchronized (tasks) { + if (!started) { + started = true; + for (int i = 0; i < THREADS; i++) { + Thread thread = new Thread(this::run, "Sound loader " + (i + 1)); + thread.setDaemon(true); + thread.start(); + } + } + tasks.addLast(task); + tasks.notifyAll(); + } + } + + private void run() { + while (true) { + Runnable task; + synchronized (tasks) { + while (tasks.isEmpty()) { + try { + tasks.wait(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } + } + task = tasks.removeFirst(); + } + // Tasks complete their own futures, failures included (CompletableFuture.supplyAsync). + task.run(); + } + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/audio/package-info.java b/incari-client/files/client/src/main/java/incari/client/audio/package-info.java new file mode 100644 index 0000000..c05cc8c --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/audio/package-info.java @@ -0,0 +1,5 @@ +/** Loading the game's sounds through the platform's decoder and streams (ADR 0013). */ +@NullMarked +package incari.client.audio; + +import org.jspecify.annotations.NullMarked; diff --git a/incari-client/files/client/src/main/java/incari/client/cosmetics/Badges.java b/incari-client/files/client/src/main/java/incari/client/cosmetics/Badges.java new file mode 100644 index 0000000..fbc2ccf --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/cosmetics/Badges.java @@ -0,0 +1,142 @@ +package incari.client.cosmetics; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.function.Predicate; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.FontDescription; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.network.chat.Style; +import net.minecraft.resources.Identifier; + +/** + * Incari's badge beside an Incari player's name tag, their name in the tab list and their name in chat (ADR 0062), so + * Incari players know each other without asking. The badge is one glyph of Incari's pack's {@code incari:badge} font (Incari's + * mark at 32 pixels, white so the glyph keeps its own colours), so the game's own name tag and tab list drawing carry it: + * nothing new is drawn. Shown for players whose account lets it show, while the player's + * "Show Incari badges" switch is on. + * + *

Render thread. A badged name is made once per player and name, not each frame; name tags and + * the tab list keep their own, as the two names differ. + */ +final class Badges { + + private static final Component BADGE = Component.literal("") + .withStyle(Style.EMPTY + .withFont(new FontDescription.Resource(Identifier.fromNamespaceAndPath("incari", "badge"))) + .withColor(0xFFFFFF)); + + private record Badged(Component from, Component to) {} + + private static final Map NAME_TAGS = new HashMap<>(); + private static final Map TAB_LIST = new HashMap<>(); + + private Badges() {} + + /** The name tag {@code tag} with the badge before it, for the player {@code id}. */ + static Component badged(UUID id, Component tag) { + return badged(NAME_TAGS, id, tag); + } + + /** The tab list's {@code name} with the badge before it, for the player {@code id}. */ + static Component badgedInTabList(UUID id, Component name) { + return badged(TAB_LIST, id, name); + } + + /** + * Chat's {@code message} with the badge before the first mention of each name {@code badged} + * takes, or {@code message} when it names none. Names are runs of name characters in the + * message's text; legacy {@code §} codes (1.8 servers' chat) are skipped over and carried past + * the badge, so a coloured name keeps its colour. Once per chat line, not per frame. + */ + static Component badgedInChat(Component message, Predicate badged) { + String text = message.getString(); + List at = new ArrayList<>(); + Set seen = new HashSet<>(); + int n = text.length(); + for (int i = 0; i < n; ) { + char c = text.charAt(i); + if (c == '§') { + i += 2; + } else if (!isNameChar(c)) { + i++; + } else { + int start = i; + while (i < n && isNameChar(text.charAt(i))) { + i++; + } + String name = text.substring(start, i); + if (i - start <= 16 && seen.add(name) && badged.test(name)) { + at.add(start); + } + } + } + if (at.isEmpty()) { + return message; + } + // The message rebuilt piece by piece in the same styles, each piece cut where a badge goes. + MutableComponent out = Component.empty(); + int[] offset = {0}; + int[] next = {0}; + message.visit( + (style, piece) -> { + int end = offset[0] + piece.length(); + int from = 0; + String carried = ""; + while (next[0] < at.size() && at.get(next[0]) < end) { + int cut = at.get(next[0]++) - offset[0]; + String before = piece.substring(from, cut); + if (!before.isEmpty()) { + out.append(Component.literal(carried + before).setStyle(style)); + } + carried += legacyCodes(before); + out.append(BADGE).append(" "); + from = cut; + } + out.append( + Component.literal(carried + piece.substring(from)).setStyle(style)); + offset[0] = end; + return Optional.empty(); + }, + Style.EMPTY); + return out; + } + + private static boolean isNameChar(char c) { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_'; + } + + /** The {@code §} codes in {@code text}, in order: what a later cut of the same text must repeat. */ + private static String legacyCodes(String text) { + StringBuilder codes = new StringBuilder(); + for (int i = text.indexOf('§'); i >= 0 && i + 1 < text.length(); i = text.indexOf('§', i + 2)) { + codes.append(text, i, i + 2); + } + return codes.toString(); + } + + private static Component badged(Map made, UUID id, Component name) { + Badged last = made.get(id); + if (last != null && last.from().equals(name)) { + return last.to(); + } + MutableComponent badged = Component.empty().append(BADGE).append(" ").append(name); + if (made.size() > 512) { + made.clear(); + } + made.put(id, new Badged(name, badged)); + return badged; + } + + /** Players who left, forgotten (on leaving a world). */ + static void clear() { + NAME_TAGS.clear(); + TAB_LIST.clear(); + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/cosmetics/CosmeticArt.java b/incari-client/files/client/src/main/java/incari/client/cosmetics/CosmeticArt.java new file mode 100644 index 0000000..63bc439 --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/cosmetics/CosmeticArt.java @@ -0,0 +1,480 @@ +package incari.client.cosmetics; + +/** + * The cosmetics' pictures, painted in code (ADR 0061): Incari's own art, so nothing is shipped as + * an image and nothing is Mojang's. Capes are painted into the game's 64x32 cape layout (the outer + * side, the inner side, the edges and an elytra), some again and again as time passes; the cards in + * the wardrobe get small icons. Pixels are ARGB. + * + *

Any thread: pure functions of their arguments. + */ +final class CosmeticArt { + + static final int CAPE_WIDTH = 64; + static final int CAPE_HEIGHT = 32; + + /** A wardrobe card's icon, square. */ + static final int ICON = 24; + + private CosmeticArt() {} + + /** Whether the cape {@code id} moves: it's painted again as time passes. */ + static boolean animated(String id) { + return switch (id) { + case "cape.aurora", "cape.midnight", "cape.ember", "cape.tide" -> true; + default -> false; + }; + } + + // --------------------------------------------------------------------------------------------- + // Capes + // --------------------------------------------------------------------------------------------- + + /** + * Paints the cape {@code id} at time {@code t} (seconds) into {@code out}, 64x32: the outer side + * at (1, 1), 10x16, as the game's cape model reads it; the inner side darker; the edges; and the + * elytra's wing at (22, 0), so an elytra worn with it matches. + */ + static void cape(String id, float t, int[] out) { + java.util.Arrays.fill(out, 0); + for (int py = 0; py < 16; py++) { + for (int px = 0; px < 10; px++) { + int color = design(id, px + 0.5F, py + 0.5F, t); + out[(py + 1) * CAPE_WIDTH + px + 1] = color; + // The inner side faces the player: the same, mirrored and in shade. + out[(py + 1) * CAPE_WIDTH + 12 + (9 - px)] = shade(color, 0.55F); + } + } + int edge = shade(design(id, 5, 8, t), 0.7F); + for (int py = 1; py <= 16; py++) { + out[py * CAPE_WIDTH] = edge; + out[py * CAPE_WIDTH + 11] = edge; + } + for (int px = 1; px <= 20; px++) { + out[px] = edge; + } + for (int y = 0; y < 22; y++) { + for (int x = 22; x < 46; x++) { + out[y * CAPE_WIDTH + x] = design(id, (x - 22 + 0.5F) * 10 / 24.0F, (y + 0.5F) * 16 / 22.0F, t); + } + } + } + + /** One cape's picture at (px, py) in its 10x16 face, at time {@code t}: opaque. */ + private static int design(String id, float px, float py, float t) { + float v = py / 16; + return 0xFF000000 + | switch (id) { + case "cape.frost" -> frost(px, py, v); + case "cape.aurora" -> aurora(px, py, v, t); + case "cape.midnight" -> midnight(px, py, v, t); + case "cape.ember" -> ember(px, py, v, t); + case "cape.sakura" -> sakura(px, py, v); + case "cape.tide" -> tide(px, py, v, t); + case "cape.mono" -> mono(px, py); + default -> 0x808080; + }; + } + + private static int frost(float px, float py, float v) { + int color = mix(0x9FD3F5, 0x1E3F66, v); + if (px < 1 || px > 9 || py < 1 || py > 15) { + color = mix(color, 0xFFFFFF, 0.35F); + } + // A snowflake in the middle: three strokes and a branch at each arm's end. + float dx = px - 5; + float dy = py - 6.5F; + boolean flake = (Math.abs(dx) < 0.6F && Math.abs(dy) < 3.4F) + || (Math.abs(dy) < 0.6F && Math.abs(dx) < 3.4F) + || (Math.abs(dx - dy) < 0.75F && Math.abs(dx) < 2.4F) + || (Math.abs(dx + dy) < 0.75F && Math.abs(dx) < 2.4F); + if (flake) { + return 0xF4FBFF; + } + // Frost glinting further down. + if (py > 11 && hash((int) px, (int) py, 3) < 0.12F) { + return mix(color, 0xFFFFFF, 0.6F); + } + return color; + } + + private static int aurora(float px, float py, float v, float t) { + int color = mix(0x0E1B33, 0x050A15, v); + int[] bands = {0x3CF2A0, 0x3CC8F2, 0xA05CF2}; + for (int k = 0; k < bands.length; k++) { + float centre = 3.5F + k * 4.2F + 1.6F * (float) Math.sin(px * 0.7F + t * 1.3F + k * 2.1F); + float d = (py - centre) / 1.7F; + float glow = (float) Math.exp(-d * d) * (0.65F + 0.35F * (float) Math.sin(t * 0.9F + px * 0.5F + k)); + color = add(color, bands[k], glow * 0.85F); + } + if (hash((int) px, (int) py, 11) < 0.05F) { + color = mix(color, 0xFFFFFF, 0.5F + 0.5F * (float) Math.sin(t * 4 + px)); + } + return color; + } + + private static int midnight(float px, float py, float v, float t) { + int color = mix(0x1F2A5C, 0x05081A, v); + // A crescent moon in the top right. + float mx = px - 7; + float my = py - 3.2F; + float ox = px - 7.9F; + float oy = py - 2.5F; + if (mx * mx + my * my < 4.4F && ox * ox + oy * oy > 3.0F) { + return 0xF2EFD0; + } + float star = hash((int) px, (int) py, 7); + if (star < 0.1F) { + float phase = hash((int) px, (int) py, 13) * 6.283F; + float twinkle = 0.5F + 0.5F * (float) Math.sin(t * 2.6F + phase); + return mix(color, 0xFFFFFF, 0.35F + 0.65F * twinkle); + } + return color; + } + + private static int ember(float px, float py, float v, float t) { + float flame = noise(px * 0.55F, py * 0.45F + t * 2.2F); + float heat = clamp(v * 1.25F + (flame - 0.5F) * 0.9F - 0.2F); + int color; + if (heat < 0.33F) { + color = mix(0x140806, 0x7A1708, heat / 0.33F); + } else if (heat < 0.66F) { + color = mix(0x7A1708, 0xE5481A, (heat - 0.33F) / 0.33F); + } else { + color = mix(0xE5481A, 0xFFC94A, (heat - 0.66F) / 0.34F); + } + // Sparks rising. + int cell = (int) Math.floor(py + t * 5); + if (hash((int) px, cell, 5) < 0.045F) { + return 0xFFE38A; + } + return color; + } + + private static int sakura(float px, float py, float v) { + int color = mix(0xFCDCE8, 0xE597B6, v); + // A branch across, from the bottom left to the top right. + float branch = Math.abs((py - 12.5F) + (px * 0.8F)) / 1.28F; + if (branch < 0.55F && px < 9.5F) { + color = 0x5E3B3B; + } + float[][] blossoms = {{2, 10.5F}, {5, 8}, {8, 5.5F}, {3, 4}, {7.5F, 12.5F}, {1.5F, 1.8F}}; + for (float[] b : blossoms) { + float dx = px - b[0]; + float dy = py - b[1]; + float d = dx * dx + dy * dy; + if (d < 0.5F) { + return 0xFFE9A8; + } + if (d < 2.1F) { + return 0xF4F0F2; + } + } + return color; + } + + private static int tide(float px, float py, float v, float t) { + int color = mix(0x3D9FE0, 0x0A2552, v); + for (int k = 0; k < 5; k++) { + float crest = 2.5F + k * 3 + 0.9F * (float) Math.sin(px * 0.9F + t * 2.0F + k * 1.7F); + if (Math.abs(py - crest) < 0.55F) { + return mix(color, 0xD8F1FF, 0.75F); + } + } + if (hash((int) px, (int) Math.floor(py + t), 9) < 0.04F) { + return mix(color, 0xFFFFFF, 0.5F); + } + return color; + } + + private static int mono(float px, float py) { + if (px < 1 || px > 9 || py < 1 || py > 15 || (px > 4 && px < 6)) { + return 0xEDEDED; + } + return 0x151515; + } + + // --------------------------------------------------------------------------------------------- + // Wings + // --------------------------------------------------------------------------------------------- + + /** + * A wing at (sx, sy) on its panel: sx from the root (0) to the tip (1), sy from the top (0) to + * the bottom (1). Transparent outside the wing. + */ + static int wing(String id, float sx, float sy) { + return switch (id) { + case "back.bat_wings" -> batWing(sx, sy); + case "back.frost_wings" -> frostWing(sx, sy); + default -> angelWing(sx, sy); + }; + } + + private static float wingTop(float sx) { + return 0.34F - 0.3F * (float) Math.sin(sx * Math.PI * 0.5); + } + + private static float featherBottom(float sx) { + float scallop = 0.06F * (float) Math.abs(Math.sin(sx * Math.PI * 5)); + return 0.97F - 0.62F * (float) Math.pow(sx, 1.15) - scallop; + } + + private static int angelWing(float sx, float sy) { + float top = wingTop(sx); + float bottom = featherBottom(sx); + if (sy < top || sy > bottom) { + return 0; + } + int color = mix(0xFFFFFF, 0xDCE3EC, clamp((sy - top) / Math.max(0.05F, bottom - top)) * 0.6F); + // Rows of feathers: lines across, and their tips toward the bottom. + float row = (sy - top) / Math.max(0.05F, bottom - top) * 4; + if (row - (float) Math.floor(row) < 0.12F && row > 0.8F) { + color = 0xC9D3E0; + } + if (sx < 0.12F) { + color = mix(color, 0xB8C3D2, 0.5F); + } + return 0xFF000000 | color; + } + + private static int frostWing(float sx, float sy) { + float top = wingTop(sx); + float bottom = featherBottom(sx); + if (sy < top || sy > bottom) { + return 0; + } + float facet = sx * 4 + sy * 2.5F; + boolean edge = facet - (float) Math.floor(facet) < 0.09F || sy - top < 0.03F || bottom - sy < 0.03F; + if (edge) { + return 0xF0F4FBFF; + } + int color = mix(0xCDEBFF, 0x7FB8E8, clamp(sy)); + return 0xA8000000 | color; + } + + private static int batWing(float sx, float sy) { + // The arm along the top, the fingers fanning down from the wrist, the skin scalloped + // between them. + float top = 0.12F + 0.12F * sx; + float fingers = sx * 3; + float between = fingers - (float) Math.floor(fingers); + float bottom = 0.9F - 0.5F * sx - 0.22F * (float) Math.sin(between * Math.PI); + if (sy < top || sy > bottom) { + return 0; + } + if (sy - top < 0.07F) { + return 0xFF3A2A40; + } + for (int finger = 1; finger <= 3; finger++) { + float endX = finger / 3.0F; + float endY = 0.9F - 0.5F * endX; + float along = sx / endX; + if (along <= 1 && Math.abs(sy - (top + (endY - top) * along)) < 0.035F) { + return 0xFF22182A; + } + } + return 0xFF000000 | mix(0x62486E, 0x3E2D47, clamp(sy)); + } + + // --------------------------------------------------------------------------------------------- + // Icons + // --------------------------------------------------------------------------------------------- + + /** The wardrobe card's icon for a hat or a back cosmetic, {@link #ICON} square, into {@code out}. */ + static void icon(String id, int[] out) { + java.util.Arrays.fill(out, 0); + for (int y = 0; y < ICON; y++) { + for (int x = 0; x < ICON; x++) { + out[y * ICON + x] = iconPixel(id, x + 0.5F, y + 0.5F); + } + } + } + + private static int iconPixel(String id, float x, float y) { + return switch (id) { + case "hat.crown" -> crownIcon(x, y); + case "hat.halo" -> haloIcon(x, y); + case "hat.top_hat" -> topHatIcon(x, y); + case "hat.beanie" -> beanieIcon(x, y); + case "hat.horns" -> hornsIcon(x, y); + case "hat.cat_ears" -> earsIcon(x, y); + case "back.backpack" -> backpackIcon(x, y); + case "back.angel_wings", "back.frost_wings", "back.bat_wings" -> wingsIcon(id, x, y); + default -> 0; + }; + } + + private static int crownIcon(float x, float y) { + boolean band = y >= 13 && y < 19 && x >= 4 && x < 20; + boolean points = false; + for (float peak : new float[] {5, 12, 19}) { + float dx = Math.abs(x - peak); + if (y < 13 && y >= 6 + dx * 2.2F && dx < 3) { + points = true; + } + } + if (Math.abs(x - 12) < 1.6F && Math.abs(y - 16) < 1.6F) { + return 0xFFE0344B; + } + if (band || points) { + return 0xFF000000 | mix(0xFFE58A, 0xD69A1E, (y - 6) / 13); + } + return 0; + } + + private static int haloIcon(float x, float y) { + float dx = (x - 12) / 9; + float dy = (y - 12) / 4; + float d = dx * dx + dy * dy; + if (d < 1 && d > 0.45F) { + return 0xFFFFF0B0; + } + if (d < 1.4F && d > 0.3F) { + return 0x60FFE68A; + } + return 0; + } + + private static int topHatIcon(float x, float y) { + if (y >= 17 && y < 19 && x >= 2 && x < 22) { + return 0xFF1C1C22; + } + if (y >= 4 && y < 17 && x >= 6 && x < 18) { + return y >= 13 ? 0xFFC0263A : 0xFF26262E; + } + return 0; + } + + private static int beanieIcon(float x, float y) { + float dx = (x - 12) / 9; + float dy = (y - 17) / 11; + if (y < 17 && dx * dx + dy * dy < 1) { + int row = (int) (y / 2.5F); + return (row & 1) == 0 ? 0xFF7FC3F2 : 0xFFEAF6FF; + } + if (y >= 17 && y < 20 && x >= 3 && x < 21) { + return 0xFF4F8FC7; + } + float px = x - 12; + float py = y - 5; + if (px * px + py * py < 6) { + return 0xFFFFFFFF; + } + return 0; + } + + private static int hornsIcon(float x, float y) { + for (int side = -1; side <= 1; side += 2) { + float baseX = 12 + side * 5; + float t = (20 - y) / 15; + if (t < 0 || t > 1) { + continue; + } + float centre = baseX + side * 5 * t * t; + float half = 2.6F * (1 - t) + 0.4F; + if (Math.abs(x - centre) < half) { + return 0xFF000000 | mix(0xF2E6CC, 0x9C8A6A, t); + } + } + return 0; + } + + private static int earsIcon(float x, float y) { + for (int side = -1; side <= 1; side += 2) { + float cx = 12 + side * 6; + float t = (19 - y) / 13; + if (t < 0 || t > 1) { + continue; + } + float half = 4.5F * (1 - t); + float d = Math.abs(x - cx); + if (d < half) { + if (d < half - 1.6F && t < 0.7F) { + return 0xFFF2A6BC; + } + // A light rim, so dark ears read on a dark card. + return d > half - 0.8F || t > 0.92F ? 0xFF9A9AAE : 0xFF4A4A58; + } + } + return 0; + } + + private static int backpackIcon(float x, float y) { + if (x >= 6 && x < 18 && y >= 4 && y < 21) { + if (y < 9) { + return 0xFF7FC3F2; + } + if (x >= 8 && x < 16 && y >= 12 && y < 18) { + return (x < 8.8F || x > 15.2F || y < 12.8F || y > 17.2F) ? 0xFFA9DCFF : 0xFF2C4A72; + } + return 0xFF22385A; + } + return 0; + } + + private static int wingsIcon(String id, float x, float y) { + // Both wings, spread from the middle. + float sx = Math.abs(x - 12) / 11; + float sy = (y - 2) / 20; + if (Math.abs(x - 12) < 1 || sy < 0 || sy > 1 || sx > 1) { + return 0; + } + int color = wing(id, sx, sy); + return (color >>> 24) == 0 ? 0 : 0xFF000000 | color; + } + + // --------------------------------------------------------------------------------------------- + // Helpers + // --------------------------------------------------------------------------------------------- + + /** A colour between {@code a} and {@code b} (RGB), {@code t} of the way. */ + static int mix(int a, int b, float t) { + float k = clamp(t); + int r = Math.round(((a >> 16) & 255) + (((b >> 16) & 255) - ((a >> 16) & 255)) * k); + int g = Math.round(((a >> 8) & 255) + (((b >> 8) & 255) - ((a >> 8) & 255)) * k); + int bl = Math.round((a & 255) + ((b & 255) - (a & 255)) * k); + return r << 16 | g << 8 | bl; + } + + private static int add(int base, int light, float amount) { + int r = Math.min(255, ((base >> 16) & 255) + Math.round(((light >> 16) & 255) * amount)); + int g = Math.min(255, ((base >> 8) & 255) + Math.round(((light >> 8) & 255) * amount)); + int b = Math.min(255, (base & 255) + Math.round((light & 255) * amount)); + return r << 16 | g << 8 | b; + } + + /** {@code argb} darker by {@code factor}, alpha kept. */ + static int shade(int argb, float factor) { + int r = Math.round(((argb >> 16) & 255) * factor); + int g = Math.round(((argb >> 8) & 255) * factor); + int b = Math.round((argb & 255) * factor); + return (argb & 0xFF000000) | r << 16 | g << 8 | b; + } + + static float clamp(float value) { + return Math.max(0, Math.min(1, value)); + } + + /** A number in [0, 1) for a cell: the same for the same cell and salt. */ + static float hash(int x, int y, int salt) { + int h = x * 374761393 + y * 668265263 + salt * 1274126177; + h = (h ^ (h >>> 13)) * 1274126177; + h ^= h >>> 16; + return (h & 0xFFFFFF) / (float) 0x1000000; + } + + /** Smooth value noise in [0, 1). */ + private static float noise(float x, float y) { + int ix = (int) Math.floor(x); + int iy = (int) Math.floor(y); + float fx = x - ix; + float fy = y - iy; + float sx = fx * fx * (3 - 2 * fx); + float sy = fy * fy * (3 - 2 * fy); + float a = hash(ix, iy, 1); + float b = hash(ix + 1, iy, 1); + float c = hash(ix, iy + 1, 1); + float d = hash(ix + 1, iy + 1, 1); + return a + (b - a) * sx + (c - a) * sy + (a - b - c + d) * sx * sy; + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/cosmetics/CosmeticModels.java b/incari-client/files/client/src/main/java/incari/client/cosmetics/CosmeticModels.java new file mode 100644 index 0000000..34504b2 --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/cosmetics/CosmeticModels.java @@ -0,0 +1,382 @@ +package incari.client.cosmetics; + +import com.mojang.blaze3d.platform.NativeImage; +import incari.online.Cosmetic; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import net.minecraft.client.Minecraft; +import net.minecraft.client.model.Model; +import net.minecraft.client.model.geom.ModelPart; +import net.minecraft.client.model.geom.PartPose; +import net.minecraft.client.model.geom.builders.CubeDeformation; +import net.minecraft.client.model.geom.builders.CubeListBuilder; +import net.minecraft.client.model.geom.builders.LayerDefinition; +import net.minecraft.client.model.geom.builders.MeshDefinition; +import net.minecraft.client.model.geom.builders.PartDefinition; +import net.minecraft.client.renderer.entity.state.AvatarRenderState; +import net.minecraft.client.renderer.rendertype.RenderType; +import net.minecraft.client.renderer.rendertype.RenderTypes; +import net.minecraft.client.renderer.texture.DynamicTexture; +import net.minecraft.core.Direction; +import net.minecraft.resources.Identifier; +import org.jspecify.annotations.Nullable; + +/** + * The hats and back cosmetics as models (ADR 0061): each a few boxes, described here, baked once, + * with a texture painted from the same description, so the boxes and their pictures never disagree. + * Coordinates are the player model's: a hat's from the head's pivot (the head's box is -4..4 across, + * -8..0 up), a back cosmetic's from the body's (the body's back is at z = 2). + * + *

Render thread. A model and its texture are made the first time something wears it. + */ +final class CosmeticModels { + + /** Where a cosmetic sits on the player. */ + enum Anchor { + HEAD, + BODY + } + + /** How a cosmetic is drawn. */ + enum Look { + /** Opaque, with see-through pixels cut out. */ + CUTOUT, + /** Partly see-through. */ + TRANSLUCENT, + /** Glowing: lit by itself, at full brightness. */ + GLOW + } + + /** What a box is painted with. */ + enum Material { + GOLD, + GOLD_GEM, + VELVET, + HALO, + FELT, + FELT_BAND, + KNIT, + POM, + BONE, + EAR, + PACK, + POCKET, + WING + } + + /** A box: where, how big, how much bigger than that, and what it's painted with. */ + private record Box(float x, float y, float z, int w, int h, int d, float grow, Material material, boolean mirror) {} + + /** A part: where it turns about, how it's turned, and its boxes. */ + private record Part(String name, PartPose pose, List boxes) {} + + /** A cosmetic's model as described. */ + private record Spec(Anchor anchor, Look look, List parts) {} + + private static final int TEXTURE = 64; + + /** Each cosmetic's model, made the first time it's drawn: null for one that isn't a model. */ + private static final Map MADE = new HashMap<>(); + + /** A model ready to draw, with its texture and where it sits. */ + record Made(CosmeticModel model, Identifier texture, Anchor anchor, Look look) {} + + private CosmeticModels() {} + + /** The model for {@code cosmetic}, made now if it's the first time; null if it isn't one. */ + static @Nullable Made of(Cosmetic cosmetic) { + if (MADE.containsKey(cosmetic.id())) { + return MADE.get(cosmetic.id()); + } + Spec spec = spec(cosmetic.id()); + Made made = spec == null ? null : make(cosmetic.id(), spec); + MADE.put(cosmetic.id(), made); + return made; + } + + // --------------------------------------------------------------------------------------------- + // The descriptions + // --------------------------------------------------------------------------------------------- + + private static @Nullable Spec spec(String id) { + return switch (id) { + case "hat.crown" -> { + List boxes = new ArrayList<>(); + // A band round the top of the head, outside the skin's hat layer, its top velvet. + boxes.add(box(-4, -10, -4, 8, 2, 8, 0.6F, Material.GOLD_GEM)); + for (float[] at : new float[][] { + {-4.6F, -4.6F}, + {3.6F, -4.6F}, + {-4.6F, 3.6F}, + {3.6F, 3.6F}, + {-0.5F, -4.6F}, + {-0.5F, 3.6F}, + {-4.6F, -0.5F}, + {3.6F, -0.5F} + }) { + boxes.add(box(at[0], -12.6F, at[1], 1, 2, 1, 0.05F, Material.GOLD)); + } + yield new Spec(Anchor.HEAD, Look.CUTOUT, List.of(new Part("crown", PartPose.ZERO, boxes))); + } + case "hat.halo" -> + new Spec( + Anchor.HEAD, + Look.GLOW, + List.of(new Part( + "ring", + PartPose.offset(0, -12.5F, 0), + List.of( + box(-3, -0.5F, -3.5F, 6, 1, 1, 0, Material.HALO), + box(-3, -0.5F, 2.5F, 6, 1, 1, 0, Material.HALO), + box(-3.5F, -0.5F, -3, 1, 1, 6, 0, Material.HALO), + box(2.5F, -0.5F, -3, 1, 1, 6, 0, Material.HALO))))); + case "hat.top_hat" -> + new Spec( + Anchor.HEAD, + Look.CUTOUT, + List.of(new Part( + "hat", + PartPose.ZERO, + List.of( + box(-5, -9, -5, 10, 1, 10, 0.1F, Material.FELT), + box(-4, -15, -4, 8, 6, 8, -0.5F, Material.FELT_BAND))))); + case "hat.beanie" -> + new Spec( + Anchor.HEAD, + Look.CUTOUT, + List.of(new Part( + "beanie", + PartPose.ZERO, + List.of( + box(-4, -9, -4, 8, 3, 8, 0.7F, Material.KNIT), + box(-1, -12, -1, 2, 2, 2, 0.3F, Material.POM))))); + case "hat.horns" -> new Spec(Anchor.HEAD, Look.CUTOUT, List.of(horn("left", 1), horn("right", -1))); + case "hat.cat_ears" -> new Spec(Anchor.HEAD, Look.CUTOUT, List.of(ear("left", 1), ear("right", -1))); + case "back.angel_wings", "back.bat_wings" -> wings(Look.CUTOUT); + case "back.frost_wings" -> wings(Look.TRANSLUCENT); + case "back.backpack" -> + new Spec( + Anchor.BODY, + Look.CUTOUT, + List.of(new Part( + "pack", + PartPose.ZERO, + List.of( + box(-4, 1, 2, 8, 10, 4, 0, Material.PACK), + box(-3, 5, 6, 6, 4, 1, 0, Material.POCKET))))); + default -> null; + }; + } + + private static Box box(float x, float y, float z, int w, int h, int d, float grow, Material material) { + return new Box(x, y, z, w, h, d, grow, material, false); + } + + private static Part horn(String name, int side) { + return new Part( + name, + PartPose.offsetAndRotation(side * 2.5F, -8, -1, -0.2F, 0, side * 0.45F), + List.of( + box(-1, -3, -1, 2, 3, 2, 0, Material.BONE), + box(-0.5F + side * 0.4F, -5.5F, -0.5F, 1, 3, 1, 0, Material.BONE))); + } + + private static Part ear(String name, int side) { + return new Part( + name, + PartPose.offsetAndRotation(side * 2.6F, -8.2F, -0.5F, 0, 0, side * 0.28F), + List.of( + box(-1.5F, -3, -0.5F, 3, 3, 1, 0, Material.EAR), + box(-0.5F, -4, -0.5F, 1, 1, 1, 0, Material.EAR))); + } + + /** How far back the wings are swept at rest, in radians. */ + private static final float WING_SWEEP = 0.28F; + + /** Two wings, panels with nothing but a front and a back, from the shoulder blades. */ + private static Spec wings(Look look) { + // From the shoulder blades, out past the shoulders and up past them, swept back a little: + // turning the left wing (+x) by a negative yRot takes its tip back (+z), away from the arms. + Part left = new Part( + "left_wing", + PartPose.offsetAndRotation(1, 3, 2.4F, 0, -WING_SWEEP, -0.12F), + List.of(new Box(0, -9, 0, 16, 16, 0, 0, Material.WING, false))); + Part right = new Part( + "right_wing", + PartPose.offsetAndRotation(-1, 3, 2.4F, 0, WING_SWEEP, 0.12F), + List.of(new Box(-16, -9, 0, 16, 16, 0, 0, Material.WING, true))); + return new Spec(Anchor.BODY, look, List.of(left, right)); + } + + // --------------------------------------------------------------------------------------------- + // Baking and painting + // --------------------------------------------------------------------------------------------- + + private static Made make(String id, Spec spec) { + MeshDefinition mesh = new MeshDefinition(); + PartDefinition root = mesh.getRoot(); + NativeImage image = new NativeImage(TEXTURE, TEXTURE, true); + int shelfX = 0; + int shelfY = 0; + int shelfHeight = 0; + for (Part part : spec.parts()) { + CubeListBuilder cubes = CubeListBuilder.create(); + for (Box box : part.boxes()) { + int width = 2 * box.d() + 2 * box.w(); + int height = box.d() + box.h(); + if (shelfX + width > TEXTURE) { + shelfX = 0; + shelfY += shelfHeight; + shelfHeight = 0; + } + int u = shelfX; + int v = shelfY; + shelfX += width; + shelfHeight = Math.max(shelfHeight, height); + cubes.texOffs(u, v).mirror(box.mirror()); + if (box.d() == 0) { + Set sides = EnumSet.of(Direction.NORTH, Direction.SOUTH); + cubes.addBox(box.x(), box.y(), box.z(), box.w(), box.h(), box.d(), sides); + } else { + cubes.addBox(box.x(), box.y(), box.z(), box.w(), box.h(), box.d(), new CubeDeformation(box.grow())); + } + paint(image, id, box, u, v); + } + root.addOrReplaceChild(part.name(), cubes, part.pose()); + } + ModelPart baked = LayerDefinition.create(mesh, TEXTURE, TEXTURE).bakeRoot(); + Identifier texture = Identifier.fromNamespaceAndPath("incari", "cosmetics/" + id.replace('.', '/')); + Minecraft.getInstance().getTextureManager().register(texture, new DynamicTexture(texture::toString, image)); + CosmeticModel model = new CosmeticModel(baked, renderType(spec.look()), id); + return new Made(model, texture, spec.anchor(), spec.look()); + } + + private static java.util.function.Function renderType(Look look) { + // Culled: a wing is a panel whose front and back lie in one plane, and drawn both ways they + // fight for the same depth (and, translucent, swap as their sort changes with the camera). + return switch (look) { + case CUTOUT -> RenderTypes::entityCutoutCull; + case TRANSLUCENT -> RenderTypes::entityTranslucentCull; + case GLOW -> RenderTypes::eyes; + }; + } + + /** Paints a box's six faces where the game's box mapping reads them. */ + private static void paint(NativeImage image, String id, Box box, int u, int v) { + int w = box.w(); + int h = box.h(); + int d = box.d(); + // The game's layout of a box's faces, from (u, v): down and up along the top, then west, + // north (the front), east and south (the back) side by side. + face(image, id, box, 0, u + d, v, w, d); + face(image, id, box, 1, u + d + w, v, w, d); + face(image, id, box, 2, u, v + d, d, h); + face(image, id, box, 3, u + d, v + d, w, h); + face(image, id, box, 4, u + d + w, v + d, d, h); + face(image, id, box, 5, u + 2 * d + w, v + d, w, h); + } + + private static void face(NativeImage image, String id, Box box, int face, int x0, int y0, int width, int height) { + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + int px = x0 + x; + int py = y0 + y; + if (px < TEXTURE && py < TEXTURE) { + image.setPixel(px, py, color(id, box.material(), face, x, y, width, height)); + } + } + } + } + + /** A face's pixel: face 0 and 1 the bottom and top, 3 the front, 5 the back. */ + private static int color(String id, Material material, int face, int x, int y, int width, int height) { + boolean flat = face <= 1; + float row = height <= 1 ? 0 : y / (float) (height - 1); + float grain = CosmeticArt.hash(x, y, face + material.name().length() * 7); + return switch (material) { + case GOLD, GOLD_GEM -> { + if (material == Material.GOLD_GEM && flat) { + yield 0xFF000000 | CosmeticArt.mix(0x8E1B2E, 0x6A1222, grain); + } + if (material == Material.GOLD_GEM && face == 3 && Math.abs(x - (width - 1) / 2.0F) < 1 && y == 0) { + yield 0xFFE0344B; + } + int gold = CosmeticArt.mix(0xFFE58A, 0xD69A1E, flat ? 0.1F : row); + yield 0xFF000000 | (grain < 0.08F ? CosmeticArt.mix(gold, 0xFFFFFF, 0.6F) : gold); + } + case VELVET -> 0xFF000000 | CosmeticArt.mix(0x8E1B2E, 0x6A1222, grain); + case HALO -> 0xFF000000 | CosmeticArt.mix(0xFFF6D2, 0xFFDB7A, grain * 0.6F); + case FELT -> 0xFF000000 | CosmeticArt.mix(0x2A2A33, 0x1A1A20, grain); + case FELT_BAND -> + !flat && y >= height - 2 ? 0xFFC0263A : 0xFF000000 | CosmeticArt.mix(0x2A2A33, 0x1A1A20, grain); + case KNIT -> { + if (!flat && y == height - 1) { + yield 0xFF4F8FC7; + } + int stripe = flat ? (x + y) / 2 : y; + yield (stripe & 1) == 0 ? 0xFF7FC3F2 : 0xFFEAF6FF; + } + case POM -> 0xFF000000 | CosmeticArt.mix(0xFFFFFF, 0xDDE8F2, grain); + case BONE -> 0xFF000000 | CosmeticArt.mix(0xF2E6CC, 0x9C8A6A, flat ? 0.3F : 1 - row); + case EAR -> face == 3 && x > 0 && x < width - 1 && y > 0 ? 0xFFF2A6BC : 0xFF4A4A58; + case PACK -> { + if (face == 1) { + yield 0xFF7FC3F2; + } + boolean seam = x == 0 || y == 0 || x == width - 1 || y == height - 1; + yield seam ? 0xFF3B5B8A : 0xFF000000 | CosmeticArt.mix(0x22385A, 0x1B2D49, grain); + } + case POCKET -> (x == 0 || y == 0 || x == width - 1 || y == height - 1) ? 0xFFA9DCFF : 0xFF2C4A72; + case WING -> { + // The back (south) face has the root on its left; the front shows it mirrored, so + // the two sides of the panel line up. + float sx = (x + 0.5F) / width; + float sy = (y + 0.5F) / height; + yield CosmeticArt.wing(id, face == 5 ? sx : 1 - sx, sy); + } + }; + } + + /** A cosmetic's model: its parts posed from the player's state as it's drawn (halo, wings). */ + static final class CosmeticModel extends Model { + + private final @Nullable ModelPart ring; + private final @Nullable ModelPart leftWing; + private final @Nullable ModelPart rightWing; + + CosmeticModel(ModelPart root, java.util.function.Function renderType, String id) { + super(root, renderType); + this.ring = id.equals("hat.halo") ? root.getChild("ring") : null; + boolean wings = id.endsWith("_wings"); + this.leftWing = wings ? root.getChild("left_wing") : null; + this.rightWing = wings ? root.getChild("right_wing") : null; + } + + @Override + public void setupAnim(AvatarRenderState state) { + super.setupAnim(state); + float age = state.ageInTicks; + ModelPart halo = ring; + if (halo != null) { + halo.yRot = age * 0.04F; + halo.y += (float) Math.sin(age * 0.08F) * 0.4F; + } + ModelPart left = leftWing; + ModelPart right = rightWing; + if (left != null && right != null) { + // Swept further back by a slow beat at rest, folded back while sneaking, spread while + // gliding; never swept forward far enough to reach the arms. + float beat = (float) Math.sin(age * 0.12F) * 0.08F + 0.08F; + float fold = state.isCrouching ? 0.25F : 0; + float spread = state.isFallFlying ? 0.2F : 0; + float sweep = Math.max(-WING_SWEEP + 0.1F, beat + fold - spread); + left.yRot -= sweep; + right.yRot += sweep; + } + } + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/cosmetics/CosmeticTextures.java b/incari-client/files/client/src/main/java/incari/client/cosmetics/CosmeticTextures.java new file mode 100644 index 0000000..dc8a1f3 --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/cosmetics/CosmeticTextures.java @@ -0,0 +1,127 @@ +package incari.client.cosmetics; + +import com.mojang.blaze3d.platform.NativeImage; +import incari.online.Cosmetic; +import java.util.HashMap; +import java.util.Map; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.texture.DynamicTexture; +import net.minecraft.core.ClientAsset; +import net.minecraft.resources.Identifier; +import net.minecraft.util.Util; +import org.jspecify.annotations.Nullable; + +/** + * The capes' textures and the wardrobe's icons (ADR 0061), painted by {@link CosmeticArt} the first + * time each is needed. A moving cape is painted again ten times a second while something has drawn + * it in the last two seconds, and left as it is otherwise: a cape nobody sees costs nothing. + * + *

Render thread (the game's thread in Incari's builds). + */ +final class CosmeticTextures { + + /** How long a moving cape goes on moving after it was last drawn. */ + private static final long IDLE_MILLIS = 2_000; + + /** A cape's texture, and when it was last drawn. */ + private static final class Cape { + final Identifier id; + final ClientAsset.Texture asset; + final DynamicTexture texture; + final int[] pixels = new int[CosmeticArt.CAPE_WIDTH * CosmeticArt.CAPE_HEIGHT]; + final boolean animated; + long lastDrawn; + + Cape(Identifier id, DynamicTexture texture, boolean animated) { + this.id = id; + this.asset = new ClientAsset.ResourceTexture(id, id); + this.texture = texture; + this.animated = animated; + } + } + + private static final Map CAPES = new HashMap<>(); + private static final Map ICONS = new HashMap<>(); + private static final long START = Util.getMillis(); + + private CosmeticTextures() {} + + /** The cape's texture, as a skin's cape: made now if it's the first time. */ + static ClientAsset.Texture cape(Cosmetic cape) { + Cape made = capeTexture(cape); + made.lastDrawn = Util.getMillis(); + return made.asset; + } + + /** The cape's texture by id, for the wardrobe's cards (which show its outer side). */ + static Identifier capeId(Cosmetic cape) { + Cape made = capeTexture(cape); + made.lastDrawn = Util.getMillis(); + return made.id; + } + + private static Cape capeTexture(Cosmetic cape) { + Cape made = CAPES.get(cape.id()); + if (made == null) { + Identifier id = Identifier.fromNamespaceAndPath( + "incari", "cosmetics/" + cape.id().replace('.', '/')); + NativeImage image = new NativeImage(CosmeticArt.CAPE_WIDTH, CosmeticArt.CAPE_HEIGHT, true); + DynamicTexture texture = new DynamicTexture(id::toString, image); + made = new Cape(id, texture, CosmeticArt.animated(cape.id())); + paint(cape.id(), made); + texture.upload(); + Minecraft.getInstance().getTextureManager().register(id, texture); + CAPES.put(cape.id(), made); + } + return made; + } + + /** Once a client tick: moving capes drawn lately are painted again, every other tick. */ + static void tick(long tick) { + if ((tick & 1) != 0 || CAPES.isEmpty()) { + return; + } + long now = Util.getMillis(); + for (Map.Entry each : CAPES.entrySet()) { + Cape cape = each.getValue(); + if (cape.animated && now - cape.lastDrawn < IDLE_MILLIS) { + paint(each.getKey(), cape); + cape.texture.upload(); + } + } + } + + private static void paint(String id, Cape cape) { + CosmeticArt.cape(id, (Util.getMillis() - START) / 1000.0F, cape.pixels); + NativeImage image = cape.texture.getPixels(); + for (int y = 0; y < CosmeticArt.CAPE_HEIGHT; y++) { + for (int x = 0; x < CosmeticArt.CAPE_WIDTH; x++) { + image.setPixel(x, y, cape.pixels[y * CosmeticArt.CAPE_WIDTH + x]); + } + } + } + + /** A hat's or back cosmetic's icon for its wardrobe card; null for one with none. */ + static @Nullable Identifier icon(Cosmetic cosmetic) { + if (cosmetic.slot() != Cosmetic.Slot.HAT && cosmetic.slot() != Cosmetic.Slot.BACK) { + return null; + } + Identifier id = ICONS.get(cosmetic.id()); + if (id == null) { + int[] pixels = new int[CosmeticArt.ICON * CosmeticArt.ICON]; + CosmeticArt.icon(cosmetic.id(), pixels); + NativeImage image = new NativeImage(CosmeticArt.ICON, CosmeticArt.ICON, true); + for (int y = 0; y < CosmeticArt.ICON; y++) { + for (int x = 0; x < CosmeticArt.ICON; x++) { + image.setPixel(x, y, pixels[y * CosmeticArt.ICON + x]); + } + } + id = Identifier.fromNamespaceAndPath( + "incari", "cosmetics/icon/" + cosmetic.id().replace('.', '/')); + Identifier label = id; + Minecraft.getInstance().getTextureManager().register(id, new DynamicTexture(label::toString, image)); + ICONS.put(cosmetic.id(), id); + } + return id; + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/cosmetics/Cosmetics.java b/incari-client/files/client/src/main/java/incari/client/cosmetics/Cosmetics.java new file mode 100644 index 0000000..51e8a86 --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/cosmetics/Cosmetics.java @@ -0,0 +1,421 @@ +package incari.client.cosmetics; + +import incari.client.IncariKeys; +import incari.client.online.IncariOnline; +import incari.client.settings.ClientSettings; +import incari.framework.online.IncariPlayer; +import incari.framework.online.Online; +import incari.online.Cosmetic; +import incari.online.Loadout; +import incari.online.OnlineService; +import incari.online.Wardrobe; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.minecraft.client.CameraType; +import net.minecraft.client.Minecraft; +import net.minecraft.client.model.player.PlayerModel; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.ClientPacketListener; +import net.minecraft.client.multiplayer.PlayerInfo; +import net.minecraft.client.player.AbstractClientPlayer; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.client.renderer.entity.RenderLayerParent; +import net.minecraft.client.renderer.entity.layers.RenderLayer; +import net.minecraft.client.renderer.entity.state.AvatarRenderState; +import net.minecraft.core.ClientAsset; +import net.minecraft.core.particles.ParticleTypes; +import net.minecraft.network.chat.Component; +import net.minecraft.util.RandomSource; +import net.minecraft.world.entity.Avatar; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.entity.player.PlayerSkin; +import org.jspecify.annotations.Nullable; + +/** + * Cosmetics in the world (ADR 0061): what each player wears and plays, from the player's own + * wardrobe or, for others, the online service, put on each player's render state for the layers to + * draw. Others' are drawn only for Incari players the service named, and only while + * {@link Wardrobe#showOthers} is on. + * + *

The game calls in from six hooks: the player renderer's layers ({@link #layer}) and its + * render state ({@link #extract}), the player model's pose ({@link #pose}), the tab list's names + * ({@link #tabListName}), chat ({@link #chatMessage}), and once a tick ({@link #tick}): emotes start and end, trails are left, + * moving capes are painted. + * + *

Render thread (the game's thread in Incari's builds). {@link #extract} runs for every player + * every frame: a lookup, and nothing made unless what someone wears changed. + */ +public final class Cosmetics { + + /** Trails are left only by players this near. */ + private static final double TRAIL_DISTANCE = 32; + + /** At most this many trail particles a tick, however many players are about. */ + private static final int TRAIL_BUDGET = 12; + + /** + * An emote playing: which, the player's tick it started on (its pose counts from it), and the + * client tick it ends on. The end is in client ticks because a respawn or dimension change makes + * a new player, whose ticks restart at 0. + */ + private record Play(Cosmetic emote, int startTick, long endsAt) { + Play(Cosmetic emote, int startTick) { + this(emote, startTick, ticks + Emotes.duration(emote)); + } + } + + /** What another player was last seen wearing and playing, and what that came to. */ + private record Seen(List source, @Nullable Play play, Worn worn) {} + + private static final Map OTHERS = new HashMap<>(); + private static final Map PLAYS = new HashMap<>(); + + /** Skins with a cosmetic cape, by cape and by the skin they were made from. */ + private static final Map> DRESSED = new HashMap<>(); + + private static Worn self = Worn.NONE; + private static Loadout selfLoadout = Loadout.EMPTY; + private static @Nullable Play selfPlay; + + /** The camera to go back to once the player's own emote ends; null when it wasn't moved. */ + private static @Nullable CameraType cameraBefore; + + private static long ticks; + + private Cosmetics() {} + + // --------------------------------------------------------------------------------------------- + // The game's hooks + // --------------------------------------------------------------------------------------------- + + /** {@code AvatarRenderer}'s constructor: the layer that draws hats and back cosmetics. */ + public static RenderLayer layer( + RenderLayerParent parent) { + return new CosmeticsLayer(parent); + } + + /** {@code AvatarRenderer.extractRenderState}'s end: what this player wears, on their state. */ + public static void extract(Avatar avatar, AvatarRenderState state) { + if (avatar instanceof AbstractClientPlayer player) { + Worn worn = wornBy(player); + if (worn != Worn.NONE) { + dress(state, worn, player.getUUID()); + } + // Incari's badge (ADR 0062): other Incari players who show it, while the player wants it. + if (state.nameTag != null && !(player instanceof LocalPlayer) && ClientSettings.SHOW_BADGES.get()) { + IncariPlayer incari = IncariOnline.service().player(player.getUUID()); + if (incari != null && incari.badge()) { + state.nameTag = Badges.badged(player.getUUID(), state.nameTag); + } + } + } + } + + /** + * {@code PlayerTabOverlay}'s list: the player {@code id}'s {@code name} with Incari's badge before + * it, as their name tag has it (ADR 0062), or {@code name}. The player's own name has it too while + * they show others they use Incari. + */ + public static Component tabListName(UUID id, Component name) { + OnlineService online = IncariOnline.service(); + if (online.status() != Online.Status.SIGNED_IN) { + return name; + } + return showsBadge(online, id) ? Badges.badgedInTabList(id, name) : name; + } + + /** + * {@code ChatComponent.addMessage}: {@code message} with Incari's badge before the first mention + * of each Incari player in it, as the tab list has it, or {@code message}. Players are found by + * their name in the tab list, since most servers send chat as plain text with no sender. + */ + public static Component chatMessage(Component message) { + OnlineService online = IncariOnline.service(); + ClientPacketListener connection = Minecraft.getInstance().getConnection(); + if (online.status() != Online.Status.SIGNED_IN || connection == null) { + return message; + } + return Badges.badgedInChat(message, name -> { + PlayerInfo info = connection.getPlayerInfo(name); + return info != null && showsBadge(online, info.getProfile().id()); + }); + } + + /** Whether the player {@code id}'s badge shows: theirs if they let it, the player's own if they do. */ + private static boolean showsBadge(OnlineService online, UUID id) { + LocalPlayer me = Minecraft.getInstance().player; + if (me != null && me.getUUID().equals(id)) { + return online.showsBadge(); + } + IncariPlayer incari = online.player(id); + return incari != null && incari.badge() && ClientSettings.SHOW_BADGES.get(); + } + + /** {@code PlayerModel.setupAnim}'s end: an emote's pose over the game's. */ + public static void pose(PlayerModel model, AvatarRenderState state) { + Emotes.pose(model, state); + } + + /** Whether the player wears any cosmetic: the title screen's player then shows them. */ + public static boolean wearsAny() { + return !IncariOnline.service().wardrobe().worn().isEmpty(); + } + + /** What the player wears. */ + public static Loadout ownLoadout() { + return IncariOnline.service().wardrobe().worn(); + } + + /** The player's {@code name} in their name tag cosmetic, or plain. */ + public static Component ownName(String name) { + Cosmetic nametag = ownLoadout().in(Cosmetic.Slot.NAMETAG); + return nametag == null ? Component.literal(name) : NameTags.styled(name, nametag); + } + + /** The emote {@code state}'s player is playing, or null (the smoke tests' check). */ + public static @Nullable Cosmetic emoteOf(AvatarRenderState state) { + return state.incariWorn.emote; + } + + /** What {@code state} carries. */ + static Worn worn(AvatarRenderState state) { + return state.incariWorn; + } + + /** + * Puts {@code worn} on {@code state}: for the layers, the cape as the skin's own, and the name tag + * styled. The wardrobe's preview dresses its state the same way. + */ + static void dress(AvatarRenderState state, Worn worn, UUID id) { + state.incariWorn = worn; + Cosmetic cape = worn.cape; + if (cape != null) { + state.skin = withCape(state.skin, cape); + } + Cosmetic back = worn.back; + if (back != null && back.id().equals("back.backpack")) { + // A backpack and a cape would go through each other. + state.showCape = false; + } + Cosmetic nametag = worn.nametag; + if (nametag != null && state.nameTag != null) { + state.nameTag = NameTags.style(id, state.nameTag, nametag); + } + } + + private static PlayerSkin withCape(PlayerSkin skin, Cosmetic cape) { + ClientAsset.Texture texture = CosmeticTextures.cape(cape); + Map bySkin = DRESSED.computeIfAbsent(cape, key -> new HashMap<>()); + PlayerSkin dressed = bySkin.get(skin); + if (dressed == null) { + if (bySkin.size() > 256) { + bySkin.clear(); + } + // The elytra matches the cape, as it does with the game's capes. + dressed = new PlayerSkin(skin.body(), texture, texture, skin.model(), skin.secure()); + bySkin.put(skin, dressed); + } + return dressed; + } + + // --------------------------------------------------------------------------------------------- + // Who wears what + // --------------------------------------------------------------------------------------------- + + @SuppressWarnings("ReferenceEquality") // the same loadout, list and play objects, not equal ones + private static Worn wornBy(AbstractClientPlayer player) { + UUID id = player.getUUID(); + OnlineService online = IncariOnline.service(); + Wardrobe wardrobe = online.wardrobe(); + Play play = PLAYS.get(id); + if (player instanceof LocalPlayer) { + Loadout loadout = wardrobe.worn(); + if (loadout != selfLoadout || play != selfPlay) { + selfLoadout = loadout; + selfPlay = play; + self = loadout.isEmpty() && play == null + ? Worn.NONE + : new Worn(loadout, play == null ? null : play.emote(), play == null ? 0 : play.startTick()); + } + return self; + } + if (!wardrobe.showOthers()) { + return Worn.NONE; + } + IncariPlayer incari = online.player(id); + if (incari == null && play == null) { + return Worn.NONE; + } + List source = incari == null ? List.of() : incari.cosmetics(); + Seen seen = OTHERS.get(id); + if (seen == null || seen.source() != source || seen.play() != play) { + Loadout loadout = Loadout.of(source); + Worn worn = loadout.isEmpty() && play == null + ? Worn.NONE + : new Worn(loadout, play == null ? null : play.emote(), play == null ? 0 : play.startTick()); + seen = new Seen(source, play, worn); + OTHERS.put(id, seen); + } + return seen.worn(); + } + + // --------------------------------------------------------------------------------------------- + // Emotes + // --------------------------------------------------------------------------------------------- + + /** + * The player plays {@code emote} (the emote wheel): the camera turns to face them while it plays, + * and Incari players on the server see it too. False if it can't play now (one every two + * seconds, and only in a world). + */ + public static boolean playEmote(Cosmetic emote) { + Minecraft minecraft = Minecraft.getInstance(); + LocalPlayer player = minecraft.player; + if (player == null || !IncariOnline.service().playEmote(emote)) { + return false; + } + PLAYS.put(player.getUUID(), new Play(emote, player.tickCount)); + if (minecraft.options.getCameraType() == CameraType.FIRST_PERSON) { + cameraBefore = CameraType.FIRST_PERSON; + minecraft.options.setCameraType(CameraType.THIRD_PERSON_FRONT); + } + return true; + } + + private static void emotesEnded(Minecraft minecraft) { + CameraType before = cameraBefore; + cameraBefore = null; + // Unless the player moved the camera themselves meanwhile. + if (before != null && minecraft.options.getCameraType() == CameraType.THIRD_PERSON_FRONT) { + minecraft.options.setCameraType(before); + } + } + + // --------------------------------------------------------------------------------------------- + // Each tick + // --------------------------------------------------------------------------------------------- + + /** From {@code IncariTicks}, after the online service's tick. */ + public static void tick(Minecraft minecraft) { + ticks++; + CosmeticTextures.tick(ticks); + OnlineService online = IncariOnline.service(); + List played = online.takeEmotes(); + ClientLevel level = minecraft.level; + if (level == null) { + if (!PLAYS.isEmpty() || !OTHERS.isEmpty()) { + PLAYS.clear(); + OTHERS.clear(); + NameTags.clear(); + Badges.clear(); + } + // Left the world mid-emote: the camera goes back now, not with the next world. + emotesEnded(minecraft); + return; + } + // The wheel opens with its key over the game, not over another screen. + while (IncariKeys.EMOTE_WHEEL.consumeClick()) { + if (minecraft.gui.screen() == null && minecraft.player != null) { + minecraft.gui.setScreen(new EmoteWheelScreen()); + } + } + boolean showOthers = online.wardrobe().showOthers(); + for (OnlineService.PlayedEmote each : played) { + Player player = level.getPlayerByUUID(each.player()); + if (player != null && showOthers) { + PLAYS.put(each.player(), new Play(each.emote(), player.tickCount)); + } + } + endEmotes(minecraft, level, showOthers); + trails(minecraft, level); + if (ticks % 200 == 0) { + OTHERS.keySet().removeIf(id -> level.getPlayerByUUID(id) == null); + } + } + + private static void endEmotes(Minecraft minecraft, ClientLevel level, boolean showOthers) { + LocalPlayer me = minecraft.player; + boolean mineEnded = false; + for (Iterator> each = PLAYS.entrySet().iterator(); each.hasNext(); ) { + Map.Entry entry = each.next(); + Player player = level.getPlayerByUUID(entry.getKey()); + Play play = entry.getValue(); + boolean mine = me != null && entry.getKey().equals(me.getUUID()); + boolean over = player == null + || ticks >= play.endsAt() + || (!mine && !showOthers) + // Moving cuts an emote short: the player's own by their keys, others' by their legs. + || ((me != null && mine) ? moving(me) : player.walkAnimation.speed() > 0.35F); + if (over) { + each.remove(); + mineEnded |= mine; + } + } + if (mineEnded || (cameraBefore != null && (me == null || !PLAYS.containsKey(me.getUUID())))) { + emotesEnded(minecraft); + } + } + + private static boolean moving(LocalPlayer player) { + return player.input.getMoveVector().lengthSquared() > 0 + || player.input.keyPresses.jump() + || player.isSwinging(); + } + + private static void trails(Minecraft minecraft, ClientLevel level) { + if ((ticks & 1) != 0) { + return; + } + LocalPlayer me = minecraft.player; + if (me == null) { + return; + } + int left = TRAIL_BUDGET; + RandomSource random = level.getRandom(); + for (AbstractClientPlayer player : level.players()) { + if (left <= 0) { + break; + } + Cosmetic trail = wornBy(player).trail; + if (trail == null || player.isInvisible() || player.isSpectator()) { + continue; + } + if (player.distanceToSqr(me) > TRAIL_DISTANCE * TRAIL_DISTANCE) { + continue; + } + double dx = player.getX() - player.xo; + double dy = player.getY() - player.yo; + double dz = player.getZ() - player.zo; + if (dx * dx + dy * dy + dz * dz < 0.0004) { + continue; + } + // Hearts are big: fewer of them. + if (trail.id().equals("trail.hearts") && (ticks / 2 + player.getId()) % 3 != 0) { + continue; + } + double x = player.getX() + (random.nextDouble() - 0.5) * 0.5; + double y = player.getY() + 0.1 + random.nextDouble() * 0.2; + double z = player.getZ() + (random.nextDouble() - 0.5) * 0.5; + switch (trail.id()) { + case "trail.snow" -> level.addParticle(ParticleTypes.SNOWFLAKE, x, y, z, 0, 0.02, 0); + case "trail.hearts" -> level.addParticle(ParticleTypes.HEART, x, y + 0.3, z, 0, 0, 0); + case "trail.sparkles" -> + level.addParticle( + ParticleTypes.END_ROD, + x, + y + 0.2, + z, + (random.nextDouble() - 0.5) * 0.02, + 0.02, + (random.nextDouble() - 0.5) * 0.02); + // A note's color is its first speed (a pitch, 0 to 1). + case "trail.notes" -> level.addParticle(ParticleTypes.NOTE, x, y + 0.4, z, random.nextDouble(), 0, 0); + default -> {} + } + left--; + } + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/cosmetics/CosmeticsLayer.java b/incari-client/files/client/src/main/java/incari/client/cosmetics/CosmeticsLayer.java new file mode 100644 index 0000000..7701289 --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/cosmetics/CosmeticsLayer.java @@ -0,0 +1,113 @@ +package incari.client.cosmetics; + +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.math.Axis; +import incari.online.Cosmetic; +import net.minecraft.client.model.player.PlayerModel; +import net.minecraft.client.renderer.SubmitNodeCollector; +import net.minecraft.client.renderer.entity.LivingEntityRenderer; +import net.minecraft.client.renderer.entity.RenderLayerParent; +import net.minecraft.client.renderer.entity.layers.RenderLayer; +import net.minecraft.client.renderer.entity.state.AvatarRenderState; +import net.minecraft.core.component.DataComponents; +import net.minecraft.util.Mth; +import org.jspecify.annotations.Nullable; + +/** + * Draws a player's hat and back cosmetic (ADR 0061), from what their render state carries ({@link + * Worn}). The cape is the game's own cape layer's, with the cosmetic's texture as the skin's cape + * ({@link Cosmetics#dress}), so it moves as capes do. + * + *

A hat hides under a helmet (the halo floats above one); a back cosmetic hides under an elytra, + * stands off a chestplate and hangs behind a cape. Nothing is drawn for an invisible player, or past {@link + * #MAX_DISTANCE} blocks, where a hat is a pixel or two. Render thread; per player per frame, so + * nothing here allocates. + */ +final class CosmeticsLayer extends RenderLayer { + + /** Past this, worn models aren't drawn. */ + static final double MAX_DISTANCE = 48; + + /** The cape's top edge from the body's pivot, in blocks: the body's back. */ + private static final float CAPE_TOP = 2.0F / 16.0F; + + /** How far a back cosmetic moves back to clear a cape: its pixel, and a gap. */ + private static final float BEHIND_CAPE = 1.0F / 16.0F; + + CosmeticsLayer(RenderLayerParent parent) { + super(parent); + } + + @Override + public void submit( + PoseStack poseStack, + SubmitNodeCollector submitNodeCollector, + int lightCoords, + AvatarRenderState state, + float yRot, + float xRot) { + Worn worn = Cosmetics.worn(state); + if (worn.isEmpty() || state.isInvisible || state.distanceToCameraSq > MAX_DISTANCE * MAX_DISTANCE) { + return; + } + Cosmetic hat = worn.hat; + if (hat != null && (state.headEquipment.isEmpty() || hat.id().equals("hat.halo"))) { + draw(poseStack, submitNodeCollector, lightCoords, state, CosmeticModels.of(hat), true); + } + Cosmetic back = worn.back; + if (back != null && !state.chestEquipment.has(DataComponents.GLIDER)) { + draw(poseStack, submitNodeCollector, lightCoords, state, CosmeticModels.of(back), false); + } + } + + private void draw( + PoseStack poseStack, + SubmitNodeCollector submitNodeCollector, + int lightCoords, + AvatarRenderState state, + CosmeticModels.@Nullable Made made, + boolean onHead) { + if (made == null) { + return; + } + PlayerModel parent = getParentModel(); + poseStack.pushPose(); + parent.root().translateAndRotate(poseStack); + if (onHead) { + parent.head.translateAndRotate(poseStack); + } else { + parent.body.translateAndRotate(poseStack); + if (!state.chestEquipment.isEmpty()) { + // A chestplate stands a pixel out from the body. + poseStack.translate(0.0F, 0.0F, 0.0625F); + } + if (state.showCape && state.skin.cape() != null) { + behindCape(poseStack, state); + } + } + boolean glow = made.look() == CosmeticModels.Look.GLOW; + submitNodeCollector.submitModel( + made.model(), + state, + poseStack, + made.model().renderType(made.texture()), + glow ? 0xF000F0 : lightCoords, + LivingEntityRenderer.getOverlayCoords(state, 0.0F), + state.outlineColor); + poseStack.popPose(); + } + + /** + * Over a cape, a back cosmetic hangs behind it and swings out with it, as the cape layer turns + * the cape ({@code PlayerCapeModel.setupAnim}): otherwise the cape, which hangs from the + * shoulders a pixel thick and swings back as the player moves, cuts through it. (A backpack + * hides the cape instead, {@link Cosmetics#dress}.) + */ + private static void behindCape(PoseStack poseStack, AvatarRenderState state) { + float swing = (6.0F + state.capeLean / 2.0F + state.capeFlap) * Mth.DEG_TO_RAD; + // About the cape's top edge, at the body's back (z = 2 pixels). + poseStack.translate(0.0F, 0.0F, CAPE_TOP); + poseStack.rotate(Axis.XP, swing); + poseStack.translate(0.0F, 0.0F, -CAPE_TOP + BEHIND_CAPE); + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/cosmetics/EmoteWheelScreen.java b/incari-client/files/client/src/main/java/incari/client/cosmetics/EmoteWheelScreen.java new file mode 100644 index 0000000..7b08b0b --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/cosmetics/EmoteWheelScreen.java @@ -0,0 +1,144 @@ +package incari.client.cosmetics; + +import incari.client.IncariKeys; +import incari.client.online.IncariOnline; +import incari.client.ui.Circles; +import incari.client.ui.Look; +import incari.client.ui.RoundRects; +import incari.client.ui.Theme; +import incari.online.Cosmetic; +import java.util.List; +import net.minecraft.client.gui.GuiGraphicsExtractor; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.input.KeyEvent; +import net.minecraft.client.input.MouseButtonEvent; +import net.minecraft.network.chat.Component; +import org.jspecify.annotations.Nullable; + +/** + * The emote wheel (ADR 0061): held open by its key (G), the player's emotes round a circle; the one + * the pointer points toward plays when the key is let go, or when it's clicked. Escape, or letting + * go with the pointer in the middle, plays nothing. A quick tap of the key, let go before the wheel + * opened, leaves it open to click an emote; the key again closes it. The game goes on behind it. + */ +public final class EmoteWheelScreen extends Screen { + + private static final float RADIUS = 78; + private static final float INNER = 24; + private static final float LABEL_RADIUS = 54; + + private final List emotes; + private int hovered = -1; + + /** + * Whether the key was let go before the wheel opened (it opens on the tick after the press): its + * release is gone, so the wheel waits for a click instead. + */ + private final boolean tapped; + + public EmoteWheelScreen() { + super(Component.literal("Emotes")); + this.emotes = IncariOnline.service().wardrobe().emotes(); + this.tapped = !IncariKeys.EMOTE_WHEEL.isDown(); + } + + @Override + public void extractRenderState(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) { + float cx = width / 2.0F; + float cy = height / 2.0F; + hovered = pointedAt(mouseX, mouseY); + Circles.disc(graphics, cx, cy, RADIUS, Look.normal() ? 0xB0101822 : Theme.GLASS_SOLID); + Circles.ring(graphics, cx, cy, RADIUS, 1, Theme.GLASS_EDGE); + Circles.ring(graphics, cx, cy, INNER, 1, Theme.GLASS_EDGE); + int count = emotes.size(); + for (int i = 0; i < count; i++) { + double angle = angle(i, count); + int x = Math.round(cx + (float) Math.sin(angle) * LABEL_RADIUS); + int y = Math.round(cy - (float) Math.cos(angle) * LABEL_RADIUS); + Component name = Component.literal(emotes.get(i).name()); + int textWidth = font.width(name); + boolean on = i == hovered; + if (on) { + RoundRects.fill(graphics, x - textWidth / 2 - 6, y - 8, textWidth + 12, 16, 8, Theme.ACCENT); + } + graphics.text(font, name, x - textWidth / 2, y - 4, on ? Theme.ON_ACCENT : Theme.TEXT, false); + } + Component middle = hovered >= 0 + ? Component.literal(emotes.get(hovered).name()) + : Component.literal(count == 0 ? "No emotes" : "Emotes"); + graphics.centeredText(font, middle, (int) cx, (int) cy - 4, hovered >= 0 ? Theme.ACCENT : Theme.MUTED); + String key = IncariKeys.EMOTE_WHEEL.getTranslatedKeyMessage().getString(); + Component hint = Component.literal( + tapped + ? "Click an emote to play it, or press " + key + " to close" + : "Release " + key + " or click to play"); + graphics.centeredText(font, hint, (int) cx, (int) (cy + RADIUS + 10), Theme.MUTED); + } + + /** The angle of emote {@code i} of {@code count}, clockwise from straight up. */ + private static double angle(int i, int count) { + return Math.PI * 2 * i / Math.max(1, count); + } + + /** The emote the pointer points toward, or -1 in the middle or with none. */ + private int pointedAt(double mouseX, double mouseY) { + double dx = mouseX - width / 2.0; + double dy = mouseY - height / 2.0; + if (emotes.isEmpty() || dx * dx + dy * dy < INNER * INNER) { + return -1; + } + double angle = Math.atan2(dx, -dy); + if (angle < 0) { + angle += Math.PI * 2; + } + double slice = Math.PI * 2 / emotes.size(); + return (int) Math.round(angle / slice) % emotes.size(); + } + + private void play(int index) { + onClose(); + if (index >= 0 && index < emotes.size()) { + Cosmetics.playEmote(emotes.get(index)); + } + } + + @Override + public boolean keyPressed(KeyEvent event) { + if (tapped && IncariKeys.EMOTE_WHEEL.matches(event)) { + onClose(); + return true; + } + return super.keyPressed(event); + } + + @Override + public boolean keyReleased(KeyEvent event) { + if (!tapped && IncariKeys.EMOTE_WHEEL.matches(event)) { + play(hovered); + return true; + } + return super.keyReleased(event); + } + + @Override + public boolean mouseClicked(MouseButtonEvent event, boolean doubleClick) { + play(pointedAt(event.x(), event.y())); + return true; + } + + @Override + public boolean isPauseScreen() { + return false; + } + + @Override + public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) { + // The world stays as it is behind the wheel: the player is in the middle of a game. + } + + /** The emote under the pointer, for tests. */ + @Nullable + Cosmetic hovered() { + return hovered >= 0 && hovered < emotes.size() ? emotes.get(hovered) : null; + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/cosmetics/Emotes.java b/incari-client/files/client/src/main/java/incari/client/cosmetics/Emotes.java new file mode 100644 index 0000000..d89b483 --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/cosmetics/Emotes.java @@ -0,0 +1,103 @@ +package incari.client.cosmetics; + +import incari.online.Cosmetic; +import net.minecraft.client.model.geom.ModelPart; +import net.minecraft.client.model.player.PlayerModel; +import net.minecraft.client.renderer.entity.state.AvatarRenderState; +import net.minecraft.util.Mth; + +/** + * Emotes as the player model plays them (ADR 0061): each a pose for the arms and head, eased in and + * out, some moving as they go (a wave, a clap). Laid over the game's own pose at the end of {@code + * PlayerModel.setupAnim}, so the legs still walk if the player does, and sleeves, hats and capes + * follow the parts they hang from. + * + *

Render thread; the pose is set while the model is drawn, so nothing here allocates. + */ +final class Emotes { + + /** Ticks an emote takes to ease in, and out. */ + private static final float EASE = 4; + + private Emotes() {} + + /** How long {@code emote} plays, in ticks. */ + static int duration(Cosmetic emote) { + return switch (emote.id()) { + case "emote.wave", "emote.clap", "emote.facepalm" -> 50; + case "emote.cheer" -> 45; + case "emote.salute", "emote.bow" -> 40; + case "emote.shrug" -> 35; + case "emote.dab" -> 30; + default -> 40; + }; + } + + /** {@code PlayerModel.setupAnim}'s hook: the emote's pose over the game's, if one is playing. */ + static void pose(PlayerModel model, AvatarRenderState state) { + Worn worn = Cosmetics.worn(state); + Cosmetic emote = worn.emote; + if (emote == null) { + return; + } + float elapsed = state.ageInTicks - worn.emoteStart; + int duration = duration(emote); + if (elapsed < 0 || elapsed >= duration) { + return; + } + float weight = Math.min(1, Math.min(elapsed / EASE, (duration - elapsed) / EASE)); + float e = elapsed; + ModelPart head = model.head; + ModelPart right = model.rightArm; + ModelPart left = model.leftArm; + switch (emote.id()) { + case "emote.wave" -> arm(right, weight, 0, 0, 2.6F + 0.35F * Mth.sin(e * 0.6F)); + case "emote.clap" -> { + float swing = 0.25F + 0.3F * (0.5F + 0.5F * Mth.sin(e * 0.9F)); + arm(right, weight, -1.35F, -swing, 0); + arm(left, weight, -1.35F, swing, 0); + } + case "emote.cheer" -> { + float bounce = 0.15F * Mth.sin(e * 0.5F); + arm(right, weight, -2.9F + bounce, 0, 0.35F); + arm(left, weight, -2.9F - bounce, 0, -0.35F); + turn(head, weight, -0.25F, 0, 0); + } + case "emote.salute" -> { + arm(right, weight, -2.3F, -0.55F, 0.1F); + turn(head, weight, -0.05F, 0, 0); + } + case "emote.facepalm" -> { + arm(right, weight, -2.1F, -0.75F, 0); + turn(head, weight, 0.35F, 0, 0); + } + case "emote.shrug" -> { + float lift = 0.1F * Mth.sin(e * 0.4F); + arm(right, weight, -0.45F, 0, 0.75F + lift); + arm(left, weight, -0.45F, 0, -0.75F - lift); + turn(head, weight, -0.1F, 0, 0.12F * Mth.sin(e * 0.3F)); + } + case "emote.dab" -> { + arm(right, weight, -1.6F, -1.0F, 0); + arm(left, weight, -0.4F, 0, -2.3F); + turn(head, weight, 0.55F, 0.6F, 0); + } + case "emote.bow" -> { + arm(right, weight, -0.9F, -0.6F, 0); + arm(left, weight, 0.3F, 0, 0); + turn(head, weight, 0.75F, 0, 0); + } + default -> {} + } + } + + private static void arm(ModelPart arm, float weight, float xRot, float yRot, float zRot) { + turn(arm, weight, xRot, yRot, zRot); + } + + private static void turn(ModelPart part, float weight, float xRot, float yRot, float zRot) { + part.xRot = Mth.lerp(weight, part.xRot, xRot); + part.yRot = Mth.lerp(weight, part.yRot, yRot); + part.zRot = Mth.lerp(weight, part.zRot, zRot); + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/cosmetics/NameTags.java b/incari-client/files/client/src/main/java/incari/client/cosmetics/NameTags.java new file mode 100644 index 0000000..e00f8ec --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/cosmetics/NameTags.java @@ -0,0 +1,83 @@ +package incari.client.cosmetics; + +import incari.online.Cosmetic; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.network.chat.Style; + +/** + * Name tag cosmetics (ADR 0061): the name over a player's head in a color, or fading from one color + * to another across it. Only where the server leaves the name uncolored: a team's or a rank's color + * means something in the game, and wins. + * + *

Render thread. Each player's last name tag and its styled copy are kept, so a name that doesn't + * change is styled once. + */ +public final class NameTags { + + /** Each player's last name tag in, and what it became. */ + private record Styled(Component from, Cosmetic style, Component to) {} + + private static final Map LAST = new HashMap<>(); + + private NameTags() {} + + /** The colors of {@code style}: one for a plain color, two for a fade. */ + public static int[] colors(Cosmetic style) { + return switch (style.id()) { + case "nametag.ice" -> new int[] {0xA9DCFF}; + case "nametag.gold" -> new int[] {0xFFD36A}; + case "nametag.mint" -> new int[] {0x8FE3B0}; + case "nametag.rose" -> new int[] {0xFF9BB8}; + case "nametag.violet" -> new int[] {0xC6A2FF}; + case "nametag.frost" -> new int[] {0xFFFFFF, 0x7FC8FF}; + case "nametag.sunset" -> new int[] {0xFFB36A, 0xFF6FA8}; + case "nametag.aurora" -> new int[] {0x6AF2B0, 0xA06CFF}; + default -> new int[] {0xFFFFFF}; + }; + } + + /** {@code tag} styled for the player {@code id}, or {@code tag} itself where the server colored it. */ + static Component style(UUID id, Component tag, Cosmetic style) { + Styled last = LAST.get(id); + if (last != null && last.style().equals(style) && last.from().equals(tag)) { + return last.to(); + } + Component styled = colored(tag) ? tag : styled(tag.getString(), style); + LAST.put(id, new Styled(tag, style, styled)); + return styled; + } + + /** {@code name} in {@code style}: for the wardrobe's preview and cards, too. */ + public static Component styled(String name, Cosmetic style) { + int[] colors = colors(style); + if (colors.length == 1 || name.length() < 2) { + return Component.literal(name).withColor(colors[0]); + } + MutableComponent out = Component.empty(); + int last = name.length() - 1; + for (int i = 0; i < name.length(); i++) { + int color = CosmeticArt.mix(colors[0], colors[1], i / (float) last); + out.append(Component.literal(String.valueOf(name.charAt(i))).withColor(color)); + } + return out; + } + + /** Whether any part of {@code tag} has a color of the server's. */ + private static boolean colored(Component tag) { + Optional found = tag.visit( + (Style style, String text) -> + style.getColor() != null && !text.isEmpty() ? Optional.of(Boolean.TRUE) : Optional.empty(), + Style.EMPTY); + return found.isPresent(); + } + + /** Players who left, forgotten (on leaving a world). */ + static void clear() { + LAST.clear(); + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/cosmetics/PlayerPreview.java b/incari-client/files/client/src/main/java/incari/client/cosmetics/PlayerPreview.java new file mode 100644 index 0000000..3f066d8 --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/cosmetics/PlayerPreview.java @@ -0,0 +1,155 @@ +package incari.client.cosmetics; + +import incari.client.skins.OwnSkin; +import incari.client.startup.DeferredModels; +import incari.online.Cosmetic; +import incari.online.Loadout; +import java.util.UUID; +import java.util.function.Supplier; +import net.minecraft.client.gui.ComponentPath; +import net.minecraft.client.gui.GuiGraphicsExtractor; +import net.minecraft.client.gui.components.AbstractWidget; +import net.minecraft.client.gui.narration.NarrationElementOutput; +import net.minecraft.client.gui.navigation.FocusNavigationEvent; +import net.minecraft.client.input.MouseButtonEvent; +import net.minecraft.client.renderer.entity.state.AvatarRenderState; +import net.minecraft.network.chat.Component; +import net.minecraft.util.Util; +import org.joml.Quaternionf; +import org.joml.Vector3f; +import org.jspecify.annotations.Nullable; + +/** + * The player in 3D wearing a loadout (ADR 0061), drawn by the game's own player renderer with every + * layer, so what shows here is what others see: the Wardrobe's preview, and the title screen's + * player while they wear something. Dragged to turn; left alone, it turns to show what was picked + * last (the back for a cape or wings, the front otherwise). + * + *

Render thread. The game draws one 3D picture of this kind a frame, so a screen has one of these. + */ +public final class PlayerPreview extends AbstractWidget { + + /** Blocks of height the widget's height holds: a player is 1.8, a halo or wings stand above. */ + private static final float BLOCKS = 2.6F; + + /** Turned to show the front, a little from the side. */ + private static final float FRONT = -28; + + /** Turned to show the back: a cape, wings. */ + private static final float BACK = 152; + + /** A stand-in id: the preview's name tag is styled by name, not looked up by player. */ + private static final UUID PREVIEW = new UUID(0, 0); + + private final Supplier loadout; + private final long start = Util.getMillis(); + + private float yaw = FRONT; + private float targetYaw = FRONT; + private long draggedAt = -1; + private @Nullable Cosmetic emote; + private float emoteStart; + private Worn worn = Worn.NONE; + private @Nullable Loadout wornFor; + private @Nullable Cosmetic wornEmote; + + public PlayerPreview(int x, int y, int width, int height, Supplier loadout) { + super(x, y, width, height, Component.literal("Preview")); + this.loadout = loadout; + } + + /** Turns to show {@code cosmetic} best: capes and wings from behind, the rest from the front. */ + public void show(Cosmetic cosmetic) { + show(cosmetic.slot()); + } + + /** Turns to show {@code slot} best; the first time, at once. */ + public void show(Cosmetic.Slot slot) { + targetYaw = slot == Cosmetic.Slot.CAPE || slot == Cosmetic.Slot.BACK ? BACK : FRONT; + draggedAt = -1; + } + + /** Stands turned as {@link #show} would, without turning there. */ + public void face(Cosmetic.Slot slot) { + show(slot); + yaw = targetYaw; + } + + /** Plays {@code emote} now, from the front. */ + public void play(Cosmetic emote) { + this.emote = emote; + this.emoteStart = ticks(); + targetYaw = FRONT; + draggedAt = -1; + } + + private float ticks() { + return (Util.getMillis() - start) / 50.0F; + } + + @Override + @SuppressWarnings("ReferenceEquality") // the same loadout object, not an equal one + protected void extractWidgetRenderState(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) { + // The player renderer comes with the entity models, just after the title screen shows. + if (!DeferredModels.ready()) { + return; + } + float age = ticks(); + Cosmetic playing = emote; + if (playing != null && age - emoteStart >= Emotes.duration(playing)) { + emote = null; + playing = null; + } + Loadout now = loadout.get(); + if (now != wornFor || playing != wornEmote) { + wornFor = now; + wornEmote = playing; + worn = new Worn(now, playing, emoteStart); + } + if (draggedAt < 0 || Util.getMillis() - draggedAt > 4_000) { + yaw += (targetYaw - yaw) * 0.12F; + } + AvatarRenderState state = new AvatarRenderState(); + state.skin = OwnSkin.shared().playerSkin(); + state.ageInTicks = age; + state.bodyRot = 180 + yaw; + state.yRot = 0; + state.xRot = 0; + state.boundingBoxWidth = 0.6F; + state.boundingBoxHeight = 1.8F; + state.scale = 1; + state.capeLean = 6; + state.outlineColor = 0; + Cosmetics.dress(state, worn, PREVIEW); + float scale = getHeight() / BLOCKS; + Quaternionf rotation = new Quaternionf().rotateZ((float) Math.PI); + Quaternionf tilt = new Quaternionf().rotateX(-0.12F); + rotation.mul(tilt); + // Centered on the middle of what's shown: from the feet to a halo's top. + graphics.entity( + state, scale, new Vector3f(0, 1.12F, 0), rotation, tilt, getX(), getY(), getRight(), getBottom()); + } + + @Override + public void onClick(MouseButtonEvent event, boolean doubleClick) { + draggedAt = Util.getMillis(); + } + + @Override + protected void onDrag(MouseButtonEvent event, double dx, double dy) { + yaw -= (float) dx * 2.5F; + targetYaw = yaw; + draggedAt = Util.getMillis(); + } + + @Override + protected void updateWidgetNarration(NarrationElementOutput output) { + defaultButtonNarrationText(output); + } + + @Override + public @Nullable ComponentPath nextFocusPath(FocusNavigationEvent navigationEvent) { + // For the pointer: turned by dragging. + return null; + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/cosmetics/WardrobeScreen.java b/incari-client/files/client/src/main/java/incari/client/cosmetics/WardrobeScreen.java new file mode 100644 index 0000000..ad6f82f --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/cosmetics/WardrobeScreen.java @@ -0,0 +1,779 @@ +package incari.client.cosmetics; + +import incari.client.IncariKeys; +import incari.client.online.AccountScreen; +import incari.client.online.IncariOnline; +import incari.client.profile.PlayerName; +import incari.client.ui.Icons; +import incari.client.ui.Panels; +import incari.client.ui.RoundRects; +import incari.client.ui.ScreenPanels; +import incari.client.ui.Theme; +import incari.client.ui.Ui; +import incari.framework.online.Online; +import incari.online.Catalog; +import incari.online.Cosmetic; +import incari.online.Loadout; +import incari.online.OnlineService; +import incari.online.Wardrobe; +import java.util.ArrayList; +import java.util.List; +import net.minecraft.client.gui.GuiGraphicsExtractor; +import net.minecraft.client.gui.components.AbstractButton; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.components.EditBox; +import net.minecraft.client.gui.narration.NarrationElementOutput; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.input.InputWithModifiers; +import net.minecraft.client.input.MouseButtonEvent; +import net.minecraft.client.renderer.RenderPipelines; +import net.minecraft.network.chat.CommonComponents; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.Identifier; +import net.minecraft.util.ARGB; +import net.minecraft.util.FormattedCharSequence; +import org.jspecify.annotations.Nullable; + +/** + * The Wardrobe (ADR 0061): the player's cosmetics, laid out as the module menu is. Kinds down the + * left (Capes, Hats, Wings & Back, Name Tags, Trails, Emotes, Outfits), a grid of cards in the + * middle, and the player on the right wearing what's picked. Pointing at a card tries it on; a + * click puts it on, and a click on what's worn (or on None) takes it off. Emotes play on the + * preview. Outfits are what's worn saved under a name, put on again in a click. + * + *

Under the preview: whether other Incari players see what's worn (signed in) or only the player + * does (with Sign In beside it), and the switch that hides other players' cosmetics for anyone who + * finds them distracting. + * + *

Opened from the title screen's player card and the pause menu. Changes are made at once and + * reach the service a moment later ({@link Wardrobe}). + */ +public final class WardrobeScreen extends Screen { + + private static final int SIDEBAR = 104; + private static final int PREVIEW = 128; + private static final int PADDING = 10; + private static final int ENTRY = 16; + private static final int CARD_WIDTH = 64; + private static final int CARD_HEIGHT = 74; + private static final int GAP = 6; + private static final int SCROLL_STEP = 24; + private static final String[] LETTERS = {"W", "A", "R", "D", "R", "O", "B", "E"}; + + /** A kind of cosmetic down the left, and Outfits. */ + private enum Tab { + CAPES(Cosmetic.Slot.CAPE), + HATS(Cosmetic.Slot.HAT), + BACK(Cosmetic.Slot.BACK), + NAMETAGS(Cosmetic.Slot.NAMETAG), + TRAILS(Cosmetic.Slot.TRAIL), + EMOTES(Cosmetic.Slot.EMOTE), + OUTFITS(null); + + final Cosmetic.@Nullable Slot slot; + + Tab(Cosmetic.@Nullable Slot slot) { + this.slot = slot; + } + + String label() { + return slot == null ? "Outfits" : slot.label(); + } + } + + /** The tab shown last, shown again next time. */ + private static Tab lastTab = Tab.CAPES; + + private final @Nullable Screen parent; + private final OnlineService online = IncariOnline.service(); + private final Wardrobe wardrobe = online.wardrobe(); + private final List cards = new ArrayList<>(); + + private Tab tab = lastTab; + private double scroll; + private int panelX; + private int panelY; + private int panelWidth; + private int panelHeight; + private int gridX; + private int gridY; + private int gridWidth; + private int gridHeight; + private int contentHeight; + private int previewX; + /** The preview's width: {@link #PREVIEW}, less on a narrow screen so a card still fits beside. */ + private int previewWidth = PREVIEW; + + private @Nullable PlayerPreview preview; + private @Nullable Button signIn; + private @Nullable EditBox outfitName; + + /** What the pointer is on, tried on in the preview: a card's loadout. */ + private @Nullable Loadout tryOn; + + private @Nullable Component notice; + + public WardrobeScreen(@Nullable Screen parent) { + super(Component.literal("Wardrobe")); + this.parent = parent; + } + + /** The Wardrobe open on {@code slot}'s kind, or on Outfits for null (the smoke test's screenshots). */ + public static WardrobeScreen showing(@Nullable Screen parent, Cosmetic.@Nullable Slot slot) { + WardrobeScreen screen = new WardrobeScreen(parent); + for (Tab each : Tab.values()) { + if (each.slot == slot) { + screen.tab = each; + } + } + return screen; + } + + @Override + protected void init() { + panelWidth = Math.min(width - 24, 560); + panelHeight = Math.min(height - 20, 300); + panelX = (width - panelWidth) / 2; + panelY = (height - panelHeight) / 2; + ScreenPanels.clear(this); + ScreenPanels.add(this, panelX, panelY, panelWidth, panelHeight); + + // The kinds, down the left. + int x = panelX + 8; + int entryWidth = SIDEBAR - 16; + int y = panelY + 34; + for (Tab each : Tab.values()) { + addRenderableWidget(new Entry(Component.literal(each.label()), count(each), x, y, entryWidth, each)); + y += ENTRY + 2; + } + Button done = Ui.button(CommonComponents.GUI_DONE, entryWidth, this::onClose); + done.setPosition(x, panelY + panelHeight - 8 - Theme.CONTROL_HEIGHT); + addRenderableWidget(done); + + // The player, on the right, with whether others see it and the switch for others' below. + previewWidth = Math.clamp(panelWidth - SIDEBAR - 2 * PADDING - 2 * CARD_WIDTH - GAP, 88, PREVIEW); + previewX = panelX + panelWidth - PADDING - previewWidth; + int previewTop = panelY + PADDING + 14; + int previewHeight = panelHeight - PADDING - 14 - 64; + PlayerPreview player = + new PlayerPreview(previewX + 8, previewTop, previewWidth - 16, previewHeight, this::shown); + Cosmetic.Slot facing = tab.slot; + if (facing != null) { + player.face(facing); + } + preview = player; + addRenderableWidget(player); + int belowY = previewTop + previewHeight + 4; + Button signInButton = Ui.button(Component.literal("Sign In"), previewWidth, () -> { + if (minecraft != null) { + minecraft.gui.setScreen(new AccountScreen(this)); + } + }); + signInButton.setPosition(previewX, belowY + 12); + signInButton.setTooltip(Ui.tooltip("Sign in so other Incari players can see your cosmetics")); + signIn = signInButton; + addRenderableWidget(signInButton); + addRenderableWidget(new OthersSwitch(previewX, panelY + panelHeight - 8 - 14, previewWidth)); + + gridX = panelX + SIDEBAR + PADDING; + gridWidth = previewX - PADDING - gridX; + gridY = panelY + PADDING + 14; + outfitName = null; + if (tab == Tab.OUTFITS) { + int saveWidth = 70; + // A grid too narrow for both side by side puts Save under the name. + boolean stacked = gridWidth < saveWidth + Theme.GAP + 80; + int nameWidth = stacked ? gridWidth : gridWidth - saveWidth - Theme.GAP; + EditBox name = Ui.textField(font, Component.literal("Outfit name"), nameWidth, 24); + name.setMaxLength(Wardrobe.MAX_OUTFIT_NAME); + name.setHint(Component.literal(Ui.fit(font, "Name this outfit", nameWidth - 8))); + name.setPosition(gridX, gridY); + addRenderableWidget(name); + outfitName = name; + if (stacked) { + gridY += Theme.CONTROL_HEIGHT + Theme.GAP; + } + Button save = Ui.button(Component.literal("Save"), stacked ? gridWidth : saveWidth, this::saveOutfit); + save.setPosition(stacked ? gridX : gridX + gridWidth - saveWidth, gridY); + save.setTooltip(Ui.tooltip("Save what you're wearing as an outfit")); + addRenderableWidget(save); + gridY += Theme.CONTROL_HEIGHT + PADDING; + } + gridHeight = panelY + panelHeight - PADDING - gridY; + + cards.clear(); + if (tab == Tab.OUTFITS) { + cards.add(new Card(null, null, null)); + for (Wardrobe.Outfit outfit : wardrobe.outfits()) { + cards.add(new Card(null, null, outfit)); + } + } else { + Cosmetic.Slot slot = tab.slot; + if (slot != null) { + if (slot.worn()) { + cards.add(new Card(null, slot, null)); + } + for (Cosmetic each : Catalog.inSlot(slot)) { + cards.add(new Card(each, slot, null)); + } + } + } + for (Card card : cards) { + // Drawn by this screen inside the grid's clip, not with the other widgets. + addWidget(card); + } + layOutCards(); + } + + private String count(Tab each) { + if (each.slot == null) { + return String.valueOf(wardrobe.outfits().size()); + } + int owned = 0; + for (Cosmetic cosmetic : Catalog.inSlot(each.slot)) { + if (wardrobe.owns(cosmetic)) { + owned++; + } + } + return String.valueOf(owned); + } + + private void choose(Tab chosen) { + tab = chosen; + lastTab = chosen; + scroll = 0; + notice = null; + rebuildWidgets(); + } + + private void layOutCards() { + int columns = Math.max(1, (gridWidth + GAP) / (CARD_WIDTH + GAP)); + int cardWidth = (gridWidth - (columns - 1) * GAP) / columns; + int shown = 0; + for (Card card : cards) { + int column = shown % columns; + int row = shown / columns; + card.setRectangle( + cardWidth, + CARD_HEIGHT, + gridX + column * (cardWidth + GAP), + gridY + row * (CARD_HEIGHT + GAP) - (int) scroll); + shown++; + } + int rows = (shown + columns - 1) / columns; + contentHeight = Math.max(0, rows * (CARD_HEIGHT + GAP) - GAP); + double max = Math.max(0, contentHeight - gridHeight); + if (scroll > max) { + scroll = max; + layOutCards(); + } + } + + /** What the preview wears: what the pointer is on, or what's worn. */ + private Loadout shown() { + Loadout trying = tryOn; + return trying != null ? trying : wardrobe.worn(); + } + + private void saveOutfit() { + EditBox name = outfitName; + String typed = name == null ? "" : name.getValue(); + if (wardrobe.saveOutfit(typed)) { + notice = Component.literal("Outfit saved."); + rebuildWidgets(); + } else { + notice = Component.literal("No room for more outfits. Delete one first.") + .withStyle(style -> style.withColor(Theme.WARNING)); + } + } + + @Override + public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY) { + if (mouseX >= gridX && mouseX < gridX + gridWidth && mouseY >= gridY && mouseY < gridY + gridHeight) { + scroll = Math.max(0, Math.min(Math.max(0, contentHeight - gridHeight), scroll - scrollY * SCROLL_STEP)); + layOutCards(); + return true; + } + return super.mouseScrolled(mouseX, mouseY, scrollX, scrollY); + } + + @Override + public void extractRenderState(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) { + // Whatever the pointer is on is tried on. + tryOn = null; + for (Card card : cards) { + if (card.isMouseOver(mouseX, mouseY)) { + tryOn = card.tryOn(); + } + } + Button signInButton = signIn; + if (signInButton != null) { + signInButton.visible = !wardrobe.shared() && online.status() == Online.Status.SIGNED_OUT; + } + + // The sidebar's mark, and the lines between the columns. + Icons.HANGER.draw(graphics, panelX + 10, panelY + 10, 13, Theme.TEXT); + int letterX = panelX + 28; + for (String letter : LETTERS) { + graphics.text(font, letter, letterX, panelY + 14, Theme.TEXT, false); + letterX += font.width(letter) + 2; + } + graphics.fill(panelX + SIDEBAR, panelY + 8, panelX + SIDEBAR + 1, panelY + panelHeight - 8, 0x1AFFFFFF); + graphics.fill(previewX - 5, panelY + 8, previewX - 4, panelY + panelHeight - 8, 0x1AFFFFFF); + + // The grid's heading: the kind, and a hint for the ones that need one. + if (tab != Tab.OUTFITS) { + String label = tab.label(); + graphics.text(font, label, gridX, panelY + PADDING, Theme.TEXT, false); + // Cut on a narrow grid rather than run into the label. + String hint = Ui.fit(font, hint(), gridWidth - font.width(label) - 8); + graphics.text(font, hint, gridX + gridWidth - font.width(hint), panelY + PADDING, Theme.MUTED, false); + } + + // The name over the preview, in the name tag cosmetic if one's shown. + Cosmetic nametag = shown().in(Cosmetic.Slot.NAMETAG); + String name = PlayerName.name(); + Component styled = nametag == null ? Component.literal(name) : NameTags.styled(name, nametag); + FormattedCharSequence label = Ui.fit(font, styled, previewWidth - 6); + int labelWidth = font.width(label); + int labelX = previewX + (previewWidth - labelWidth) / 2; + int labelY = panelY + PADDING; + graphics.fill(labelX - 3, labelY - 2, labelX + labelWidth + 2, labelY + 9, 0x40000000); + graphics.text(font, label, labelX, labelY, 0xFFFFFFFF, false); + + super.extractRenderState(graphics, mouseX, mouseY, a); + + // Who sees what's worn. + PlayerPreview player = preview; + int statusY = player == null ? panelY : player.getBottom() + 4; + boolean shared = wardrobe.shared(); + String status = Ui.fit(font, shared ? "Incari players see these" : "Only you see these", previewWidth - 12); + int statusWidth = font.width(status) + 12; + int statusX = previewX + (previewWidth - statusWidth) / 2; + (shared ? Icons.CHECK : Icons.EYE).draw(graphics, statusX, statusY, 9, shared ? Theme.POSITIVE : Theme.MUTED); + graphics.text(font, status, statusX + 12, statusY + 1, shared ? Theme.POSITIVE : Theme.MUTED, false); + + graphics.enableScissor(gridX - 6, gridY, gridX + gridWidth + 6, gridY + gridHeight); + for (Card card : cards) { + if (card.getBottom() > gridY && card.getY() < gridY + gridHeight) { + card.extractRenderState(graphics, mouseX, mouseY, a); + } + } + graphics.disableScissor(); + if (tab == Tab.OUTFITS && cards.size() <= 1) { + int lineY = gridY + CARD_HEIGHT + 16; + for (FormattedCharSequence line : + Ui.wrap(font, "Put on what you like, name it above and press Save.", gridWidth, 3)) { + graphics.centeredText(font, line, gridX + gridWidth / 2, lineY, Theme.MUTED); + lineY += font.lineHeight + 1; + } + } + Component shownNotice = notice; + if (shownNotice != null) { + graphics.text( + font, + Component.literal(Ui.fit(font, shownNotice.getString(), gridWidth)) + .withStyle(shownNotice.getStyle()), + gridX, + panelY + panelHeight - PADDING + 1, + Theme.MUTED, + false); + } + if (contentHeight > gridHeight) { + int thumb = Math.max(16, gridHeight * gridHeight / contentHeight); + int top = gridY + (int) ((gridHeight - thumb) * scroll / (contentHeight - gridHeight)); + RoundRects.fill(graphics, gridX + gridWidth + 3, top, 2, thumb, 1, 0x80FFFFFF); + } + } + + private String hint() { + return switch (tab) { + case EMOTES -> + "In a world, hold " + + IncariKeys.EMOTE_WHEEL.getTranslatedKeyMessage().getString(); + case NAMETAGS -> "Unless the server colors names"; + case HATS -> "Hidden under a helmet"; + case BACK -> "Hidden under an elytra"; + default -> ""; + }; + } + + @Override + public void onClose() { + if (minecraft != null) { + minecraft.gui.setScreen(parent); + } + } + + @Override + public boolean isPauseScreen() { + return true; + } + + /** A line in the sidebar: one kind of cosmetic, with how many the player has. */ + private final class Entry extends AbstractButton { + + private final String value; + private final Tab target; + + Entry(Component label, String value, int x, int y, int width, Tab target) { + super(x, y, width, ENTRY, label); + this.value = value; + this.target = target; + } + + @Override + public void onPress(InputWithModifiers input) { + choose(target); + } + + @Override + protected void extractContents(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) { + boolean on = tab == target; + if (on || isHoveredOrFocused()) { + RoundRects.fill( + graphics, + getX(), + getY(), + getWidth(), + getHeight(), + Theme.RADIUS, + on ? Theme.BUTTON_HOT : Theme.BUTTON); + } + if (on) { + RoundRects.fill(graphics, getX(), getY() + 4, 2, getHeight() - 8, 1, Theme.ACCENT); + } + int textY = getY() + (getHeight() - 7) / 2; + graphics.text(font, getMessage(), getX() + 7, textY, on ? Theme.TEXT : Theme.MUTED, false); + graphics.text(font, value, getRight() - 6 - font.width(value), textY, Theme.MUTED, false); + } + + @Override + protected void updateWidgetNarration(NarrationElementOutput output) { + defaultButtonNarrationText(output); + } + } + + /** The switch for other players' cosmetics. */ + private final class OthersSwitch extends AbstractButton { + + OthersSwitch(int x, int y, int width) { + super(x, y, width, 12, Component.literal("Show others' cosmetics")); + setTooltip(Ui.tooltip("Off hides other players' capes, hats, wings, trails and emotes. Yours still show.")); + } + + @Override + public void onPress(InputWithModifiers input) { + wardrobe.setShowOthers(!wardrobe.showOthers()); + } + + @Override + protected void extractContents(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) { + boolean on = wardrobe.showOthers(); + // Cut short of the switch beside a narrow preview; the tooltip says what it does. + graphics.text( + font, + Ui.fit(font, getMessage(), getWidth() - Panels.SWITCH_WIDTH - 4), + getX(), + getY() + 2, + isHoveredOrFocused() ? Theme.TEXT : Theme.MUTED, + false); + Panels.toggle(graphics, getRight() - Panels.SWITCH_WIDTH, getY() + 1, on, 1.0F); + } + + @Override + protected void updateWidgetNarration(NarrationElementOutput output) { + defaultButtonNarrationText(output); + } + } + + /** + * A card: a cosmetic, None for a kind (takes it off), an outfit, or, on the Outfits tab with + * neither, Take Off All. + */ + private final class Card extends AbstractButton { + + private static final int TRASH = 9; + + private final @Nullable Cosmetic cosmetic; + private final Cosmetic.@Nullable Slot slot; + private final Wardrobe.@Nullable Outfit outfit; + private @Nullable Loadout tried; + private @Nullable Loadout triedFrom; + + Card(@Nullable Cosmetic cosmetic, Cosmetic.@Nullable Slot slot, Wardrobe.@Nullable Outfit outfit) { + super(0, 0, CARD_WIDTH, CARD_HEIGHT, label(cosmetic, outfit, slot)); + this.cosmetic = cosmetic; + this.slot = slot; + this.outfit = outfit; + } + + private static Component label( + @Nullable Cosmetic cosmetic, Wardrobe.@Nullable Outfit outfit, Cosmetic.@Nullable Slot slot) { + if (cosmetic != null) { + return Component.literal(cosmetic.name()); + } + if (outfit != null) { + return Component.literal(outfit.name()); + } + return Component.literal(slot == null ? "Take Off All" : "None"); + } + + /** What the preview wears while the pointer's here. */ + @SuppressWarnings("ReferenceEquality") // the same loadout object, not an equal one + @Nullable + Loadout tryOn() { + Loadout worn = wardrobe.worn(); + if (tried != null && triedFrom == worn) { + return tried; + } + Loadout next; + if (cosmetic != null) { + next = cosmetic.slot().worn() && wardrobe.owns(cosmetic) ? worn.with(cosmetic) : null; + } else if (outfit != null) { + next = outfit.loadout(); + } else if (slot != null) { + next = worn.without(slot); + } else { + next = Loadout.EMPTY; + } + tried = next; + triedFrom = worn; + return next; + } + + private boolean worn() { + Loadout worn = wardrobe.worn(); + if (cosmetic != null) { + return worn.wears(cosmetic); + } + if (outfit != null) { + return worn.equals(outfit.loadout()); + } + return slot != null && slot.worn() && worn.in(slot) == null; + } + + @Override + public void onPress(InputWithModifiers input) { + press(false); + } + + @Override + public void onClick(MouseButtonEvent event, boolean doubleClick) { + press(outfit != null && overTrash(event.x(), event.y())); + } + + private void press(boolean trash) { + PlayerPreview player = preview; + Wardrobe.Outfit saved = outfit; + if (saved != null) { + if (trash) { + wardrobe.deleteOutfit(saved); + notice = Component.literal("Deleted " + saved.name() + "."); + rebuildWidgets(); + } else { + wardrobe.wear(saved.loadout()); + } + return; + } + Cosmetic picked = cosmetic; + if (picked == null) { + if (slot != null) { + wardrobe.takeOff(slot); + } else { + wardrobe.wear(Loadout.EMPTY); + } + return; + } + if (!wardrobe.owns(picked)) { + return; + } + if (picked.slot() == Cosmetic.Slot.EMOTE) { + if (player != null) { + player.play(picked); + } + return; + } + if (wardrobe.worn().wears(picked)) { + wardrobe.takeOff(picked.slot()); + } else { + wardrobe.wear(picked); + if (player != null) { + player.show(picked); + } + } + } + + private boolean overTrash(double x, double y) { + return x >= getRight() - 5 - TRASH - 2 && y <= getY() + 5 + TRASH + 2; + } + + @Override + public boolean isMouseOver(double mouseX, double mouseY) { + return super.isMouseOver(mouseX, mouseY) && mouseY >= gridY && mouseY < gridY + gridHeight; + } + + @Override + protected void extractContents(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) { + boolean on = worn(); + boolean owned = cosmetic == null || wardrobe.owns(cosmetic); + Panels.card( + graphics, getX(), getY(), getWidth(), getHeight(), isHoveredOrFocused(), on, owned ? 1.0F : 0.5F); + int artX = getX() + getWidth() / 2; + int artY = getY() + 6; + picture(graphics, artX, artY); + // An outfit's name can be 24 characters: cut to the card, not into the next one. + String message = Ui.fit(font, getMessage().getString(), getWidth() - 8); + int textWidth = font.width(message); + int textX = getX() + Math.max(4, (getWidth() - textWidth) / 2); + graphics.text(font, message, textX, getBottom() - 14, owned ? Theme.TEXT : Theme.MUTED, false); + if (on) { + Icons.CHECK.draw(graphics, getRight() - 13, getY() + 5, 8, Theme.ACCENT); + } + if (outfit != null && isHovered()) { + boolean hot = overTrash(mouseX, mouseY); + Icons.TRASH.draw( + graphics, getRight() - 5 - TRASH, getY() + 5, TRASH, hot ? Theme.NEGATIVE : Theme.MUTED); + } + if (!owned) { + graphics.text(font, "Locked", getX() + 5, getY() + 5, Theme.MUTED, false); + } + } + + /** The card's picture, 44 tall, centered on {@code x}. */ + private void picture(GuiGraphicsExtractor graphics, int x, int y) { + Cosmetic shown = cosmetic; + if (shown == null) { + if (outfit != null) { + outfitPicture(graphics, x, y, outfit.loadout()); + } else { + Icons.CLOSE.draw(graphics, x - 8, y + 14, 16, Theme.MUTED); + } + return; + } + switch (shown.slot()) { + case CAPE -> { + // The cape's outer side, as it hangs: 10x16 pixels at twice the size. + Identifier texture = CosmeticTextures.capeId(shown); + graphics.blit( + RenderPipelines.GUI_TEXTURED, + texture, + x - 13, + y + 1, + 1, + 1, + 26, + 42, + 10, + 16, + CosmeticArt.CAPE_WIDTH, + CosmeticArt.CAPE_HEIGHT); + } + case HAT, BACK -> { + Identifier icon = CosmeticTextures.icon(shown); + if (icon != null) { + graphics.blit( + RenderPipelines.GUI_TEXTURED, + icon, + x - 18, + y + 4, + 0, + 0, + 36, + 36, + CosmeticArt.ICON, + CosmeticArt.ICON, + CosmeticArt.ICON, + CosmeticArt.ICON); + } + } + case NAMETAG -> { + Component name = NameTags.styled(PlayerName.name(), shown); + int nameWidth = Math.min(getWidth() - 8, font.width(name)); + graphics.fill(x - nameWidth / 2 - 3, y + 15, x + nameWidth / 2 + 3, y + 27, 0x60000000); + graphics.enableScissor(getX() + 3, y, getRight() - 3, y + 40); + graphics.text(font, name, x - font.width(name) / 2, y + 17, 0xFFFFFFFF, false); + graphics.disableScissor(); + } + case TRAIL -> trailPicture(graphics, x, y, shown); + case EMOTE -> Icons.PERSON.draw(graphics, x - 12, y + 8, 24, Theme.TEXT); + } + } + + private void trailPicture(GuiGraphicsExtractor graphics, int x, int y, Cosmetic trail) { + int[] colors = + switch (trail.id()) { + case "trail.hearts" -> new int[] {0xFFFF5A7A, 0xFFFF8FA6}; + case "trail.sparkles" -> new int[] {0xFFFFF4C2, 0xFFFFFFFF}; + case "trail.notes" -> new int[] {0xFF6AF2B0, 0xFFA06CFF, 0xFFFFD36A}; + default -> new int[] {0xFFFFFFFF, 0xFFA9DCFF}; + }; + // Dots drifting up from the bottom left, bigger toward the start. + for (int i = 0; i < 7; i++) { + int dotX = x - 16 + i * 5; + int dotY = y + 34 - i * 4 - (i % 2) * 3; + int size = Math.max(2, 6 - i / 2); + RoundRects.fill(graphics, dotX, dotY, size, size, size / 2, colors[i % colors.length]); + } + } + + private void outfitPicture(GuiGraphicsExtractor graphics, int x, int y, Loadout loadout) { + // Up to four of what the outfit wears, small, in a row. + List worn = new ArrayList<>(); + for (Cosmetic.Slot each : Cosmetic.Slot.values()) { + Cosmetic in = loadout.in(each); + if (in != null && worn.size() < 4) { + worn.add(in); + } + } + if (worn.isEmpty()) { + Icons.HANGER.draw(graphics, x - 10, y + 12, 20, Theme.MUTED); + return; + } + int each = 14; + int startX = x - (worn.size() * (each + 2)) / 2; + for (int i = 0; i < worn.size(); i++) { + Cosmetic c = worn.get(i); + int cx = startX + i * (each + 2); + Identifier icon = c.slot() == Cosmetic.Slot.CAPE ? null : CosmeticTextures.icon(c); + if (c.slot() == Cosmetic.Slot.CAPE) { + graphics.blit( + RenderPipelines.GUI_TEXTURED, + CosmeticTextures.capeId(c), + cx + 2, + y + 10, + 1, + 1, + 10, + 16, + 10, + 16, + CosmeticArt.CAPE_WIDTH, + CosmeticArt.CAPE_HEIGHT); + } else if (icon != null) { + graphics.blit( + RenderPipelines.GUI_TEXTURED, + icon, + cx, + y + 12, + 0, + 0, + each, + each, + CosmeticArt.ICON, + CosmeticArt.ICON, + CosmeticArt.ICON, + CosmeticArt.ICON); + } else { + int color = c.slot() == Cosmetic.Slot.NAMETAG ? 0xFF000000 | NameTags.colors(c)[0] : Theme.MUTED; + RoundRects.fill(graphics, cx + 3, y + 15, 8, 8, 4, ARGB.opaque(color)); + } + } + } + + @Override + protected void updateWidgetNarration(NarrationElementOutput output) { + defaultButtonNarrationText(output); + } + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/cosmetics/Worn.java b/incari-client/files/client/src/main/java/incari/client/cosmetics/Worn.java new file mode 100644 index 0000000..520ddb7 --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/cosmetics/Worn.java @@ -0,0 +1,43 @@ +package incari.client.cosmetics; + +import incari.online.Cosmetic; +import incari.online.Loadout; +import org.jspecify.annotations.Nullable; + +/** + * What one player shows, as their render state carries it (ADR 0061): what they wear, and the emote + * they're playing, if any. Made when that changes, not each frame. + * + *

Immutable; render thread. + */ +public final class Worn { + + /** Nothing: what every player the client draws no cosmetics for carries. */ + public static final Worn NONE = new Worn(Loadout.EMPTY, null, 0); + + final Loadout loadout; + final @Nullable Cosmetic cape; + final @Nullable Cosmetic hat; + final @Nullable Cosmetic back; + final @Nullable Cosmetic nametag; + final @Nullable Cosmetic trail; + final @Nullable Cosmetic emote; + /** When the emote started, in the player's own ticks ({@code ageInTicks}). */ + final float emoteStart; + + Worn(Loadout loadout, @Nullable Cosmetic emote, float emoteStart) { + this.loadout = loadout; + this.cape = loadout.in(Cosmetic.Slot.CAPE); + this.hat = loadout.in(Cosmetic.Slot.HAT); + this.back = loadout.in(Cosmetic.Slot.BACK); + this.nametag = loadout.in(Cosmetic.Slot.NAMETAG); + this.trail = loadout.in(Cosmetic.Slot.TRAIL); + this.emote = emote; + this.emoteStart = emoteStart; + } + + /** Whether there's nothing to show. */ + boolean isEmpty() { + return loadout.isEmpty() && emote == null; + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/cosmetics/package-info.java b/incari-client/files/client/src/main/java/incari/client/cosmetics/package-info.java new file mode 100644 index 0000000..10504c6 --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/cosmetics/package-info.java @@ -0,0 +1,9 @@ +/** + * Cosmetics (ADR 0061): what players wear and play, drawn on them, the Wardrobe screen that picks + * it, and the emote wheel. What's owned and worn is kept by {@code :online}'s wardrobe and the + * online service; this draws it. + */ +@NullMarked +package incari.client.cosmetics; + +import org.jspecify.annotations.NullMarked; diff --git a/incari-client/files/client/src/main/java/incari/client/credits/Credit.java b/incari-client/files/client/src/main/java/incari/client/credits/Credit.java new file mode 100644 index 0000000..bcef3f7 --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/credits/Credit.java @@ -0,0 +1,23 @@ +package incari.client.credits; + +import java.net.URI; +import org.jspecify.annotations.Nullable; + +/** + * One entry on the credits screen: a piece of software in this build, under its own license. + * + * @param name what the software is called + * @param version the version in this build, shown after the name; null when it isn't known here + * @param authors who holds its copyright + * @param license the license's short name, as SPDX names it where it can + * @param licenseText where the license's full text is + * @param source where its source code is + */ +public record Credit( + String name, @Nullable String version, String authors, String license, URI licenseText, URI source) { + + /** The name with the version after it, if there is one. */ + public String title() { + return version == null ? name : name + " " + version; + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/credits/Credits.java b/incari-client/files/client/src/main/java/incari/client/credits/Credits.java new file mode 100644 index 0000000..f3fb44b --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/credits/Credits.java @@ -0,0 +1,130 @@ +package incari.client.credits; + +import com.viaversion.viaversion.util.VersionInfo; +import incari.client.IncariBuild; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +/** + * What the credits screen lists: Incari and the third-party software it adds to the game, in + * every build. Minecraft's own libraries are Mojang's to credit, which the vanilla screen beside + * this one does. + * + *

A build adds what only it contains (the browser build: TeaVM's runtime) with {@link #add}, + * at start-up, before the game's first screen. Adding a library to every build means adding it to + * {@code COMMON} here. + */ +public final class Credits { + + /** + * Incari's public source (incari.properties' {@code incari.repository}). GPL-3.0's source offer + * for every build points here. + */ + public static final URI INCARI_SOURCE = URI.create(IncariBuild.REPOSITORY); + + /** The pause menu's Report Bugs: a new issue on the repository, from its bug template. */ + public static final URI REPORT_BUGS = URI.create(IncariBuild.REPOSITORY + "/issues/new?template=bug_report.yml"); + + /** The pause menu's Give Feedback: a new discussion in the repository's Feedback category. */ + public static final URI FEEDBACK = URI.create(IncariBuild.REPOSITORY + "/discussions/new?category=feedback"); + + public static final URI GPL_3 = URI.create("https://www.gnu.org/licenses/gpl-3.0.html"); + public static final URI APACHE_2 = URI.create("https://www.apache.org/licenses/LICENSE-2.0"); + public static final URI BSD_3_CLAUSE = URI.create("https://opensource.org/license/bsd-3-clause"); + public static final URI OFL_1_1 = URI.create("https://openfontlicense.org/open-font-license-official-text/"); + + private static final List COMMON = List.of( + new Credit( + "Incari Client", + null, + "The Incari Client contributors", + "GPL-3.0-or-later, with an exception for Minecraft", + URI.create(INCARI_SOURCE + "/blob/main/LICENSE-EXCEPTION.txt"), + INCARI_SOURCE), + // VERSION is a constant, so these are the versions the client was compiled against, + // which are the ones the build bundles. + new Credit( + "ViaVersion", + VersionInfo.VERSION, + "ViaVersion and contributors", + "GPL-3.0", + GPL_3, + URI.create("https://github.com/ViaVersion/ViaVersion")), + new Credit( + "ViaBackwards", + com.viaversion.viabackwards.utils.VersionInfo.VERSION, + "ViaVersion and contributors", + "GPL-3.0", + GPL_3, + URI.create("https://github.com/ViaVersion/ViaBackwards")), + // Microsoft sign-in's TLS, and the browser build's AES, RSA and chat signing (ADR 0070). + new Credit( + "Bouncy Castle", + null, + "The Legion of the Bouncy Castle Inc.", + "MIT", + URI.create("https://www.bouncycastle.org/about/license/"), + URI.create("https://github.com/bcgit/bc-java")), + // The look's fonts, in Incari's pack with their licences beside them. + new Credit( + "Red Hat Display", + null, + "The Red Hat Project Authors", + "OFL-1.1", + OFL_1_1, + URI.create("https://github.com/RedHatOfficial/RedHatFont")), + new Credit( + "Michroma", + null, + "The Michroma Project Authors", + "OFL-1.1", + OFL_1_1, + URI.create("https://github.com/googlefonts/Michroma-font")), + // A theme's other fonts, subset to Red Hat Display's characters. + new Credit( + "Inter", + null, + "The Inter Project Authors", + "OFL-1.1", + OFL_1_1, + URI.create("https://github.com/rsms/inter")), + new Credit( + "Nunito", + null, + "The Nunito Project Authors", + "OFL-1.1", + OFL_1_1, + URI.create("https://github.com/googlefonts/nunito")), + new Credit( + "Poppins", + null, + "The Poppins Project Authors", + "OFL-1.1", + OFL_1_1, + URI.create("https://github.com/itfoundry/Poppins")), + new Credit( + "JetBrains Mono", + null, + "The JetBrains Mono Project Authors", + "OFL-1.1", + OFL_1_1, + URI.create("https://github.com/JetBrains/JetBrainsMono"))); + + // Written at start-up, read by the screen later on the same thread. + private static final List added = new ArrayList<>(); + + private Credits() {} + + /** Adds software only this build contains. */ + public static void add(Credit credit) { + added.add(credit); + } + + /** Everything this build credits: Incari's own entries first, then what the build added. */ + public static List all() { + List all = new ArrayList<>(COMMON); + all.addAll(added); + return List.copyOf(all); + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/credits/CreditsScreen.java b/incari-client/files/client/src/main/java/incari/client/credits/CreditsScreen.java new file mode 100644 index 0000000..ce906d9 --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/credits/CreditsScreen.java @@ -0,0 +1,108 @@ +package incari.client.credits; + +import net.minecraft.ChatFormatting; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.components.MultiLineTextWidget; +import net.minecraft.client.gui.components.ScrollableLayout; +import net.minecraft.client.gui.components.StringWidget; +import net.minecraft.client.gui.layouts.HeaderAndFooterLayout; +import net.minecraft.client.gui.layouts.LinearLayout; +import net.minecraft.client.gui.screens.ConfirmLinkScreen; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.CommonComponents; +import net.minecraft.network.chat.Component; +import org.jspecify.annotations.Nullable; + +/** + * Incari's credits and the licenses of what it adds to the game ({@link Credits}), reached from + * the vanilla Credits & Attribution screen. Each entry links to its source and its license, which + * is what GPL-3.0 asks a build to come with. + * + *

English only for now; Incari's screens don't have language files yet. + */ +public final class CreditsScreen extends Screen { + + private static final Component TITLE = Component.literal("Incari & Open Source"); + private static final Component NOTICE = Component.literal( + "Incari Client is free software that runs on Minecraft: Java Edition. It is not an official Minecraft" + + " product, and is not approved by or associated with Mojang or Microsoft. This build contains" + + " the software below, each under its own license."); + private static final int BODY_WIDTH = 300; + private static final int BUTTON_WIDTH = 103; + private static final int BUTTON_SPACING = 4; + + private final Screen parent; + private final HeaderAndFooterLayout layout = new HeaderAndFooterLayout(this); + private @Nullable ScrollableLayout body; + + public CreditsScreen(Screen parent) { + super(TITLE); + this.parent = parent; + } + + /** The button that opens this screen from {@code parent}, for the vanilla screen's list. */ + public static Button button(Screen parent, int width) { + return Button.builder(TITLE, button -> Minecraft.getInstance().gui.setScreen(new CreditsScreen(parent))) + .width(width) + .build(); + } + + @Override + protected void init() { + this.layout.addTitleHeader(TITLE, this.font); + LinearLayout content = LinearLayout.vertical().spacing(12); + content.defaultCellSetting().alignHorizontallyCenter(); + content.addChild(new MultiLineTextWidget(NOTICE, this.font) + .setMaxWidth(BODY_WIDTH) + .setCentered(true)); + for (Credit credit : Credits.all()) { + content.addChild(entry(credit)); + } + ScrollableLayout scroll = + new ScrollableLayout(Minecraft.getInstance(), content, this.layout.getContentHeight()); + body = scroll; + this.layout.addToContents(scroll); + this.layout.addToFooter(Button.builder(CommonComponents.GUI_DONE, button -> onClose()) + .width(200) + .build()); + this.layout.visitWidgets(this::addRenderableWidget); + repositionElements(); + } + + private LinearLayout entry(Credit credit) { + LinearLayout entry = LinearLayout.vertical().spacing(2); + entry.defaultCellSetting().alignHorizontallyCenter(); + entry.addChild(new StringWidget(Component.literal(credit.title()), this.font)); + entry.addChild(new MultiLineTextWidget( + Component.literal(credit.authors() + " · " + credit.license()) + .withStyle(ChatFormatting.GRAY), + this.font) + .setMaxWidth(BODY_WIDTH) + .setCentered(true)); + LinearLayout links = entry.addChild(LinearLayout.horizontal().spacing(BUTTON_SPACING)); + links.addChild(Button.builder(Component.literal("Source"), ConfirmLinkScreen.confirmLink(this, credit.source())) + .width(BUTTON_WIDTH) + .build()); + links.addChild( + Button.builder(Component.literal("License"), ConfirmLinkScreen.confirmLink(this, credit.licenseText())) + .width(BUTTON_WIDTH) + .build()); + return entry; + } + + @Override + protected void repositionElements() { + ScrollableLayout scroll = body; + if (scroll != null) { + scroll.arrangeElements(); + scroll.setMaxHeight(this.layout.getContentHeight()); + } + this.layout.arrangeElements(); + } + + @Override + public void onClose() { + Minecraft.getInstance().gui.setScreen(parent); + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/credits/package-info.java b/incari-client/files/client/src/main/java/incari/client/credits/package-info.java new file mode 100644 index 0000000..d78099b --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/credits/package-info.java @@ -0,0 +1,8 @@ +/** + * Incari's credits: the software a build contains beside Minecraft, each under its own license, + * and the screen that lists them. + */ +@NullMarked +package incari.client.credits; + +import org.jspecify.annotations.NullMarked; diff --git a/incari-client/files/client/src/main/java/incari/client/datafix/DataFixing.java b/incari-client/files/client/src/main/java/incari/client/datafix/DataFixing.java new file mode 100644 index 0000000..d27cee0 --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/datafix/DataFixing.java @@ -0,0 +1,46 @@ +package incari.client.datafix; + +import com.mojang.datafixers.DSL; +import com.mojang.datafixers.DataFixer; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import net.minecraft.SharedConstants; +import net.minecraft.util.datafix.DataFixers; + +/** + * Whether the game builds its data fixer at start or when it's first needed. + * + *

The game builds every schema since 2013's at start-up (the class initializer of + * {@code DataFixers}), optimizes the world list's types on a thread of their own, and waits for that + * before its window opens. A browser client almost never needs any of it: its options, servers and + * worlds were written by this version, and a multiplayer client upgrades nothing. Lazily, the game + * keeps a stand-in fixer that passes data already at the current version through untouched (what + * the real fixer does with it) and builds the real one the first time something older arrives: an + * imported world, an old options file. + */ +public final class DataFixing { + + private static volatile boolean lazy; + + private DataFixing() {} + + /** + * Builds the data fixer only when it's first needed. Also turns off the game's check, at + * bootstrap, that every entity and block entity type has a schema: a development check whose + * answer is discarded, which would build the fixer to ask. + */ + public static void buildLazily() { + lazy = true; + SharedConstants.CHECK_DATA_FIXER_SCHEMA = false; + } + + /** The fixer {@code Minecraft} keeps: the game's, or the stand-in that builds it on first use. */ + public static DataFixer fixer() { + return lazy ? LazyDataFixer.INSTANCE : DataFixers.getDataFixer(); + } + + /** {@code Main}'s start-up optimization of {@code types}: none when the fixer may never be built. */ + public static CompletableFuture optimizeAtStart(Set types) { + return lazy ? CompletableFuture.completedFuture(null) : DataFixers.optimize(types); + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/datafix/LazyDataFixer.java b/incari-client/files/client/src/main/java/incari/client/datafix/LazyDataFixer.java new file mode 100644 index 0000000..0d49c85 --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/datafix/LazyDataFixer.java @@ -0,0 +1,29 @@ +package incari.client.datafix; + +import com.mojang.datafixers.DSL; +import com.mojang.datafixers.DataFixer; +import com.mojang.datafixers.schemas.Schema; +import com.mojang.serialization.Dynamic; +import net.minecraft.util.datafix.DataFixers; + +/** + * The game's data fixer, built the first time something needs upgrading. Data already at (or + * past) the version it's being upgraded to comes back untouched, as the real fixer returns it, + * without building anything; everything else goes to the real fixer. + */ +final class LazyDataFixer implements DataFixer { + + static final LazyDataFixer INSTANCE = new LazyDataFixer(); + + private LazyDataFixer() {} + + @Override + public Dynamic update(DSL.TypeReference type, Dynamic input, int version, int newVersion) { + return version >= newVersion ? input : DataFixers.getDataFixer().update(type, input, version, newVersion); + } + + @Override + public Schema getSchema(int key) { + return DataFixers.getDataFixer().getSchema(key); + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/datafix/package-info.java b/incari-client/files/client/src/main/java/incari/client/datafix/package-info.java new file mode 100644 index 0000000..1d30c23 --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/datafix/package-info.java @@ -0,0 +1,5 @@ +/** The game's data fixer, built only when something old needs upgrading (ADR 0025). */ +@NullMarked +package incari.client.datafix; + +import org.jspecify.annotations.NullMarked; diff --git a/incari-client/files/client/src/main/java/incari/client/eagler/EaglerAuth.java b/incari-client/files/client/src/main/java/incari/client/eagler/EaglerAuth.java new file mode 100644 index 0000000..4f87fbc --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/eagler/EaglerAuth.java @@ -0,0 +1,71 @@ +package incari.client.eagler; + +import incari.net.WebSocketUrl; +import incari.net.eagler.EaglerPassword; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import org.jspecify.annotations.Nullable; + +/** + * Passwords for Eagler servers that ask for one (ADR 0019). A password is kept in memory for + * the session, by server URL, and never written to disk: servers that want the player to stay + * logged in set a cookie instead ({@link EaglerCookies}). + * + *

When a login fails for want of a password, the Eagler session records it here, and the + * disconnection screen asks for one ({@link PasswordScreen}) instead of showing the refusal. + */ +public final class EaglerAuth { + + /** A server's request for a password, from the login that just failed. */ + public record Request(String server, int method, String message) {} + + private static final Object LOCK = new Object(); + private static final Map PASSWORDS = new HashMap<>(); + private static @Nullable Request pending; + + private EaglerAuth() {} + + /** The password to offer {@code server}, if the player gave one this session. */ + public static @Nullable EaglerPassword password(String server) { + synchronized (LOCK) { + return PASSWORDS.get(key(server)); + } + } + + /** Remembers the password for {@code server} for this session. */ + public static void remember(String server, EaglerPassword password) { + synchronized (LOCK) { + PASSWORDS.put(key(server), password); + } + } + + /** Forgets the password for {@code server}, as a new session would. */ + public static void forget(String server) { + synchronized (LOCK) { + PASSWORDS.remove(key(server)); + } + } + + /** The Eagler session: {@code server} refused the login for want of a password. */ + static void required(String server, int method, String message) { + synchronized (LOCK) { + pending = new Request(server, method, message); + } + } + + /** The request the last failed login left, once; null if it wasn't a password matter. */ + public static @Nullable Request takePending() { + synchronized (LOCK) { + Request request = pending; + pending = null; + return request; + } + } + + /** The server's URL as the client writes it, so "ws://host:1" and "ws://HOST:1/" are one. */ + private static String key(String server) { + WebSocketUrl url = WebSocketUrl.tryParse(server.trim()); + return (url != null ? url.toString() : server.trim()).toLowerCase(Locale.ROOT); + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/eagler/EaglerCookies.java b/incari-client/files/client/src/main/java/incari/client/eagler/EaglerCookies.java new file mode 100644 index 0000000..34bb370 --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/eagler/EaglerCookies.java @@ -0,0 +1,166 @@ +package incari.client.eagler; + +import com.mojang.logging.LogUtils; +import incari.net.WebSocketUrl; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import org.jspecify.annotations.Nullable; +import org.slf4j.Logger; + +/** + * Eagler server cookies (ADR 0019): up to 255 bytes a server stores in the client, for at + * most a week, and gets back with the next login. Auth plugins use them as session tokens, so a + * player logs in once rather than every join. A server chooses whether its cookie outlives the + * session; those are kept in {@code incari/eagler-cookies.txt}, the rest in memory only. + * + *

A cookie goes back only to the server that set it: the key is the server's WebSocket URL. + */ +public final class EaglerCookies { + + private static final Logger LOGGER = LogUtils.getLogger(); + private static final String FILE = "eagler-cookies.txt"; + /** The longest a server may keep a cookie, as Eagler's clients hold it to. */ + private static final long MAX_SECONDS = TimeUnit.DAYS.toSeconds(7); + + private static final int MAX_BYTES = 255; + + /** One server's cookie: its bytes, when it expires, whether it's kept on disk. */ + private static final class Cookie { + final byte[] data; + final long expiresMillis; + final boolean onDisk; + + Cookie(byte[] data, long expiresMillis, boolean onDisk) { + this.data = data; + this.expiresMillis = expiresMillis; + this.onDisk = onDisk; + } + } + + private static final Object LOCK = new Object(); + private static @Nullable EaglerCookies instance; + + private final Path file; + private final Map cookies = new HashMap<>(); + + private EaglerCookies(Path file) { + this.file = file; + } + + /** The store for the game in {@code gameDirectory}, loaded the first time it's asked for. */ + public static EaglerCookies get(Path gameDirectory) { + synchronized (LOCK) { + EaglerCookies store = instance; + if (store == null) { + store = new EaglerCookies(gameDirectory.resolve("incari").resolve(FILE)); + store.load(); + instance = store; + } + return store; + } + } + + /** The cookie {@code server} set, if it hasn't expired. */ + public byte @Nullable [] cookie(String server) { + synchronized (LOCK) { + Cookie cookie = cookies.get(key(server)); + if (cookie == null) { + return null; + } + if (System.currentTimeMillis() > cookie.expiresMillis) { + cookies.remove(key(server)); + if (cookie.onDisk) { + save(); + } + return null; + } + return cookie.data.clone(); + } + } + + /** + * {@code server} sets its cookie: {@code data} for {@code seconds}, kept on disk if {@code + * onDisk}. Empty data, a negative lifetime, or one past the limits clears it instead. + */ + public void set(String server, byte[] data, long seconds, boolean onDisk) { + synchronized (LOCK) { + Cookie previous; + if (data.length == 0 || seconds < 0 || seconds > MAX_SECONDS || data.length > MAX_BYTES) { + if (seconds > MAX_SECONDS || data.length > MAX_BYTES) { + LOGGER.warn( + "{} set a cookie past Eagler's limits ({} bytes, {} s); cleared", + server, + data.length, + seconds); + } + previous = cookies.remove(key(server)); + } else { + long expires = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(seconds); + previous = cookies.put(key(server), new Cookie(data.clone(), expires, onDisk)); + } + if (onDisk || (previous != null && previous.onDisk)) { + save(); + } + } + } + + private void load() { + if (!Files.isRegularFile(file)) { + return; + } + try { + long now = System.currentTimeMillis(); + for (String line : Files.readAllLines(file, StandardCharsets.UTF_8)) { + String[] parts = line.split("\t", -1); + if (parts.length != 3) { + continue; + } + long expires = Long.parseLong(parts[1]); + if (expires > now) { + cookies.put(parts[0], new Cookie(unhex(parts[2]), expires, true)); + } + } + } catch (IOException | RuntimeException e) { + LOGGER.warn("Couldn't read {}: {}", file, e.toString()); + } + } + + private void save() { + StringBuilder text = new StringBuilder(); + cookies.forEach((server, cookie) -> { + if (cookie.onDisk) { + text.append(server).append('\t').append(cookie.expiresMillis).append('\t'); + for (byte b : cookie.data) { + text.append(Character.forDigit((b >> 4) & 15, 16)).append(Character.forDigit(b & 15, 16)); + } + text.append('\n'); + } + }); + try { + Files.createDirectories(file.getParent()); + Files.writeString(file, text, StandardCharsets.UTF_8); + } catch (IOException e) { + LOGGER.warn("Couldn't save {}: {}", file, e.toString()); + } + } + + private static byte[] unhex(String hex) { + byte[] out = new byte[hex.length() / 2]; + for (int i = 0; i < out.length; i++) { + out[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2), 16); + } + return out; + } + + /** The server's URL as the client writes it, so "ws://host:1" and "ws://HOST:1/" are one. */ + private static String key(String server) { + WebSocketUrl url = WebSocketUrl.tryParse(server.trim()); + return (url != null ? url.toString() : server.trim()).toLowerCase(Locale.ROOT); + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/eagler/EaglerJoin.java b/incari-client/files/client/src/main/java/incari/client/eagler/EaglerJoin.java new file mode 100644 index 0000000..266e6f8 --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/eagler/EaglerJoin.java @@ -0,0 +1,107 @@ +package incari.client.eagler; + +import com.mojang.logging.LogUtils; +import incari.client.skins.EaglerSkins; +import incari.client.skins.OwnSkin; +import incari.net.eagler.EaglerMessages; +import incari.net.eagler.EaglerPauseMenu; +import incari.net.eagler.EaglerSession; +import io.netty.buffer.ByteBuf; +import java.nio.file.Path; +import java.util.UUID; +import net.minecraft.client.Minecraft; +import org.jspecify.annotations.Nullable; +import org.slf4j.Logger; + +/** + * Everything an Eagler connection the player joins does beside the game's packets: + * skins, voice, the server's cookie, its requests for a password, its redirects, and its pause menu. The + * connection's event loop calls in; each part takes what's its own. + */ +public final class EaglerJoin implements EaglerSession { + + private static final Logger LOGGER = LogUtils.getLogger(); + + private final String server; + private final Path gameDirectory; + private final EaglerSkins skins; + private final @Nullable EaglerVoice voice; + private int capabilities; + + private EaglerJoin(String server, Path gameDirectory, EaglerSkins skins, @Nullable EaglerVoice voice) { + this.server = server; + this.gameDirectory = gameDirectory; + this.skins = skins; + this.voice = voice; + } + + /** The session for a join of {@code server} (its WebSocket URL). */ + public static EaglerJoin start(String server) { + Path gameDirectory = Minecraft.getInstance().gameDirectory.toPath(); + EaglerSkins skins = EaglerSkins.start(OwnSkin.load(gameDirectory)); + return new EaglerJoin(server, gameDirectory, skins, EaglerVoice.start()); + } + + @Override + public void capabilities(int accepted) { + capabilities = accepted; + } + + @Override + public void loggedIn(String name, UUID uuid, EaglerMessages messages) { + skins.loggedIn(name, uuid, messages); + if (voice != null) { + voice.loggedIn(uuid, messages, (capabilities & incari.net.eagler.EaglerLogin.VOICE) != 0); + } + } + + @Override + public void received(int id, ByteBuf body) { + switch (id) { + case EaglerMessages.S_SET_COOKIE -> setCookie(body); + case EaglerMessages.S_REDIRECT -> ServerRedirects.redirect(EaglerMessages.readShortAscii(body)); + case EaglerMessages.S_CUSTOMIZE_PAUSE_MENU -> ServerPauseMenu.received(EaglerPauseMenu.read(body)); + case EaglerMessages.S_VOICE_ALLOWED, + EaglerMessages.S_VOICE_CONNECT, + EaglerMessages.S_VOICE_CONNECT_ANNOUNCE, + EaglerMessages.S_VOICE_DISCONNECT_PEER, + EaglerMessages.S_VOICE_ICE, + EaglerMessages.S_VOICE_DESCRIPTION, + EaglerMessages.S_VOICE_GLOBAL -> { + if (voice != null) { + voice.received(id, body); + } + } + default -> skins.received(id, body); + } + } + + @Override + public void authenticationRequired(int method, String message) { + EaglerAuth.required(server, method, message); + } + + @Override + public void redirected(String address) { + ServerRedirects.pending(address); + } + + @Override + public void closed() { + skins.closed(); + ServerPauseMenu.closed(); + if (voice != null) { + voice.closed(); + } + } + + private void setCookie(ByteBuf body) { + int flags = body.readUnsignedByte(); + long seconds = EaglerMessages.readVarLong(body); + byte[] data = new byte[body.readUnsignedByte()]; + body.readBytes(data); + boolean onDisk = (flags & 2) != 0; + LOGGER.info("{} set a {}-byte cookie for {} s{}", server, data.length, seconds, onDisk ? ", kept on disk" : ""); + EaglerCookies.get(gameDirectory).set(server, data, seconds, onDisk); + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/eagler/EaglerJoinFailures.java b/incari-client/files/client/src/main/java/incari/client/eagler/EaglerJoinFailures.java new file mode 100644 index 0000000..b9b5767 --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/eagler/EaglerJoinFailures.java @@ -0,0 +1,32 @@ +package incari.client.eagler; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.multiplayer.ServerData; +import net.minecraft.client.multiplayer.resolver.ServerAddress; + +/** An Eagler login that ended in a redirect or a request for a password (ADR 0019). */ +public final class EaglerJoinFailures { + + private EaglerJoinFailures() {} + + /** + * Follows a redirect, or asks for the password, left by the login that just failed. Returns + * false if it left neither. Render thread. + */ + public static boolean handle(Minecraft minecraft, Screen parent, ServerData server, ServerAddress address) { + String redirect = ServerRedirects.takePending(); + if (redirect != null) { + EaglerAuth.takePending(); + // Starting a connection replaces the screen being set up: after its init. + minecraft.execute(() -> ServerRedirects.join(minecraft, parent, redirect)); + return true; + } + EaglerAuth.Request request = EaglerAuth.takePending(); + if (request != null) { + minecraft.execute(() -> minecraft.gui.setScreen(new PasswordScreen(parent, server, address, request))); + return true; + } + return false; + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/eagler/EaglerVoice.java b/incari-client/files/client/src/main/java/incari/client/eagler/EaglerVoice.java new file mode 100644 index 0000000..01c2c6e --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/eagler/EaglerVoice.java @@ -0,0 +1,579 @@ +package incari.client.eagler; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.mojang.logging.LogUtils; +import incari.client.platform.ClientPlatform; +import incari.net.eagler.EaglerMessages; +import incari.platform.api.rtc.IceServer; +import incari.platform.api.rtc.Microphone; +import incari.platform.api.rtc.PlatformRtc; +import incari.platform.api.rtc.RtcPeer; +import io.netty.buffer.ByteBuf; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.client.Minecraft; +import net.minecraft.client.player.AbstractClientPlayer; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.phys.Vec3; +import org.jspecify.annotations.Nullable; +import org.slf4j.Logger; + +/** + * Eagler voice chat on one connection (ADR 0019). The server only signals: it tells each + * client who else has voice on, pairs two clients up when one asks ({@code C_VOICE_REQUEST}), and + * relays their WebRTC offers, answers and ICE candidates. The audio goes peer to peer, through the + * platform's WebRTC ({@link PlatformRtc}), which only the browser has. + * + *

In the global channel every voice player is paired up; in proximity, those within range, + * whose voices then fade with distance and pan with direction. Talking is push to talk. + * + *

Messages arrive on the connection's event loop and are handed to the game's thread; everything + * else happens there. + */ +public final class EaglerVoice { + + private static final Logger LOGGER = LogUtils.getLogger(); + /** Proximity peers are asked for this much beyond the range, so they're ready before heard. */ + private static final double CONNECT_MARGIN = 6.0; + /** A proximity peer out of range this long is let go. */ + private static final long LINGER_MILLIS = 5000; + /** A level over this means a peer is talking. */ + private static final float TALKING_LEVEL = 0.06F; + /** How long a peer still counts as talking after its last loud moment: speech has gaps. */ + private static final long TALKING_HOLD_MILLIS = 600; + + private static @Nullable EaglerVoice current; + private static @Nullable VoiceSettings settings; + + private final PlatformRtc rtc; + private final Map peers = new HashMap<>(); + /** Everyone with voice on, from the server's list: names by UUID. */ + private final Map voicePlayers = new LinkedHashMap<>(); + /** Peers asked for and not yet connected, so each is asked once. */ + private final Set requested = new HashSet<>(); + /** When a proximity peer was last in range. */ + private final Map lastInRange = new HashMap<>(); + /** The players the player muted on this connection, whether paired with them now or not. */ + private final Set muted = new HashSet<>(); + + private @Nullable EaglerMessages messages; + private @Nullable UUID self; + private boolean capability; + private boolean serverAllows; + private List iceServers = List.of(); + /** The channel the server was told about: OFF until connected. */ + private VoiceSettings.Channel joined = VoiceSettings.Channel.OFF; + + private boolean transmitting; + + private EaglerVoice(PlatformRtc rtc) { + this.rtc = rtc; + } + + /** Whether this platform can do voice at all. */ + public static boolean supported() { + return ClientPlatform.get().rtc().supported(); + } + + /** Voice for a new connection, or null where there's no WebRTC. */ + static @Nullable EaglerVoice start() { + if (!supported()) { + return null; + } + EaglerVoice voice = new EaglerVoice(ClientPlatform.get().rtc()); + Minecraft.getInstance().execute(() -> { + EaglerVoice previous = current; + if (previous != null) { + previous.shutDown(); + } + current = voice; + }); + return voice; + } + + /** The voice of the connection the player is on, if it has any. Game thread. */ + public static @Nullable EaglerVoice current() { + return current; + } + + /** The player's voice settings. Game thread. */ + public static VoiceSettings settings() { + VoiceSettings loaded = settings; + if (loaded == null) { + loaded = VoiceSettings.load(Minecraft.getInstance().gameDirectory.toPath()); + settings = loaded; + } + return loaded; + } + + // --- The connection's event loop --------------------------------------------------------- + + void loggedIn(UUID uuid, EaglerMessages sender, boolean accepted) { + Minecraft.getInstance().execute(() -> { + self = uuid; + messages = sender; + capability = accepted; + }); + } + + void received(int id, ByteBuf body) { + // Parsed here, where the buffer is valid; acted on, on the game's thread. + Runnable action = parse(id, body); + if (action != null) { + Minecraft.getInstance().execute(action); + } + } + + void closed() { + Minecraft.getInstance().execute(() -> { + shutDown(); + if (current == this) { + current = null; + } + }); + } + + private @Nullable Runnable parse(int id, ByteBuf body) { + return switch (id) { + case EaglerMessages.S_VOICE_ALLOWED -> { + boolean allowed = body.readBoolean(); + List servers = new ArrayList<>(); + if (allowed) { + int count = EaglerMessages.readVarInt(body); + for (int i = 0; i < count && i < 64; i++) { + IceServer server = IceServer.parseEagler(EaglerMessages.readString(body)); + if (server != null) { + servers.add(server); + } + } + } + yield () -> allowed(allowed, servers); + } + case EaglerMessages.S_VOICE_CONNECT -> { + UUID peer = uuid(body); + boolean offer = body.readBoolean(); + yield () -> connect(peer, offer); + } + case EaglerMessages.S_VOICE_CONNECT_ANNOUNCE -> { + UUID peer = uuid(body); + yield () -> announced(peer); + } + case EaglerMessages.S_VOICE_DISCONNECT_PEER -> { + UUID peer = uuid(body); + yield () -> close(peer, false); + } + case EaglerMessages.S_VOICE_ICE -> { + UUID peer = uuid(body); + String json = bytesText(body); + yield () -> remoteCandidate(peer, json); + } + case EaglerMessages.S_VOICE_DESCRIPTION -> { + UUID peer = uuid(body); + String json = bytesText(body); + yield () -> remoteDescription(peer, json); + } + case EaglerMessages.S_VOICE_GLOBAL -> { + int count = EaglerMessages.readVarInt(body); + List uuids = new ArrayList<>(); + for (int i = 0; i < count; i++) { + uuids.add(uuid(body)); + } + List names = new ArrayList<>(); + if (body.isReadable()) { + for (int i = 0; i < count; i++) { + names.add(EaglerMessages.readString(body)); + } + } + yield () -> global(uuids, names); + } + default -> null; + }; + } + + // --- The game's thread ------------------------------------------------------------------- + + /** Whether this server has voice and the player may use it. */ + public boolean available() { + return capability && serverAllows; + } + + /** The channel the player chose; takes effect on this server at once. */ + public void setChannel(VoiceSettings.Channel channel) { + settings().setChannel(channel); + apply(); + } + + public void setListenVolume(float volume) { + settings().setListenVolume(volume); + } + + public void setMicrophoneVolume(float volume) { + settings().setMicrophoneVolume(volume); + rtc.microphone().setVolume(volume); + } + + public void setRange(int blocks) { + settings().setRange(blocks); + } + + /** The microphone's state, for the voice screen. */ + public Microphone.State microphone() { + return rtc.microphone().state(); + } + + /** Whether the player is sending their voice now. */ + public boolean transmitting() { + return transmitting; + } + + /** Players connected by voice now: their names, and whether each is talking. */ + public List speakers() { + List speakers = new ArrayList<>(); + for (Map.Entry entry : peers.entrySet()) { + Peer peer = entry.getValue(); + if (peer.audio) { + speakers.add(new Speaker( + entry.getKey(), name(entry.getKey()), peer.talking, muted.contains(entry.getKey()))); + } + } + return speakers; + } + + /** One voice: who, whether they're talking, whether the player muted them. */ + public record Speaker(UUID uuid, String name, boolean talking, boolean muted) {} + + /** + * Mutes or unmutes one player's voice, for this connection: kept by UUID, so it holds when the + * two are paired again (out of range and back, or a dropped peer). + */ + public void setMuted(UUID player, boolean mute) { + if (mute) { + muted.add(player); + } else { + muted.remove(player); + } + } + + /** {@link incari.client.IncariTicks}: once a tick, on the game's thread. */ + public static void tick(Minecraft minecraft, boolean pushToTalk) { + EaglerVoice voice = current; + if (voice != null) { + voice.update(minecraft, pushToTalk); + } + } + + private void allowed(boolean allowed, List servers) { + serverAllows = allowed; + iceServers = List.copyOf(servers); + LOGGER.info("The server {} voice chat ({} ICE servers)", allowed ? "has" : "doesn't have", servers.size()); + apply(); + } + + /** Brings this server in line with the player's channel. */ + private void apply() { + VoiceSettings.Channel wanted = available() ? settings().channel() : VoiceSettings.Channel.OFF; + if (wanted == joined) { + return; + } + if (joined != VoiceSettings.Channel.OFF) { + closeAll(true); + send(EaglerMessages.C_VOICE_DISCONNECT, body -> {}); + if (wanted == VoiceSettings.Channel.OFF) { + // Voice off: the microphone goes too, and the browser stops showing it recording. + releaseMicrophone(); + } + } + joined = wanted; + LOGGER.info("Voice: {} channel", wanted.name().toLowerCase(java.util.Locale.ROOT)); + if (wanted != VoiceSettings.Channel.OFF) { + Microphone microphone = rtc.microphone(); + microphone.open(); + microphone.setVolume(settings().microphoneVolume()); + send(EaglerMessages.C_VOICE_CONNECT, body -> {}); + if (wanted == VoiceSettings.Channel.GLOBAL) { + voicePlayers.keySet().forEach(this::request); + } + } + } + + private void global(List uuids, List names) { + LOGGER.info("Voice: {} players have voice on", uuids.size()); + voicePlayers.clear(); + for (int i = 0; i < uuids.size(); i++) { + voicePlayers.put( + uuids.get(i), i < names.size() ? names.get(i) : uuids.get(i).toString()); + } + if (joined == VoiceSettings.Channel.GLOBAL) { + uuids.forEach(this::request); + } + } + + /** {@code peer} turned voice on: asked for now in global chat, when in range in proximity. */ + private void announced(UUID peer) { + requested.remove(peer); + if (joined == VoiceSettings.Channel.GLOBAL) { + request(peer); + } + } + + /** Asks the server to pair this client with {@code peer}. */ + private void request(UUID peer) { + if (joined == VoiceSettings.Channel.OFF + || peer.equals(self) + || peers.containsKey(peer) + || !requested.add(peer)) { + return; + } + LOGGER.info("Voice: asking to pair with {}", name(peer)); + send(EaglerMessages.C_VOICE_REQUEST, body -> writeUuid(body, peer)); + } + + private void connect(UUID uuid, boolean offer) { + if (joined == VoiceSettings.Channel.OFF) { + return; + } + requested.remove(uuid); + close(uuid, true); + LOGGER.info("Voice: pairing with {}{}", name(uuid), offer ? ", offering" : ""); + Peer peer = new Peer(uuid); + peer.connection = rtc.createPeer(iceServers, peer); + peer.connection.sendMicrophone(); + peers.put(uuid, peer); + if (offer) { + peer.connection.createOffer(); + } + } + + private void remoteDescription(UUID uuid, String json) { + Peer peer = peers.get(uuid); + if (peer != null && peer.connection != null) { + peer.connection.setRemoteDescription(json); + } + } + + private void remoteCandidate(UUID uuid, String json) { + Peer peer = peers.get(uuid); + if (peer == null || peer.connection == null) { + return; + } + try { + JsonObject candidate = JsonParser.parseString(json).getAsJsonObject(); + // Eagler's clients send the line index as a string. + int index = Integer.parseInt(candidate.get("sdpMLineIndex").getAsString()); + peer.connection.addIceCandidate(candidate.get("candidate").getAsString(), index); + } catch (RuntimeException e) { + LOGGER.warn("Unreadable ICE candidate from {}: {}", uuid, e.toString()); + } + } + + /** Ends the connection to {@code uuid}; tells the server unless {@code quietly}. */ + private void close(UUID uuid, boolean quietly) { + requested.remove(uuid); + Peer peer = peers.remove(uuid); + if (peer == null) { + return; + } + if (peer.connection != null) { + peer.connection.close(); + } + if (!quietly) { + send(EaglerMessages.C_VOICE_DISCONNECT_PEER, body -> writeUuid(body, uuid)); + } + } + + private void closeAll(boolean quietly) { + for (UUID uuid : new ArrayList<>(peers.keySet())) { + close(uuid, quietly); + } + requested.clear(); + lastInRange.clear(); + } + + private void shutDown() { + boolean wasOn = joined != VoiceSettings.Channel.OFF; + closeAll(true); + joined = VoiceSettings.Channel.OFF; + // Only the voice that opened it lets it go: an old connection closing after the next one + // turned voice on leaves the new one's microphone be. + if (wasOn) { + releaseMicrophone(); + } + } + + /** Stops sending and closes the microphone (the platform's one, shared by every connection). */ + private void releaseMicrophone() { + if (transmitting) { + rtc.microphone().setTransmitting(false); + transmitting = false; + } + rtc.microphone().close(); + } + + private void update(Minecraft minecraft, boolean pushToTalk) { + if (joined == VoiceSettings.Channel.OFF) { + return; + } + boolean talk = pushToTalk && rtc.microphone().state() == Microphone.State.OPEN; + if (talk != transmitting) { + transmitting = talk; + rtc.microphone().setTransmitting(talk); + } + Player player = minecraft.player; + if (player == null || minecraft.level == null) { + return; + } + VoiceSettings settings = settings(); + long now = System.currentTimeMillis(); + Vec3 ear = player.getEyePosition(); + Vec3 right = Vec3.directionFromRotation(0, player.getYRot() + 90); + for (AbstractClientPlayer other : minecraft.level.players()) { + if (other.getUUID().equals(player.getUUID())) { + continue; + } + UUID uuid = other.getUUID(); + Vec3 toPeer = other.getEyePosition().subtract(ear); + double distance = toPeer.length(); + Peer peer = peers.get(uuid); + if (joined == VoiceSettings.Channel.PROXIMITY) { + if (distance <= settings.range() + CONNECT_MARGIN) { + lastInRange.put(uuid, now); + request(uuid); + } + if (peer != null && peer.connection != null) { + float falloff = (float) Math.max(0, 1 - distance / settings.range()); + float pan = distance < 0.5 ? 0 : (float) (toPeer.normalize().dot(right) * 0.8); + peer.connection.voice().setVolume(muted.contains(uuid) ? 0 : settings.listenVolume() * falloff); + peer.connection.voice().setPan(pan); + } + } + } + for (Map.Entry entry : new ArrayList<>(peers.entrySet())) { + Peer peer = entry.getValue(); + if (peer.connection == null) { + continue; + } + if (joined == VoiceSettings.Channel.GLOBAL) { + peer.connection.voice().setVolume(muted.contains(entry.getKey()) ? 0 : settings.listenVolume()); + peer.connection.voice().setPan(0); + } else if (now - lastInRange.getOrDefault(entry.getKey(), 0L) > LINGER_MILLIS) { + // Gone out of range (or out of sight): let go, and tell the server. + close(entry.getKey(), false); + continue; + } + if (!muted.contains(entry.getKey()) && peer.connection.voice().level() > TALKING_LEVEL) { + peer.lastLoud = now; + } + boolean talking = now - peer.lastLoud < TALKING_HOLD_MILLIS; + if (talking && !peer.talking) { + // Once per stretch of talk: the browser checks watch for it. + LOGGER.info("Voice: {} is talking", name(entry.getKey())); + } + peer.talking = talking; + } + } + + private String name(UUID uuid) { + String name = voicePlayers.get(uuid); + if (name != null) { + return name; + } + Minecraft minecraft = Minecraft.getInstance(); + if (minecraft.getConnection() != null) { + var info = minecraft.getConnection().getPlayerInfo(uuid); + if (info != null) { + return info.getProfile().name(); + } + } + return uuid.toString(); + } + + private void send(int id, java.util.function.Consumer body) { + EaglerMessages sender = messages; + if (sender != null) { + sender.send(id, body); + } + } + + private static UUID uuid(ByteBuf body) { + return new UUID(body.readLong(), body.readLong()); + } + + private static void writeUuid(ByteBuf body, UUID uuid) { + body.writeLong(uuid.getMostSignificantBits()); + body.writeLong(uuid.getLeastSignificantBits()); + } + + private static String bytesText(ByteBuf body) { + int length = EaglerMessages.readVarInt(body); + String text = body.toString(body.readerIndex(), length, StandardCharsets.UTF_8); + body.skipBytes(length); + return text; + } + + private static void writeBytesText(ByteBuf body, String text) { + byte[] bytes = text.getBytes(StandardCharsets.UTF_8); + EaglerMessages.writeVarInt(body, bytes.length); + body.writeBytes(bytes); + } + + /** One voice connection, and what its WebRTC peer says. Game thread. */ + private final class Peer implements RtcPeer.Listener { + + final UUID uuid; + + @Nullable + RtcPeer connection; + + boolean audio; + boolean talking; + /** When the peer was last louder than {@link #TALKING_LEVEL}. */ + long lastLoud = Long.MIN_VALUE / 2; + + Peer(UUID uuid) { + this.uuid = uuid; + } + + @Override + public void localDescription(String json) { + send(EaglerMessages.C_VOICE_DESCRIPTION, body -> { + writeUuid(body, uuid); + writeBytesText(body, json); + }); + } + + @Override + public void iceCandidate(String candidate, int sdpMLineIndex) { + JsonObject json = new JsonObject(); + // As Eagler's clients write it: the index as a string. + json.addProperty("sdpMLineIndex", Integer.toString(sdpMLineIndex)); + json.addProperty("candidate", candidate); + String text = json.toString(); + send(EaglerMessages.C_VOICE_ICE, body -> { + writeUuid(body, uuid); + writeBytesText(body, text); + }); + } + + @Override + public void remoteAudio() { + audio = true; + LOGGER.info("Voice: connected to {}", name(uuid)); + } + + @Override + public void stateChanged(String state) { + if (("failed".equals(state) || "disconnected".equals(state)) && peers.get(uuid) == this) { + LOGGER.info("Voice connection to {} {}", name(uuid), state); + close(uuid, false); + } + } + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/eagler/PasswordScreen.java b/incari-client/files/client/src/main/java/incari/client/eagler/PasswordScreen.java new file mode 100644 index 0000000..23ea1aa --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/eagler/PasswordScreen.java @@ -0,0 +1,152 @@ +package incari.client.eagler; + +import incari.net.eagler.EaglerPassword; +import java.util.List; +import net.minecraft.ChatFormatting; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphicsExtractor; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.components.CycleButton; +import net.minecraft.client.gui.components.EditBox; +import net.minecraft.client.gui.components.MultiLineTextWidget; +import net.minecraft.client.gui.screens.ConnectScreen; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.input.KeyEvent; +import net.minecraft.client.multiplayer.ServerData; +import net.minecraft.client.multiplayer.resolver.ServerAddress; +import net.minecraft.network.chat.CommonComponents; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.Style; +import net.minecraft.util.FormattedCharSequence; +import org.jspecify.annotations.Nullable; + +/** + * Asks for the password an Eagler server's auth plugin wants (ADR 0019), then joins again + * with it. The server's own words are shown above the field. A server that wants the password + * unhashed gets it only if the player agrees on this screen: anyone between the player and the + * server could read it. + * + *

English only for now; Incari's screens don't have language files yet. + */ +public final class PasswordScreen extends Screen { + + /** Below the title (drawn at 17): where the server's message may start. */ + private static final int TITLE_BOTTOM = 32; + + private final Screen parent; + private final ServerData server; + private final ServerAddress address; + private final EaglerAuth.Request request; + + private boolean plaintextAllowed; + private @Nullable EditBox password; + private @Nullable Button logIn; + + public PasswordScreen(Screen parent, ServerData server, ServerAddress address, EaglerAuth.Request request) { + super(Component.literal("Password")); + this.parent = parent; + this.server = server; + this.address = address; + this.request = request; + } + + private boolean plaintext() { + return request.method() == EaglerPassword.PLAINTEXT; + } + + /** Where the plain-text notice is drawn: just above the password field. */ + private int noticeY() { + return this.height / 2 - 20 - 14; + } + + @Override + protected void init() { + int x = this.width / 2 - 100; + int y = this.height / 2 - 20; + String said = request.message().isBlank() ? "This server needs a password." : request.message(); + // The server's message sits just above the field (and the plain-text notice), as many lines + // as fit below the title: a long one is cut, never drawn over the notice or the field. + int bottom = noticeY() - (plaintext() ? 4 : -5); + int rows = Math.max(1, (bottom - TITLE_BOTTOM) / this.font.lineHeight); + MultiLineTextWidget message = new MultiLineTextWidget(Component.literal(said), this.font) + .setMaxWidth(300) + .setMaxRows(rows) + .setCentered(true); + // The widget is as wide as its longest line: centred over the field, not left-aligned to it. + message.setPosition(this.width / 2 - message.getWidth() / 2, bottom - message.getHeight()); + this.addRenderableWidget(message); + EditBox box = new EditBox(this.font, x, y, 200, 20, password, Component.literal("Password")); + box.setMaxLength(127); + // Shown as stars; the text itself stays in the box. + box.addFormatter((text, offset) -> FormattedCharSequence.forward("*".repeat(text.length()), Style.EMPTY)); + box.setResponder(text -> updateLogIn()); + password = this.addRenderableWidget(box); + int buttons = y + 30; + if (plaintext()) { + this.addRenderableWidget( + CycleButton.builder(allowed -> Component.literal(allowed ? "Yes" : "No"), plaintextAllowed) + .withValues(List.of(false, true)) + .create(x, buttons, 200, 20, Component.literal("Send as plain text"), (button, allowed) -> { + plaintextAllowed = allowed; + updateLogIn(); + })); + buttons += 24; + } + logIn = this.addRenderableWidget(Button.builder(Component.literal("Log In"), button -> logIn()) + .bounds(x, buttons, 98, 20) + .build()); + this.addRenderableWidget(Button.builder(CommonComponents.GUI_CANCEL, button -> onClose()) + .bounds(x + 102, buttons, 98, 20) + .build()); + this.setInitialFocus(box); + updateLogIn(); + } + + private void updateLogIn() { + Button button = logIn; + if (button != null) { + button.active = !typed().isEmpty() && (!plaintext() || plaintextAllowed); + } + } + + private String typed() { + EditBox box = password; + return box == null ? "" : box.getValue(); + } + + private void logIn() { + EaglerAuth.remember(request.server(), new EaglerPassword(typed(), plaintextAllowed)); + Minecraft minecraft = Minecraft.getInstance(); + ConnectScreen.startConnecting(parent, minecraft, address, server, false, null); + } + + @Override + public boolean keyPressed(KeyEvent event) { + Button button = logIn; + if (event.isConfirmation() && button != null && button.active) { + logIn(); + return true; + } + return super.keyPressed(event); + } + + @Override + public void extractRenderState(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) { + super.extractRenderState(graphics, mouseX, mouseY, a); + graphics.centeredText(this.font, this.title, this.width / 2, 17, 0xFFFFFFFF); + if (plaintext()) { + graphics.centeredText( + this.font, + Component.literal("This server wants your password as plain text.") + .withStyle(ChatFormatting.YELLOW), + this.width / 2, + noticeY(), + 0xFFFFFFFF); + } + } + + @Override + public void onClose() { + Minecraft.getInstance().gui.setScreen(parent); + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/eagler/PauseMenuHooks.java b/incari-client/files/client/src/main/java/incari/client/eagler/PauseMenuHooks.java new file mode 100644 index 0000000..0e49a27 --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/eagler/PauseMenuHooks.java @@ -0,0 +1,53 @@ +package incari.client.eagler; + +import incari.client.settings.IncariSettingsScreen; +import incari.client.ui.Icons; +import incari.client.ui.Ui; +import java.util.function.Consumer; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.components.AbstractWidget; +import net.minecraft.client.gui.components.Renderable; +import net.minecraft.client.gui.layouts.GridLayout; +import net.minecraft.client.gui.screens.Screen; + +/** + * What Incari adds to the pause menu: Incari Settings' button, an Eagler server's own buttons and + * icons, and voice chat. + */ +public final class PauseMenuHooks { + + private PauseMenuHooks() {} + + /** + * {@code PauseScreen}, in the button grid below the row of icon buttons: Incari Settings, with + * Incari's badge (everything else of Incari's is behind it), then the server's own buttons. + */ + public static void addButtons(GridLayout.RowHelper row) { + row.addChild( + Ui.menuButton(IncariSettingsScreen.TITLE, Icons.INCARI, 204, () -> { + Minecraft minecraft = Minecraft.getInstance(); + minecraft.gui.setScreen(new IncariSettingsScreen(minecraft.gui.screen())); + }) + .centered(), + 2); + ServerPauseMenu.addButtons(row); + } + + /** + * {@code PauseScreen.getCustomAdditions}: whether the server sent pause menu buttons of its + * own, which take the Server Links button's place. + */ + public static boolean replacesServerLinks() { + return ServerPauseMenu.active(); + } + + /** {@code PauseScreen}, after its widgets: the voice panel, and the icons over the buttons. */ + public static void addOverlays( + Screen screen, Consumer addWidget, Consumer addRenderable) { + ServerPauseMenu.addIcons(screen, addRenderable); + VoicePanel voice = VoicePanel.create(screen); + if (voice != null) { + addWidget.accept(voice); + } + } +} diff --git a/incari-client/files/client/src/main/java/incari/client/eagler/ServerPauseMenu.java b/incari-client/files/client/src/main/java/incari/client/eagler/ServerPauseMenu.java new file mode 100644 index 0000000..cfbcf82 --- /dev/null +++ b/incari-client/files/client/src/main/java/incari/client/eagler/ServerPauseMenu.java @@ -0,0 +1,290 @@ +package incari.client.eagler; + +import com.mojang.blaze3d.Blaze3D; +import com.mojang.blaze3d.platform.NativeImage; +import com.mojang.logging.LogUtils; +import incari.client.ui.Ui; +import incari.net.eagler.EaglerPauseMenu; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphicsExtractor; +import net.minecraft.client.gui.components.AbstractWidget; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.components.Renderable; +import net.minecraft.client.gui.components.StringWidget; +import net.minecraft.client.gui.components.events.GuiEventListener; +import net.minecraft.client.gui.layouts.GridLayout; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.renderer.RenderPipelines; +import net.minecraft.client.renderer.texture.DynamicTexture; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.contents.TranslatableContents; +import net.minecraft.resources.Identifier; +import net.minecraft.util.FormattedCharSequence; +import org.jspecify.annotations.Nullable; +import org.slf4j.Logger; + +/** + * The pause menu an EaglerXServer customizes (its {@code pause_menu.yml}): a "server info" button + * and a Discord button, which open their links, and small icons beside the menu's buttons and title, + * as Eagler's 1.8 client shows them. Kept for the connection that sent it. The game's thread only. + * + *

A server info button that shows markup the server sends, in a web view, isn't shown: the page + * has no web view yet. One that shows an address in a web view opens it in a new tab instead. + */ +public final class ServerPauseMenu { + + private static final Logger LOGGER = LogUtils.getLogger(); + private static final int FULL_WIDTH = 204; + private static final int HALF_WIDTH = 98; + private static final int ICON_SIZE = 16; + private static final int ICON_GAP = 4; + + /** The vanilla buttons' labels, by the name Eagler's icon keys give each. */ + private static final Map BUTTON_KEYS = Map.of( + "menu.returnToGame", "backToGame", + "gui.advancements", "achievements", + "gui.stats", "statistics", + "menu.options", "options", + "menu.disconnect", "disconnect", + "menu.returnToMenu", "disconnect"); + + private static @Nullable ServerPauseMenu current; + + private final EaglerPauseMenu menu; + /** Each icon key's texture, and its image's size. */ + private final Map icons = new HashMap<>(); + + private record Icon(Identifier texture, int width, int height) {} + + private ServerPauseMenu(EaglerPauseMenu menu) { + this.menu = menu; + Map uploaded = new HashMap<>(); + menu.icons().forEach((key, image) -> { + // Keys often share an image (the server sends each once); upload each once. + Identifier texture = uploaded.computeIfAbsent(image, _ -> upload(uploaded.size(), image)); + icons.put(key, new Icon(texture, image.width(), image.height())); + }); + } + + /** The message arrived (any thread): this connection's menu from now on. */ + static void received(EaglerPauseMenu menu) { + Minecraft.getInstance().execute(() -> { + clear(); + current = new ServerPauseMenu(menu); + }); + } + + /** The connection ended (any thread). */ + static void closed() { + Minecraft.getInstance().execute(ServerPauseMenu::clear); + } + + private static void clear() { + ServerPauseMenu menu = current; + if (menu != null) { + for (Icon icon : Map.copyOf(menu.icons).values()) { + Minecraft.getInstance().getTextureManager().release(icon.texture()); + } + current = null; + } + } + + private static Identifier upload(int index, EaglerPauseMenu.Image image) { + Identifier id = Identifier.fromNamespaceAndPath("incari", "pause_menu/icon_" + index); + NativeImage pixels = new NativeImage(image.width(), image.height(), false); + for (int y = 0; y < image.height(); y++) { + for (int x = 0; x < image.width(); x++) { + pixels.setPixel(x, y, image.pixel(x, y)); + } + } + // Registering again under the same id closes the texture it replaces. + Minecraft.getInstance().getTextureManager().register(id, new DynamicTexture(id::toString, pixels)); + return id; + } + + /** Whether this connection's server sent a pause menu with any button of its own. */ + static boolean active() { + ServerPauseMenu menu = current; + return menu != null && (menu.menu.serverInfo() != null || menu.menu.discord() != null); + } + + // --- The pause screen ---------------------------------------------------------------------- + + /** + * {@code PauseScreen}, below the row of icon buttons: the server's own buttons, side by side if + * both fit in half the width. + */ + public static void addButtons(GridLayout.RowHelper row) { + ServerPauseMenu menu = current; + if (menu == null) { + return; + } + List