diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 8d8687753..5567eb184 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -6,7 +6,6 @@ /.github/ @ludovic111 /tools/ci/ @ludovic111 /tools/release_train.py @ludovic111 -/tools/release_channels.py @ludovic111 /crates/horizon-release-sign/ @ludovic111 /crates/horizon-server/src/update.rs @ludovic111 /crates/horizon-server/Cargo.toml @ludovic111 diff --git a/.github/release-line.txt b/.github/release-line.txt new file mode 100644 index 000000000..3b04cfb60 --- /dev/null +++ b/.github/release-line.txt @@ -0,0 +1 @@ +0.2 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d6577d49e..8966854c2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,6 +18,10 @@ concurrency: # A new push to a pull request replaces its running checks; main's runs all finish (releases follow them). group: checks-${{ github.event.pull_request.number || github.sha }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} +env: + # Test runs never reach the telemetry server: no live-count ping, no uploads (docs/telemetry.md). + HORIZON_TELEMETRY_URL: "off" + jobs: verify: runs-on: ubuntu-latest diff --git a/.github/workflows/launcher.yml b/.github/workflows/launcher.yml index 79ea852fb..02c61cdd1 100644 --- a/.github/workflows/launcher.yml +++ b/.github/workflows/launcher.yml @@ -49,6 +49,10 @@ concurrency: group: launcher-${{ github.ref == 'refs/heads/main' && 'release' || github.ref }} cancel-in-progress: false +env: + # Test runs never reach the telemetry server: no live-count ping, no uploads (docs/telemetry.md). + HORIZON_TELEMETRY_URL: "off" + jobs: decide: runs-on: ubuntu-latest @@ -188,9 +192,6 @@ jobs: retry "$launcher" install latest "$launcher" versions --installed "$launcher" links --json - "$launcher" menu-style classic - grep -qx 'menuStyle:classic' "$HORIZON_HOME/horizon.txt" - "$launcher" menu-style horizon clients=("$HORIZON_LAUNCHER_HOME"/versions/v*/horizon-client*) client="${clients[0]}" echo "installed client: $client" diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 689cdae59..51f9e89cd 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -23,6 +23,10 @@ permissions: concurrency: group: nightly-audit cancel-in-progress: false +env: + # Test runs never reach the telemetry server: no live-count ping, no uploads (docs/telemetry.md). + HORIZON_TELEMETRY_URL: "off" + jobs: audit: runs-on: [self-hosted, horizon-game] diff --git a/.github/workflows/parity.yml b/.github/workflows/parity.yml index 7289fe4de..a18fc5019 100644 --- a/.github/workflows/parity.yml +++ b/.github/workflows/parity.yml @@ -15,6 +15,10 @@ on: required: true permissions: contents: read +env: + # Test runs never reach the telemetry server: no live-count ping, no uploads (docs/telemetry.md). + HORIZON_TELEMETRY_URL: "off" + jobs: parity: runs-on: [self-hosted, horizon-game] diff --git a/.github/workflows/promote.yml b/.github/workflows/promote.yml deleted file mode 100644 index 3966f571b..000000000 --- a/.github/workflows/promote.yml +++ /dev/null @@ -1,55 +0,0 @@ -name: promote -# Beta game releases become stable once a day (docs/release-flow.md, "Channels"): at 20:00 UTC (21:00 in Paris in -# winter time, 22:00 in summer) tools/release_channels.py promotes the newest beta that had been out 6 hours by then, -# passed its release smoke test and isn't covered by an issue labelled release-blocker. Launchers on the Alpha -# channel install every beta when it is published; Stable gets the day's promotion. The later runs of the evening are -# retries for a run GitHub starts late or skips: they promote the same beta, so stable still moves once. -# By hand, from GitHub's app too (Actions > promote > Run workflow): -# gh workflow run promote -f tag=v0.2.3 # that beta now, without waiting for 20:00 -# gh workflow run promote -f tag=v0.2.3 -f force=true # even blocked or without its smoke test -# gh workflow run promote -f dry_run=true # say what would be promoted -# Holding betas back: label an issue release-blocker. While it is open it holds every beta; closed as completed it -# still holds the betas published before it closed. The issue's text is never read (its author could edit it). -# When the oldest waiting beta is 30 hours old (it missed a promotion it was due for), an issue "Promotion to stable -# has stalled" says so; it closes itself after the next promotion. -on: - schedule: - - cron: '7,37 20-21 * * *' - workflow_dispatch: - inputs: - tag: - description: The beta to promote now (empty = the newest beta that is due) - type: string - default: '' - force: - description: Promote that tag even if a release-blocker covers it or its smoke test didn't run - type: boolean - default: false - dry_run: - description: Say what would be promoted, change nothing - type: boolean - default: false -permissions: - contents: write - issues: write -concurrency: - group: promote - cancel-in-progress: false -jobs: - promote: - runs-on: ubuntu-latest - timeout-minutes: 10 - steps: - - uses: actions/checkout@v4 - with: - # The notes of a promoted release cover every pull request since the last stable one. - fetch-depth: 0 - # gh uses GH_TOKEN below; nothing needs git credentials on disk. - persist-credentials: false - - name: Promote - env: - GH_TOKEN: ${{ github.token }} - TAG: ${{ inputs.tag }} - FORCE: ${{ inputs.force && 'yes' || '' }} - DRY_RUN: ${{ (inputs.dry_run || github.ref != 'refs/heads/main') && 'yes' || '' }} - run: python3 tools/release_channels.py promote ${TAG:+--tag "$TAG"} ${FORCE:+--force} ${DRY_RUN:+--dry-run} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b19ba9ce5..95a2fec64 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -3,12 +3,15 @@ name: release # release waiting for merges to settle goes out without another merge) and by hand, tools/release_train.py decides: # a release when pull requests merged since the last one changed what players run and the newest merged 5 minutes # ago (the oldest 20 minutes ago, if merges never pause), or at once for a pull request labelled release-now. -# RELEASES_PAUSED=1 (repository variable) stops them. +# RELEASES_PAUSED=1 (repository variable) stops them; so does an open issue labelled release-blocker, forced runs too. # Builds Linux (an older Ubuntu, so the binary runs on any recent distribution and on NixOS through nix-ld) and # Windows on GitHub, macOS on the Mac mini's runner (MAC_RUNNER=macos-latest sends it to GitHub), then # publishes vX.Y.Z on the release line in .github/release-line.txt (docs/versioning.md; without it, the dated -# vYYYY.MM.DD[.N] from before 0.2) with notes from the merged pull requests, as a beta (a pre-release) that promote.yml makes -# stable in its daily promotion. macOS: with the repository variable MACOS_SIGN_IDENTITY set, the programs are signed with +# vYYYY.MM.DD[.N] from before 0.2) with notes from the merged pull requests, as the release and GitHub's latest: one +# channel, which launchers, `horizon-server update` and install.sh follow at once. So it is published only after the +# checks that used to gate a promotion pass in this run: the Mac mini's smoke test drew a world, and no release-blocker +# is open (tools/release_train.py gate); otherwise nothing is published. macOS: with the repository variable +# MACOS_SIGN_IDENTITY set, the programs are signed with # Developer ID and the hardened runtime and the zip is notarized, from the runner's signing keychain # (packaging/macos/README.md); unset (forks), ad hoc. # gh workflow run release --ref # dry run: builds and notes, publishes nothing @@ -32,6 +35,8 @@ on: default: false permissions: contents: read + # The open release-blocker issues (decide). + issues: read concurrency: group: game-release cancel-in-progress: false @@ -203,7 +208,7 @@ jobs: or not report.get("meshed_sections") or not report.get("player"): sys.exit("the smoke run did not draw a world") EOF - # Published with the release: a beta becomes stable only with it (tools/release_channels.py). + # Published with the release; the publish job checks it again before it publishes anything. cp "$home/smoke.json" "$RUNNER_TEMP/smoke-test.json" - uses: actions/upload-artifact@v4 if: runner.environment == 'self-hosted' @@ -319,6 +324,7 @@ jobs: timeout-minutes: 15 permissions: contents: write + issues: read steps: - uses: actions/checkout@v4 with: @@ -341,6 +347,17 @@ jobs: run: | key=(); [[ -n "$EPHEMERAL" ]] && key=(--key "$(cat dist/ephemeral.pub)") cargo run --locked --quiet -p horizon-release-sign -- verify --tag "$TAG" --publishing "${key[@]}" dist + - name: Ready to publish (the smoke test passed, no release-blocker is open) + # Right before publishing: an issue labelled while the builds ran still holds this release. A dry run only + # reports what a real run would do. + env: + GH_TOKEN: ${{ github.token }} + DRY_RUN: ${{ needs.decide.outputs.dry_run }} + run: | + if ! python3 tools/release_train.py gate --kind game --smoke dist/smoke-test.json --blockers; then + [[ "$DRY_RUN" == true ]] || { echo "::error::Nothing published"; exit 1; } + echo "::warning::A real run would publish nothing" + fi - name: Publish ${{ needs.decide.outputs.tag }} if: needs.decide.outputs.dry_run != 'true' env: @@ -348,17 +365,15 @@ jobs: TAG: ${{ needs.decide.outputs.tag }} run: | signature=(); [[ -f dist/SHA256SUMS.sig ]] && signature=(dist/SHA256SUMS.sig) - smoke=(); [[ -f dist/smoke-test.json ]] && smoke=(dist/smoke-test.json) - # A beta (pre-release), the Alpha channel's: promote.yml makes it stable and latest in its daily promotion - # (docs/release-flow.md). + # The release and the latest at once: there is one channel (docs/release-flow.md). gh release create "$TAG" --target "${{ needs.decide.outputs.head }}" --title "$(cat notes/title.txt)" \ - --notes-file notes/body.md --prerelease --latest=false dist/horizon-linux-x86_64.tar.gz \ + --notes-file notes/body.md --latest dist/horizon-linux-x86_64.tar.gz \ dist/horizon-windows-x64.zip dist/horizon-macos-arm64.zip dist/horizon-server-linux-x86_64.tar.gz \ - dist/SHA256SUMS "${signature[@]}" "${smoke[@]}" + dist/SHA256SUMS "${signature[@]}" dist/smoke-test.json - name: Dry run, the release that would be published if: needs.decide.outputs.dry_run == 'true' run: | - echo "Would publish ${{ needs.decide.outputs.tag }} at ${{ needs.decide.outputs.head }}: $(cat notes/title.txt)" + echo "Would publish ${{ needs.decide.outputs.tag }} at ${{ needs.decide.outputs.head }} as the release and latest: $(cat notes/title.txt)" ls -l dist - uses: actions/upload-artifact@v4 with: diff --git a/.github/workflows/run-parity.yml b/.github/workflows/run-parity.yml index fd3cce6f8..a2b8e3291 100644 --- a/.github/workflows/run-parity.yml +++ b/.github/workflows/run-parity.yml @@ -11,6 +11,10 @@ permissions: concurrency: group: run-parity-${{ github.event.pull_request.number }} cancel-in-progress: true +env: + # Test runs never reach the telemetry server: no live-count ping, no uploads (docs/telemetry.md). + HORIZON_TELEMETRY_URL: "off" + jobs: parity: if: github.event.label.name == 'run-parity' diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 000000000..9534fba83 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,175 @@ +# Horizon: a map for agents + +Minecraft: Java Edition 26.3 rewritten in Rust (wgpu). Vanilla is the specification wherever it has the +feature. Read [CONTRIBUTING.md](CONTRIBUTING.md) once; this page tells you where things are. +Feature → files → harness for the most-changed areas: [docs/architecture.md](docs/architecture.md). + +## Rules that bite + +- **Never commit Mojang's files**: game jars, assets, decompiled source, prepared resources (`.local/`). + `tools/check_public_tree.py` rejects them; `git config core.hooksPath .githooks` runs it on commit. +- **Keep your runs away from real player data.** Any game or launcher you start gets fresh `mktemp -d` + folders in `HORIZON_HOME` (the game's data), `HORIZON_LAUNCHER_HOME`, `XDG_DATA_HOME` and + `XDG_CONFIG_HOME`, plus `HORIZON_LAUNCHER_NO_SELF_UPDATE=1` and `HORIZON_NO_AUDIO=1`. Never write to + `~/.local/share/{applications,horizon,horizon-launcher}` or `~/.local/bin`. +- **Mark what an agent posts.** A PR body starts with + `> 🤖 Opened by Ludovic's AI agent (Claude), not by Ludovic himself.` (issues: "Filed by", reviews: + "Review by"); every comment starts with `🤖 Agent:`. Never write as Ludovic. +- **Attribution.** Commits end with `Co-Authored-By: Claude `; PR bodies end + with `🤖 Generated with [Claude Code](https://claude.com/claude-code)`. +- Everything players run is Rust. Python/Java only for dev tools and harness drivers in `tools/`. +- Horizon-only features follow [docs/design-system.md](docs/design-system.md) and are off by default where + they would change the vanilla look. +- Small PRs (< ~500 lines). Labels: `feature` (players get something new), `skip-release` (they see no + change), none for a fix. Agents never add `release-now`: the maintainer decides it. Every merge to main ships + ([docs/release-flow.md](docs/release-flow.md)). +- Contributors first: `gh pr list --state open --search ` before you start; never duplicate theirs. + +## Crates + +Game workspace (root `Cargo.toml`); `launcher/` and `crates/horizon-telemetry-server` are separate workspaces. + +| Crate | Owns | +|---|---| +| `horizon-client` | The game: a lib (`src/lib.rs`, ~190 flat modules) and the bin (`src/main.rs` → `game.rs` + `game/`), plus `horizon-ctl` (`src/bin/horizon-ctl/`). Also the dedicated server (`--dedicated`) | +| `horizon-world` | Vanilla world data with no gameplay loop: NBT, regions, chunks, `datafix/`, `worldgen/`, `level/` (server-side block behaviour, ticks, redstone), entity physics, items, effects, food, damage | +| `horizon-core` | Simulation primitives: Java `Random`s, `jmath` (HotSpot-exact `Math`), positions, noise, density, paletted storage, `version.rs` (the pinned version) | +| `horizon-protocol` | Network protocol 777: codecs, framing, encryption, `packets/{handshake,status,login,configuration,play}.rs`, `entity_data.rs` | +| `horizon-assets` | Resource decoding: block-state and item models, baking, atlases | +| `horizon-prepare` | Builds `.local/horizon-client/26.3` from the player's own Minecraft install (runs the Java exporters) | +| `horizon-server` | `horizon-server`: `server.toml`, CLI, supervisor of the headless game ([docs/hosting.md](docs/hosting.md)) | +| `horizon-server-files` | `server.properties`, eula, ops/whitelist/bans, usercache | +| `horizon-friends`, `horizon-relay` | Play with Friends: invite codes, encrypted tunnel, the relay ([docs/play-with-friends.md](docs/play-with-friends.md)) | +| `horizon-shaderpack` | OptiFine/Iris packs: preprocessor, GLSL → WGSL ([docs/shader-packs.md](docs/shader-packs.md)) | +| `horizon-mods`, `horizon-mod-sdk`, `cargo-horizon-mod` | Sandboxed WebAssembly mods: runtime, SDK + WIT, `cargo horizon-mod` ([docs/mods.md](docs/mods.md)) | +| `horizon-port-pack` | Porting Java modpacks ([docs/modpacks.md](docs/modpacks.md)) | +| `horizon-theme` | Design tokens and fonts for the launcher, the game's own menus and the website | +| `horizon-telemetry`, `horizon-telemetry-server`, `horizon-bench` | Opt-in data collection, its ingest server, the benchmark report format | +| `horizon-dualsense`, `horizon-threads`, `horizon-release-sign`, `horizon-bots`, `voxel-kernels`, `xtask` | DualSense output, thread priorities, signed release checksums, load-test bots, occupancy kernels, repo tasks | +| `launcher/` | GPUI launcher: `main.rs` (UI), `backend.rs` (installs, updates), `cli.rs`, `mcp.rs`, `*_page.rs` | + +Other top-level folders: `tools/` (harnesses and dev scripts), `tests/` (Python unit tests: `python3 -m +unittest discover -s tests`), `mods/horizon/src/test/java/dev/horizonlab/parity/` (Java oracles), +`website/` (playhorizon.dev; its paths are relative to `website/`), `docs/`, `.github/workflows/`. + +## Build and test fast + +```sh +python3 tools/pr_ready.py # the self-check: fmt, clippy -D warnings, touched crates' tests, harnesses; paste its block in the PR +python3 tools/pr_ready.py --quick # same without harnesses +cargo test -p horizon-client --lib --bins --tests # skips the 104 examples (pr_ready does this); `--doc` separately +cargo build --profile fast -p horizon-client # optimized, quick to link: use it to play or run lan_e2e +python3 tools/parity.py --changed origin/main # the harnesses your branch can affect (CI's parity job) +python3 tools/parity.py --changed-files paths.txt --list # which harnesses cover these files, without running them +python3 tools/parity.py mob_ai sculk # named harnesses +python3 tools/lan_e2e.py --check chest # two real games over LAN (host in-frame); --server-thread for the host on its server thread +python3 tools/agent_control_e2e.py # horizon-ctl / MCP end to end +``` + +- Harnesses and the game need the vanilla data in `.local/` (`minecraft/`, `horizon-client/26.3`, `datagen/`, + `tools/`): see [docs/parity-workflow.md](docs/parity-workflow.md). Without it, pr_ready lists the + harnesses for CI. +- A harness = `tools/test__parity.py` (324 of them) + a Java oracle (`mods/horizon/src/test/java/dev/horizonlab/parity/Vanilla*Oracle.java`) + + a Rust probe: `crates//examples/_{probe,fixture}.rs` (horizon-world 175, horizon-client 104), + or the game binary with a fixture env var (`game/dispense_fixture.rs`, `game/sculk_fixture.rs`, + `game/command_harness.rs`, `game/net_harness.rs`). Copy a nearby harness for a new one. +- Probes build into `.local/parity-target/`; harnesses find binaries via `lab.cargo_target()`, never `target/`. +- What a change reruns (of 329 harnesses, measured 2026-10-23): a file of the game binary (`game.rs`, `game/`) + ~25, a file of the client lib ~103, of `horizon-world` ~103–109, of `horizon-core` ~119. Plan for it. +- Rust integration tests: `crates/horizon-client/tests/` (`lan_bot.rs`, `generation_saves.rs`, `streaming_meshes.rs`). +- **macOS:** `cargo build/test --workspace` may fail to link the two wasm guest cdylibs (undefined + `horizon:mods/events` symbols) until #1446 lands: add `--exclude coords-hud --exclude horizon-mods-test-guest`. + Their real check is `cargo test -p horizon-mods` (builds them for `wasm32-unknown-unknown`). +- Linux needs `libasound2-dev libudev-dev`; `--no-default-features` drops audio and controllers (the server build). +- Run and drive the game (starts the `horizon-client` beside `horizon-ctl`; other arguments go to the game): + `target/fast/horizon-ctl --socket $PWD/ctl.sock launch --world W --creative --offscreen --wait --resources $PWD/.local/horizon-client/26.3`, + then `horizon-ctl --socket … state|keys|turn|command|screenshot|quit` + ([docs/horizon-ctl-commands.md](docs/horizon-ctl-commands.md)). + +## Vanilla reference + +- Decompiled sources: `.local/minecraft/26.3/sources/{client,server}/` (`python3 tools/lab.py decompile`). +- Bytecode queries (callers through lambdas, every overload): + `python3 tools/rea_vanilla.py method net.minecraft.world.level.block.DispenserBlock dispenseFrom` + ([docs/decompilation-status.md](docs/decompilation-status.md)). +- A harness runs the oracle against the real 26.3 jars and the Rust probe on the same inputs, then compares + their JSON. Oracle runs are cached by `tools/parity_shim.py`; `--fresh` reruns them. +- Mirror vanilla's `Math` calls with `horizon_core::jmath`, and vanilla's RNG with `horizon_core::random`: + random draws must happen in vanilla's order. + +## horizon-client: where things live + +`L:` = lib (`crates/horizon-client/src/`), `G:` = bin (`crates/horizon-client/src/game/`). The lib can't see +`Game`; bin code reaches the lib as `horizon_client::`. + +| Subsystem | Files | +|---|---| +| Game loop, tick, frame | `game.rs`: `fn run`, `impl ApplicationHandler for Game` (`window_event`, `about_to_wait`), `fn tick`, `fn tick_world`, `fn render`; L: `clock.rs`, `window.rs`, `spans.rs` | +| Rendering | L: `gfx.rs` (`Renderer::new`, `Renderer::render`), `gfx/` (cull, occlusion, translucency, upload, timing, lod, weather, stars, end_sky), `*.wgsl`, `particles.rs`, `block_entity_render.rs`, `item_render.rs`, `fog.rs`, `clouds.rs`, `camera.rs`, `first_person.rs`; G: `render_tick.rs`, `item_draw.rs` | +| Chunks, streaming, light | L: `streaming.rs` (worker pool: generate, light, mesh), `world.rs`, `chunk.rs`, `chunk_map.rs`, `light.rs`, `mesher.rs` + `mesher/`, `vanillagen.rs` (binds horizon-world's generator), `lod.rs` + `lod/`, `ticket_levels.rs`; G: `world_loading.rs`, `postprocess.rs`; game.rs `fn update_world` | +| World generation | `crates/horizon-world/src/worldgen/` (`generator*.rs`, `feature_graph.rs`, `structure/`, `carver/`) | +| Block behaviour | `crates/horizon-world/src/level/` (`mod.rs`, `tick.rs`, `hooks.rs`, `redstone.rs`, `place.rs`, `interact.rs`); game.rs `fn tick_blocks`, `fn process_level_events` | +| Mobs | L: `mobs.rs` (types), `mobs/` (`ai.rs`, `goals.rs`, `brain.rs`, `*_brain.rs`, `nav.rs`, `path.rs`, `species.rs`, `spawning.rs`, `render.rs`, `anim.rs`); G: `creatures.rs` (ticking, spawning, mob events), one file per mob family (`dragon.rs`, `wither.rs`, `villagers.rs`, `piglins.rs`, `golems.rs`...), `natural_spawning.rs` | +| Other entities | L: `entities.rs`, `projectiles.rs`, `arrows.rs`; G: `boats.rs`, `minecarts.rs`, `mounts.rs`, `armor_stands.rs`, `paintings.rs`, `frames.rs`, `fireworks.rs`, `tnt.rs`, `explosion.rs` | +| Player actions | game.rs (`fn use_hand`, `fn use_item`, `fn attack`, `fn tick_mining`, `fn break_block`); G: `hand.rs`, `combat.rs`, `consume.rs`, `potions.rs`, `shield.rs`, `crossbow.rs`, `trident.rs`, `fishing.rs`; L: `motion.rs` + `motion/` (movement), `collisions.rs`, `items.rs`, `item_data.rs` | +| Inventory and containers | L: `menu.rs` (`AbstractContainerMenu.clicked`), `container_screen.rs`, `containers.rs`, `creative.rs`, `crafting.rs`, `recipe_book*.rs`, `stations.rs`, `merchant.rs`; game.rs `fn menu_ops`, `fn click_inventory`; G: `stations.rs`, `trading.rs`, `recipe_book.rs`, `machines.rs` | +| Commands | parse: L: `command/` (`args.rs`, `selector.rs`, `tree_*.rs`, `vanilla.rs`); run: G: `commands.rs` (dispatch) + `commands/*.rs` (`admin`, `execute`, `items`, `players`, `world_cmds`...); L: `scoreboard_cmd.rs`, `data_cmd.rs`, `nbt_path.rs`; G: `functions.rs`, `command_blocks.rs` | +| UI screens | `Screen` enum in game.rs; L: `title.rs` + `title/`, `options_ui.rs`, `multiplayer.rs`, `pack_screen.rs`, `graphics_ui.rs`, `screen_draw.rs`, `ui.rs` (widgets), `hud.rs`, `hud_layout.rs`, `hud_overlays.rs`, `chat.rs`, `tab_list.rs`; G: `startup_menu.rs`, `screens.rs` (pause, death), `options.rs`, `lan_screen.rs`, `chat.rs`, `sign_edit.rs`, `books.rs` | +| Multiplayer client | L: `net.rs` (network thread); G: `remote.rs` (`fn handle_packet`, `fn tick_remote`), `remote_*.rs` (mob data, objects, projectiles, vehicles, stations) | +| LAN host / server side | L: `lan/` (`conn.rs` handshake + login threads, `hub.rs` + `hub/` play state, `chunks.rs`, `entity.rs`, `tracking.rs`, `guest.rs`, `playerdata.rs`); G: `lan.rs` (`LanHost`), `lan_actions.rs` (`fn as_guest`, `fn tick_guests`), `lan_*.rs` per feature, `lan_entities.rs` (tracked entities) | +| Integrated server | G: `integrated.rs` (the server thread), `levels.rs` (one level per dimension, `fn tick_server`), `server_travel.rs` | +| Dedicated server | G: `dedicated.rs`, `dedicated/status.rs`; crates `horizon-server-files`, `horizon-server` | +| Save and load | L: `save.rs` (level.dat, regions, playerdata), `entity_nbt.rs`, `block_entity_nbt.rs`, `options_file.rs`; G: `saving.rs`, `persist.rs` (entities); `crates/horizon-world/src/{region.rs,nbt.rs,datafix/}` | +| Input | game.rs `fn window_event`, `fn key_pressed`, `fn play_mouse`; L: `keybinds.rs`, `keymapping.rs`, `key_names.rs`, `mouse.rs`, `input.rs`, `interaction_input.rs`, `gamepad.rs`, `osk.rs`, `clipboard.rs`; G: `pad.rs`, `pad_menu.rs` | +| Audio | L: `audio.rs` (mixer), `sound_engine.rs`, `sound_events.rs`, `music.rs`, `ambience.rs`; G: `music.rs`, `subtitle_hud.rs` | +| Resource packs | L: `packs.rs` + `packs/`, `pack_screen.rs`, `atlas_sources.rs`, `sprites.rs`, `mipmap.rs`, `model_library.rs`, `font.rs`, `lang.rs`; crate `horizon-assets`; G: `packs.rs` | +| Shader packs | L: `shader_pack.rs` (Horizon WGSL packs), `java_pack.rs` + crate `horizon-shaderpack` (Iris/OptiFine), `gfx/pack_stages.rs`, `gfx/java_stages.rs`; G: `shader_packs.rs` | +| Agent control | L: `control.rs` (socket), `bin/horizon-ctl/`; G: `control.rs`, `agent.rs`, `events.rs`, `ui_control.rs` ([docs/agent-control.md](docs/agent-control.md)) | +| Mods | crate `horizon-mods`; G: `mods.rs`; L: `mod_content.rs`, `mod_list.rs` | +| Horizon extras, settings | L: `extras.rs`, `graphics.rs`, `settings.rs`, `minimap.rs`; G: `extras.rs`, `tweaks.rs`, `options.rs` | + +## How `Game` is organised + +- `struct Game` (game.rs, ~290 fields) holds everything. Its methods are spread over ~180 files: game.rs keeps + the core (tick, render, input, inventory, world open/close) and each `game/.rs` adds an + `impl Game<'_>` block for one feature, with its own state types. Fields are private to the bin. +- Find a feature's code: `grep -rn "fn tick_\|fn _" crates/horizon-client/src/game*`; + the file is usually `game/s.rs`. Who calls it: grep the name in game.rs's `fn tick` / `fn tick_world`. +- Fields that say which mode runs: `remote` (this window is a client of a server: multiplayer, LAN guest, or + single player on its server thread), `lan` (`LanHost`: this world is open to the network), `integrated` + (the window's own server thread), `serving` (this `Game` *is* that server thread), `options.dedicated`. + `fn tick` returns `tick_remote()` when `remote` is set; nothing else of the local simulation runs. +- A server's players run through the same gameplay code as the local player: `as_guest` swaps the guest's + state (position, inventory, mode, mining, item use) into `Game` for one call (`game/lan_actions.rs`), and + `levels.rs` swaps whole dimensions in the same way. Changes reach clients through the block log, level + events and the entity tracker (`lan/tracking.rs`, `game/lan_entities.rs`). +- Shared read-only data: `Resources` (`res`: blocks, items, recipes, mob types, biomes) and `PackResources` + (`pack`), both in game.rs. + +## The two single-player paths + +1. **In-frame (default since #1428):** the window's `Game` ticks the world itself, one level that follows + the player (`fn enter_dimension`). This is what Stable players run and what harnesses test. +2. **Server thread (`--server-thread` or `HORIZON_SERVER_THREAD=1`):** `game/integrated.rs` runs a second + `Game` (`serving`) on a "Server thread" with one level per dimension; the window joins it as a client + through memory (`remote`), exactly as a LAN guest or a dedicated server's player does. Not at parity yet: + open `[server-thread]` issues list the gaps. + +LAN guests and dedicated servers always use the server code, so a fix there serves both. Test both paths +when you touch player-facing gameplay: + +```sh +cargo run --profile fast -p horizon-client -- --resources .local/horizon-client/26.3 --world T # in-frame +cargo run --profile fast -p horizon-client -- --resources .local/horizon-client/26.3 --world T --server-thread # server thread +python3 tools/lan_e2e.py --check # host in-frame, guest is a server client +python3 tools/lan_e2e.py --server-thread --check # host on its server thread (portals, levels, distance, lava need it) +python3 tools/parity.py dedicated_server server_entities server_player_damage +``` + +## Docs worth knowing + +[docs/parity-workflow.md](docs/parity-workflow.md) (runner, gate, shards, scopes) · +[docs/native-client.md](docs/native-client.md) (options, controls, horizon-ctl) · +[docs/server-levels.md](docs/server-levels.md) (levels per dimension) · +[docs/rust-parity.md](docs/rust-parity.md) (what is ported) · [docs/known-issues.md](docs/known-issues.md) · +[docs/release-flow.md](docs/release-flow.md) · [docs/README.md](docs/README.md) (index). diff --git a/CLAUDE.md b/CLAUDE.md new file mode 120000 index 000000000..47dc3e3d8 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +AGENTS.md \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index 16ae8d6eb..2f832e248 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1395,6 +1395,7 @@ dependencies = [ name = "horizon-bench" version = "0.1.0" dependencies = [ + "horizon-telemetry", "serde", "serde_json", ] diff --git a/README.md b/README.md index 72b6a3496..4abb52b86 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ The [documentation](https://playhorizon.dev/docs/) covers each of these. - **The game:** singleplayer with vanilla's world generation, mobs, villagers, raids, redstone, every command, the HUD and the recipe book, on saves in vanilla's format. Worlds from 1.8 to 26.2 are upgraded as vanilla does. [Status table](#project-status). - **Horizon's own extras:** new menus (vanilla's are one setting away), graphics presets, distant terrain up to 1024 chunks, controller support, optional zoom, minimap and more, all off by default where they would change the vanilla look. See [Settings](https://playhorizon.dev/docs/settings). - **Resource packs, shader packs and data packs:** resource packs work, Java shader packs run their full-screen effects (experimental), and data packs load functions, predicates and item modifiers. -- **Playing with others:** invite friends from the pause menu with a code, Open to LAN, and joining offline-mode servers. Horizon cannot sign in to a Microsoft account yet, so it cannot join servers that check accounts. See [Multiplayer](https://playhorizon.dev/docs/multiplayer). +- **Playing with others:** invite friends from the pause menu's Friends button with a code, Open to LAN, and joining offline-mode servers. Horizon cannot sign in to a Microsoft account yet, so it cannot join servers that check accounts. See [Multiplayer](https://playhorizon.dev/docs/multiplayer). - **Mods:** Horizon has its own mod system (Rust compiled to WebAssembly). Java mod jars do not run. See [Mods and data packs](https://playhorizon.dev/docs/mods). Screenshots, captured in the Rust client itself with vanilla assets and no mods or shaders: @@ -56,8 +56,8 @@ Screenshots, captured in the Rust client itself with vanilla assets and no mods Sunset over a savanna river valley and a plains village - Horizon's title screen over a veiled snowy landscape - The Video settings in their Simple view: a preset, render distance, field of view, framerate, VSync and GUI scale, each with what it costs + Survival at dusk: a zombie walks up, with the hotbar, health, hunger and experience + Vanilla's Video Settings screen with Horizon's own buttons at the top: Horizon Graphics, Advanced Graphics and Shader Packs A plains village among savanna hills, with farms, villagers and an iron golem diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 368813ecf..88d3197af 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -36,3 +36,15 @@ SOFTWARE. developers, with one upstream fix applied ([gfx-rs/wgpu#10124](https://github.com/gfx-rs/wgpu/pull/10124)). It is licensed under MIT or Apache-2.0; both licenses are in that folder (`LICENSE.MIT`, `LICENSE.APACHE`). + +## Pixelify Sans + +`crates/horizon-theme/fonts/PixelifySans-*.ttf` is [Pixelify Sans](https://github.com/eifetx/Pixelify-Sans) +by The Pixelify Sans Project Authors, licensed under the SIL Open Font License 1.1 +(`crates/horizon-theme/fonts/OFL-PixelifySans.txt`). + +## Pixelarticons + +`crates/horizon-theme/icons/pixel/*.svg` are icons from +[Pixelarticons](https://github.com/halfmage/pixelarticons) by Gerrit Halfmann, under the MIT +license (`crates/horizon-theme/icons/pixel/LICENSE-pixelarticons.txt`). diff --git a/crates/horizon-bench/Cargo.toml b/crates/horizon-bench/Cargo.toml index b945577b0..5a1884990 100644 --- a/crates/horizon-bench/Cargo.toml +++ b/crates/horizon-bench/Cargo.toml @@ -8,3 +8,5 @@ description = "The benchmark report format (docs/benchmark-report.md), shared by [dependencies] serde = { version = "1", features = ["derive"] } serde_json = "1" +# The hardware probes shared with telemetry (cores, clocks, drive, VRAM, power, form). +horizon-telemetry = { path = "../horizon-telemetry", default-features = false } diff --git a/crates/horizon-bench/src/hardware.rs b/crates/horizon-bench/src/hardware.rs index 4e41a0405..17e460bed 100644 --- a/crates/horizon-bench/src/hardware.rs +++ b/crates/horizon-bench/src/hardware.rs @@ -16,8 +16,22 @@ pub struct Hardware { pub cpu: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub cpu_threads: Option, + /// Physical cores. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cpu_cores: Option, + /// Base and top boost clock, where the OS gives them. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cpu_base_mhz: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cpu_boost_mhz: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub ram_mb: Option, + /// The drive under the game folder: `nvme`, `ssd` or `hdd`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub storage: Option, + /// `laptop` or `desktop`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub form: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub gpu: Option, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -33,6 +47,9 @@ pub struct Gpu { pub backend: String, /// `integrated`, `discrete`, `virtual`, `cpu`, `other`. pub kind: String, + /// Its own memory in MiB (rounded to 256), for a discrete GPU whose driver says. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub vram_mb: Option, } #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] @@ -47,17 +64,50 @@ pub struct Display { impl Hardware { pub fn detect() -> Hardware { + let probes = probes(); Hardware { os: std::env::consts::OS.to_owned(), os_version: os_version(), arch: std::env::consts::ARCH.to_owned(), cpu: cpu(), cpu_threads: std::thread::available_parallelism().ok().map(|n| n.get()), + cpu_cores: probes.cores, + cpu_base_mhz: probes.base, + cpu_boost_mhz: probes.boost, ram_mb: ram_bytes().map(|b| b >> 20), + storage: None, + form: probes.form, gpu: None, display: None, } } + + /// [`Hardware::detect`] with the kind of drive `game_dir` is on. + pub fn detect_in(game_dir: &std::path::Path) -> Hardware { + Hardware { + storage: horizon_telemetry::system::storage(game_dir).map(str::to_owned), + ..Hardware::detect() + } + } +} + +/// What the telemetry probes read (`horizon_telemetry::system`). +struct Probes { + cores: Option, + base: Option, + boost: Option, + form: Option, +} + +fn probes() -> Probes { + let s = horizon_telemetry::payload::System::detect(); + let some = |n: u32| (n > 0).then_some(n); + Probes { + cores: (s.cores > 0).then_some(s.cores), + base: some(s.cpu_base_mhz), + boost: some(s.cpu_boost_mhz), + form: (!s.form.is_empty()).then_some(s.form), + } } /// The one-minute load average: above about the number of threads the machine was busy. @@ -82,25 +132,7 @@ pub fn load_average() -> Option { /// `ac` or `battery`; `None` where it can't be read (and on machines without a battery on Linux). pub fn power_source() -> Option<&'static str> { - if cfg!(target_os = "macos") { - let batt = output("pmset", &["-g", "batt"])?; - return Some(if batt.contains("'Battery Power'") { - "battery" - } else { - "ac" - }); - } - let mut on_battery = None; - for entry in std::fs::read_dir("/sys/class/power_supply").ok()?.flatten() { - let read = - |name: &str| std::fs::read_to_string(entry.path().join(name)).unwrap_or_default(); - match read("type").trim() { - "Mains" if read("online").trim() == "1" => return Some("ac"), - "Battery" => on_battery = Some("battery"), - _ => {} - } - } - on_battery + horizon_telemetry::system::power() } /// Resident memory of a process, in bytes (macOS, Linux). diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index 33e383907..529262e39 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -30,7 +30,9 @@ serde = { version = "1", features = ["derive"] } serde_json = { version = "1.0.151", features = ["raw_value"] } # Shader packs: pack.toml, and WGSL checked before it reaches wgpu. toml = "1.1" -naga = { version = "30.0.1", features = ["wgsl-in"] } +# hlsl-out: the gfx.rs tests translate every shader as wgpu's DirectX 12 backend does. A normal feature, +# not a dev-dependency's, so builds, tests and examples share one build of naga, wgpu and this crate. +naga = { version = "30.0.1", features = ["wgsl-in", "hlsl-out"] } # Java (OptiFine/Iris) shader packs, translated to WGSL. horizon-shaderpack = { path = "../horizon-shaderpack" } # Sound (ALSA on Linux); the `audio` feature. diff --git a/crates/horizon-client/examples/firework_tooltip_fixture.rs b/crates/horizon-client/examples/firework_tooltip_fixture.rs index 196fa9955..7f10278b7 100644 --- a/crates/horizon-client/examples/firework_tooltip_fixture.rs +++ b/crates/horizon-client/examples/firework_tooltip_fixture.rs @@ -1,7 +1,7 @@ //! Firework tooltip companion for tools/test_firework_tooltip_parity.py: the //! lines `item_tooltip::firework_lines` gives each stack (SNBT, one per line; //! the `#resources` line names the prepared resources for en_us). -use horizon_client::{item_data::parse_stack, item_tooltip::firework_lines, lang::Language}; +use horizon_client::{enchant::Enchantments, item_data::parse_stack, item_tooltip::firework_lines}; use std::{error::Error, fmt::Write, path::PathBuf}; fn main() -> Result<(), Box> { @@ -12,8 +12,9 @@ fn main() -> Result<(), Box> { .find_map(|l| l.strip_prefix("#resources ")) .map(PathBuf::from) .ok_or("no #resources line")?; - let language = Language::load(&[&root], "en_us"); - let translate = |key: &str| language.get(key).map(str::to_owned); + // Use the inventory's filtered translations so missing tooltip keys are caught. + let enchantments = Enchantments::load(&root); + let translate = |key: &str| enchantments.translate(key).map(str::to_owned); let mut output = String::new(); for line in input.lines().filter(|l| !l.starts_with('#')) { let stack = parse_stack(line)?.ok_or("empty stack")?; diff --git a/crates/horizon-client/examples/held_drop_fixture.rs b/crates/horizon-client/examples/held_drop_fixture.rs index 87ca9870c..a0c5d92ba 100644 --- a/crates/horizon-client/examples/held_drop_fixture.rs +++ b/crates/horizon-client/examples/held_drop_fixture.rs @@ -14,13 +14,22 @@ fn main() { for count in [0, 1, 4, 64] { let mut slot = Some(ItemStack::new("minecraft:stone", count)); let mut dropped = 0; + let mut swings = 0; + let mut packets = 0; for _ in 0..2 { if let Some(stack) = take_held_drop(&mut slot, all, mode == GameMode::Spectator) { dropped += stack.count; + swings += 1; } - println!("{} {}", slot.as_ref().map_or(0, |s| s.count), dropped); + if mode != GameMode::Spectator { + packets += 1; + } + println!( + "{} {dropped} {swings} {packets}", + slot.as_ref().map_or(0, |s| s.count), + ); } } } diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 66d06aa84..a3abb54d9 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -1133,7 +1133,7 @@ fn main() -> horizon_client::Result<()> { } #[allow(unused_mut)] // filled only with the rng-trace feature let mut traces: Vec = Vec::new(); - let mut pushes = Vec::new(); + let mut pushes = horizon_client::mobs::PendingPushes::default(); let mut born = Vec::new(); for i in 0..mobs.len() { if mobs[i].removed { diff --git a/crates/horizon-client/examples/natural_spawn_fixture.rs b/crates/horizon-client/examples/natural_spawn_fixture.rs index 528f8195d..e4c9b1ce6 100644 --- a/crates/horizon-client/examples/natural_spawn_fixture.rs +++ b/crates/horizon-client/examples/natural_spawn_fixture.rs @@ -111,6 +111,8 @@ struct World<'a> { slime: f32, starts: Vec, players: Vec<([f64; 3], String)>, + /// Where the non-spectators among them are. + nearest: Vec<[f64; 3]>, respawn: Option<[i32; 3]>, unloaded: HashSet<(i32, i32)>, spawn_mobs: bool, @@ -302,19 +304,8 @@ impl NaturalLevel for World<'_> { fn structure_spawns(&self) -> &StructureSpawns { self.s.structures } - fn nearest_player_distance_sqr(&self, x: f64, y: f64, z: f64) -> Option { - let mut best: Option = None; - for (p, mode) in &self.players { - if mode == "spectator" { - continue; - } - let d = [p[0] - x, p[1] - y, p[2] - z]; - let d = d[0] * d[0] + d[1] * d[1] + d[2] * d[2]; - if best.is_none_or(|b| d < b) { - best = Some(d); - } - } - best + fn nearest_player_positions(&self) -> &[[f64; 3]] { + &self.nearest } fn respawn(&self) -> Option<[i32; 3]> { self.respawn @@ -730,6 +721,11 @@ fn main() -> horizon_client::Result<()> { dimension_id: dimension_id.clone(), slime: get("slime", "0.0").parse()?, starts, + nearest: players + .iter() + .filter(|(_, mode)| mode != "spectator") + .map(|(p, _)| *p) + .collect(), players, respawn, unloaded, diff --git a/crates/horizon-client/examples/random_tick_sections_probe.rs b/crates/horizon-client/examples/random_tick_sections_probe.rs new file mode 100644 index 000000000..91c861f45 --- /dev/null +++ b/crates/horizon-client/examples/random_tick_sections_probe.rs @@ -0,0 +1,132 @@ +//! Random-tick sections companion for tools/test_random_tick_sections_parity.py: +//! the game's `RandomTickSections` choosing the sections of a chunk that +//! `Behaviours::tick_chunk_random` ticks, after the case's edits (see +//! VanillaRandomTickSectionsOracle for the format; the `#resources` line names +//! the prepared resources). The level the ticks run against reads as air +//! everywhere, so nothing ticks for real: its reads are the drawn positions. +use horizon_client::{ + blocks::BlockFacts, + chunk::{Chunk, MIN_Y, Section}, + random_tick_sections::RandomTickSections, +}; +use horizon_core::{ + position::{BlockPos, ChunkPos}, + random::LegacyRandom, +}; +use horizon_world::{ + fluid::FluidKind, + level::{GameRules, LevelAccess, LevelEvent, Ticks, data}, + registry::BlockStateId, +}; +use std::{cell::RefCell, error::Error, fmt::Write, path::PathBuf, sync::Arc}; + +struct Air { + reads: RefCell>, + random: LegacyRandom, + speed: i32, +} +impl LevelAccess for Air { + fn block_state(&self, pos: BlockPos) -> BlockStateId { + self.reads.borrow_mut().push(pos); + BlockStateId(0) + } + fn set_raw(&mut self, _: BlockPos, _: BlockStateId) -> Option { + None + } + fn is_loaded(&self, _: BlockPos) -> bool { + true + } + fn random(&mut self) -> &mut LegacyRandom { + &mut self.random + } + fn game_time(&self) -> i64 { + 0 + } + fn game_rules(&self) -> GameRules { + GameRules { + random_tick_speed: self.speed, + ..Default::default() + } + } + fn emit(&mut self, _: LevelEvent) {} +} + +fn main() -> Result<(), Box> { + let args: Vec = std::env::args().collect(); + let input = std::fs::read_to_string(&args[1])?; + let root = input + .lines() + .find_map(|l| l.strip_prefix("#resources ")) + .map(PathBuf::from) + .ok_or("no #resources line")?; + let registry = data::load_registry(&root)?; + let (facts, behaviours) = BlockFacts::load_pair(&root, ®istry)?; + let mut output = String::new(); + for line in input.lines().filter(|l| !l.starts_with('#')) { + let mut words = line.split(' '); + let mut ticks = Ticks::new(0); + ticks.random_tick_value = words.next().ok_or("no randValue")?.parse()?; + let mut level = Air { + reads: RefCell::default(), + random: LegacyRandom::new(0), + speed: words.next().ok_or("no speed")?.parse()?, + }; + let mut chunk = Arc::new(Chunk::empty(0, 0)); + let mut cache = RandomTickSections::default(); + for word in words { + let op: Vec<&str> = word.split(':').collect(); + let int = |i: usize| -> Result> { Ok(op[i].parse()?) }; + match op[0] { + "s" => { + let (section, index) = (int(1)?, int(2)?); + Arc::make_mut(&mut chunk).set( + index & 15, + MIN_Y + section * 16 + (index >> 8), + index >> 4 & 15, + int(3)? as u32, + ); + } + "f" => { + let (a, b, m) = (int(2)? as u32, int(3)? as u32, int(4)? as usize); + let values = std::array::from_fn(|i| if i % m == m - 1 { b } else { a }); + Arc::make_mut(&mut Arc::make_mut(&mut chunk).sections[int(1)? as usize]) + .blocks = Section::from_blocks(&values); + } + "t" => { + output.push('|'); + level.reads.borrow_mut().clear(); + behaviours.tick_chunk_random( + &mut level, + &mut ticks, + ChunkPos::new(0, 0), + |_, from| cache.get((0, 0), &chunk, &facts).from(from), + ); + for pos in level.reads.borrow().iter() { + let state = chunk.block(pos.x, pos.y, pos.z); + let fluid = matches!( + behaviours.fluid(state).kind(), + FluidKind::Lava | FluidKind::FlowingLava + ); + write!( + output, + " {},{},{},{}{}", + pos.x, + pos.y, + pos.z, + if behaviours.is_randomly_ticking(state) { + 'B' + } else { + '-' + }, + if fluid { 'F' } else { '-' }, + )?; + } + } + other => return Err(format!("unknown op {other}").into()), + } + } + writeln!(output, " | {}", ticks.random_tick_value)?; + } + std::fs::write(&args[2], output)?; + Ok(()) +} diff --git a/crates/horizon-client/examples/streaming_bench.rs b/crates/horizon-client/examples/streaming_bench.rs index 9f8e99899..b8c56b28c 100644 --- a/crates/horizon-client/examples/streaming_bench.rs +++ b/crates/horizon-client/examples/streaming_bench.rs @@ -3,6 +3,7 @@ //! what the render thread pays for it in `Streaming::update`. //! //! streaming_bench RESOURCES [--threads N] [--radius R] [--seed S] [--fly CHUNKS_PER_S] [--seconds T] [--hz F] +//! [--dimension overworld|the_nether|the_end] [--center-x X] [--center-z Z] //! //! First the area around (0, 0) fills; then, with `--fly`, the centre moves along +x //! at that speed for T seconds while frames run at F per second. Each phase reports @@ -72,14 +73,33 @@ static ALLOCATOR: CountingAllocator = CountingAllocator; type Result = std::result::Result>; +fn cpu_seconds() -> f64 { + std::fs::read_to_string("/proc/self/stat") + .ok() + .and_then(|stat| { + let fields = stat + .rsplit_once(')')? + .1 + .split_whitespace() + .collect::>(); + Some((fields[11].parse::().ok()? + fields[12].parse::().ok()?) / 100.0) + }) + .unwrap_or(0.0) +} + #[derive(Default)] struct Phase { updates: Vec, local: (u64, u64), uploads: usize, + stage_samples: [u64; 7], + cpu_start: f64, } impl Phase { fn update(&mut self, streaming: &mut Streaming, world: &mut World) { + if self.updates.is_empty() { + self.cpu_start = cpu_seconds(); + } let before = LOCAL.with(Cell::get); let started = Instant::now(); let (uploads, _) = streaming.update(world); @@ -89,6 +109,9 @@ impl Phase { self.local.1 += after.1 - before.1; self.uploads += uploads.len(); drop(uploads); + for (sum, (_, count)) in self.stage_samples.iter_mut().zip(streaming.stages()) { + *sum += count as u64; + } } fn report(&self, name: &str, wall: Duration, streaming: &Streaming, generated: u64) { let mut sorted = self.updates.clone(); @@ -106,6 +129,16 @@ impl Phase { at(0.99), sorted.last().copied().unwrap_or(0.0), ); + println!( + "BENCH {}", + serde_json::json!({ + "phase": name, "wall_s": wall.as_secs_f64(), + "cpu_s": cpu_seconds() - self.cpu_start, + "chunks": streaming.generated_total - generated, "sections": self.uploads, + "updates": self.updates.len(), "update_ms": total, + "mean_stages": self.stage_samples.map(|n| n as f64 / self.updates.len() as f64), + }) + ); if TRACK { println!( " update allocations: {} ({:.1} MiB)", @@ -142,6 +175,22 @@ fn main() -> Result<()> { let fly = flag("--fly", 0.0); let seconds = flag("--seconds", 10.0); let hz = flag("--hz", 240.0); + let dimension = args + .iter() + .position(|a| a == "--dimension") + .and_then(|i| args.get(i + 1)) + .map(|d| { + if d.contains(':') { + d.clone() + } else { + format!("minecraft:{d}") + } + }) + .unwrap_or_else(|| "minecraft:overworld".into()); + let center = ( + flag("--center-x", 0.0) as i32, + flag("--center-z", 0.0) as i32, + ); let assets = Arc::new(Assets::load(&root)?); let render = Arc::new(assets.reload(&root)?); @@ -154,11 +203,12 @@ fn main() -> Result<()> { models::load_visibility(&root, assets.registry)?, )?); let light = Arc::new(LightTables::load(&root, assets.registry, &facts)?); - let terrain = Arc::new(VanillaTerrain::new( + let terrain = Arc::new(VanillaTerrain::for_dimension( &root.join("worldgen"), assets.registry, &biomes, seed, + &dimension, )?); let context = Arc::new(WorkerContext { assets, @@ -170,8 +220,12 @@ fn main() -> Result<()> { let mut world = World::new(facts.air, seed); let mut streaming = Streaming::new(terrain, context, threads); streaming.radius = radius; - streaming.center = (0, 0); - println!("{threads} workers, radius {radius}, seed {seed}"); + streaming.center = center; + streaming.nether_shading = dimension == "minecraft:the_nether"; + streaming.sky_light = dimension != "minecraft:the_nether"; + println!( + "{threads} workers, radius {radius}, seed {seed}, dimension {dimension}, center {center:?}" + ); let (allocations, bytes) = (ALLOCATIONS.load(Relaxed), BYTES.load(Relaxed)); // Fill: update as often as the game would uncapped, until settled. @@ -198,12 +252,12 @@ fn main() -> Result<()> { let mut behind = Vec::new(); while started.elapsed().as_secs_f64() < seconds { let next = Instant::now() + frame; - let x = (started.elapsed().as_secs_f64() * fly) as i32; - streaming.center = (x, 0); + let x = center.0 + (started.elapsed().as_secs_f64() * fly) as i32; + streaming.center = (x, center.1); phase.update(&mut streaming, &mut world); // Columns within 2 chunks of the player still missing their meshes. let near = (-2..=2) - .flat_map(|dz| (-2..=2).map(move |dx| (x + dx, dz))) + .flat_map(|dz| (-2..=2).map(move |dx| (x + dx, center.1 + dz))) .filter(|&(cx, cz)| !streaming.is_lit(cx, cz)) .count(); behind.push(near); diff --git a/crates/horizon-client/examples/weather_fixture.rs b/crates/horizon-client/examples/weather_fixture.rs index 15aab6bdb..3cf6c31be 100644 --- a/crates/horizon-client/examples/weather_fixture.rs +++ b/crates/horizon-client/examples/weather_fixture.rs @@ -11,6 +11,7 @@ fn bits(value: f32) -> String { fn main() -> Result<(), Box> { let args: Vec<_> = std::env::args().collect(); let mut output = String::new(); + let mut parameters = weather::ParameterCache::default(); for (case, line) in fs::read_to_string(&args[1])?.lines().enumerate() { let p: Vec<&str> = line.split_whitespace().collect(); let int = |i: usize| p[i].parse::().unwrap(); @@ -38,6 +39,13 @@ fn main() -> Result<(), Box> { bits(column.v_offset), column.light_coords )?; + assert_eq!( + parameters + .get(x, z) + .column(kind != 0, ticks, x, bottom, top, z, light, partial), + column, + "cached parameters differ from original random source at case {case}" + ); let max_alpha = if kind == 0 { 1.0 } else { 0.8 }; for v in weather::column_quad(&column, camera, max_alpha, radius, intensity) { write!( diff --git a/crates/horizon-client/src/attribute_updates.rs b/crates/horizon-client/src/attribute_updates.rs index b81db5835..1dcc21028 100644 --- a/crates/horizon-client/src/attribute_updates.rs +++ b/crates/horizon-client/src/attribute_updates.rs @@ -22,6 +22,11 @@ impl PlayerMotion { pub fn refresh_attributes(&mut self) -> Result<()> { live_updates::refresh(self) } + /// `Player.internalSetAbsorptionAmount`: the amount as given, unclamped + /// (the saved `AbsorptionAmount`, or what a client's server sent). + pub fn internal_set_absorption(&mut self, value: f32) -> Result<()> { + self.store_absorption(value) + } } impl HealthWorld for PlayerMotion { type Error = Box; diff --git a/crates/horizon-client/src/benchmark.rs b/crates/horizon-client/src/benchmark.rs index 483a68848..bcb94589c 100644 --- a/crates/horizon-client/src/benchmark.rs +++ b/crates/horizon-client/src/benchmark.rs @@ -140,7 +140,22 @@ fn run(control: &Control, setup: Setup) -> Result { driver: text(&renderer["driver"]), backend: text(&renderer["backend"]).to_lowercase(), kind: text(&renderer["device_type"]), + vram_mb: None, }); + if let Some(gpu) = report.hardware.gpu.as_mut() { + let vendor = horizon_telemetry::system::gpu_vendor(&gpu.name, 0); + let vendor = if gpu.vendor.is_empty() { + vendor + } else { + gpu.vendor.as_str() + } + .to_owned(); + if gpu.kind.contains("iscrete") { + gpu.vram_mb = horizon_telemetry::system::vram_mb(&vendor); + } + } + report.hardware.storage = + horizon_telemetry::system::storage(&setup.game_dir).map(str::to_owned); report.hardware.display = serde_json::from_value(title["display"].clone()).ok(); replace_world(&setup.game_dir)?; @@ -224,6 +239,10 @@ fn run(control: &Control, setup: Setup) -> Result { let status = control.status(); let renderer = &status["renderer"]; + // On Wayland the window is on a screen only once it has been shown: ask again. + if report.hardware.display.is_none() { + report.hardware.display = serde_json::from_value(status["display"].clone()).ok(); + } let c = &mut report.conditions; c.scenario = Some(setup.scenario.clone()); c.seed = Some(SEED.to_string()); diff --git a/crates/horizon-client/src/bin/horizon-ctl/commands.rs b/crates/horizon-client/src/bin/horizon-ctl/commands.rs index 230cbc880..f2db98535 100644 --- a/crates/horizon-client/src/bin/horizon-ctl/commands.rs +++ b/crates/horizon-client/src/bin/horizon-ctl/commands.rs @@ -32,16 +32,18 @@ pub enum Group { Move, Act, Screens, + Multiplayer, World, Scripting, } impl Group { - pub const ALL: [Group; 7] = [ + pub const ALL: [Group; 8] = [ Group::Session, Group::Observe, Group::Move, Group::Act, Group::Screens, + Group::Multiplayer, Group::World, Group::Scripting, ]; @@ -52,6 +54,7 @@ impl Group { Group::Move => "Move and look", Group::Act => "Act on the world", Group::Screens => "Screens, menus and chat", + Group::Multiplayer => "Multiplayer, LAN and friends", Group::World => "World and cheats", Group::Scripting => "Scripting and benchmarks", } @@ -117,6 +120,50 @@ const OVER: Param = flag( "turn with mouse motion spread over this many seconds (eased), as a player would", ); const FACE: Ty = Ty::Enum(&["down", "up", "north", "south", "west", "east"]); +const BOX: [Param; 6] = [ + p("x1", Ty::Int, "corner X"), + p("y1", Ty::Int, "corner Y"), + p("z1", Ty::Int, "corner Z"), + p("x2", Ty::Int, "opposite X"), + p("y2", Ty::Int, "opposite Y"), + p("z2", Ty::Int, "opposite Z"), +]; +const PAGES: Ty = Ty::Enum(&[ + "main", + "video", + "sound", + "controls", + "keybinds", + "controller", + "controller-binds", + "mouse", + "chat", + "accessibility", + "language", + "font", + "packs", + "mods", + "graphics", + "graphics-advanced", + "extras", + "horizon", + "shader-packs", + "agent", +]); + +/// `--confirm`, required by destructive commands: the player agreed. +const CONFIRM: Param = Param { + name: "confirm", + ty: Ty::Bool, + required: true, + flag: true, + help: "true once the player agreed: it cannot be undone", +}; + +/// MCP tools that delete or overwrite the player's things (`destructiveHint`). +pub const DESTRUCTIVE: &[&str] = &["world-delete", "fill", "setblock"]; +/// MCP tools that reach other players or the network (`openWorldHint`): only when the player asks. +pub const OPEN_WORLD: &[&str] = &["connect", "lan", "friends", "chat", "command"]; macro_rules! cmd { ($name:expr, $group:ident, $usage:expr, $summary:expr, $details:expr, [$($ex:expr),* $(,)?], $params:expr, mcp: $mcp:expr, local: $local:expr $(, wire: $wire:expr)?) => { @@ -164,7 +211,19 @@ pub const COMMANDS: &[Cmd] = &[ &[flag("lines", Ty::Int, "how many lines of latest.log (default 100)"), flag("crash", Ty::Bool, "the newest crash report instead")], mcp: true, local: true), cmd!("status", Session, "status", "game, renderer and streaming state (the scripting socket's original summary)", - "", ["horizon-ctl status"], &[], mcp: false, local: false), + "Also what F3 shows: the overlay flags, the renderer, chunk streaming and memory.", ["horizon-ctl status"], &[], mcp: true, local: false), + cmd!("worlds", Session, "worlds", "the saved worlds, newest first: folder, name, mode, last played, version", + "folder is what open, world-rename, world-backup and world-delete take.", ["horizon-ctl worlds"], &[], mcp: true, local: false), + cmd!("world-rename", Session, "world-rename FOLDER NAME", "rename a world, as Edit World does (its folder stays)", + "Needs the title screen (no world open).", ["horizon-ctl world-rename Test \"My Base\""], + &[p("folder", Ty::Str, "world folder from worlds"), p("name", Ty::Rest, "the new name")], mcp: true, local: false), + cmd!("world-backup", Session, "world-backup FOLDER", "zip a world into backups/, as Edit World's Make Backup does", + "Needs the title screen. Replies once the zip is written, with its size.", ["horizon-ctl world-backup Test"], + &[p("folder", Ty::Str, "world folder from worlds")], mcp: true, local: false), + cmd!("world-delete", Session, "world-delete FOLDER --confirm", "delete a world for good, as Select World's Delete does", + "Needs the title screen and --confirm: ask the player first, it cannot be undone (world-backup keeps a copy).", + ["horizon-ctl world-delete Test --confirm"], + &[p("folder", Ty::Str, "world folder from worlds"), CONFIRM], mcp: true, local: false), cmd!("open", Session, "open WORLD [SEED] [creative]", "open or create a world from the title screen", "Opens saves/WORLD, creating it with SEED (and creative mode) when it doesn't exist.", ["horizon-ctl open Test 12345", "horizon-ctl open Build 0 creative"], @@ -190,10 +249,10 @@ pub const COMMANDS: &[Cmd] = &[ cmd!("light", Observe, "light X1 Y1 Z1 X2 Y2 Z2", "the stored sky and block light of a box", "At most 32768 blocks per request. One hex digit per block in `sky` and `block`, x fastest, then z, then y; `.` where no chunk is loaded.", ["horizon-ctl light 0 64 0 15 70 15"], - &[p("x1", Ty::Int, "corner X"), p("y1", Ty::Int, "corner Y"), p("z1", Ty::Int, "corner Z"), p("x2", Ty::Int, "opposite X"), p("y2", Ty::Int, "opposite Y"), p("z2", Ty::Int, "opposite Z")], mcp: true, local: false), + &BOX, mcp: true, local: false), cmd!("blocks", Observe, "blocks X1 Y1 Z1 X2 Y2 Z2", "the non-air blocks of a box, with counts per block", "At most 32768 blocks per request.", ["horizon-ctl blocks 0 60 0 15 70 15"], - &[p("x1", Ty::Int, "corner X"), p("y1", Ty::Int, "corner Y"), p("z1", Ty::Int, "corner Z"), p("x2", Ty::Int, "opposite X"), p("y2", Ty::Int, "opposite Y"), p("z2", Ty::Int, "opposite Z")], mcp: true, local: false), + &BOX, mcp: true, local: false), cmd!("find-block", Observe, "find-block BLOCK [RADIUS]", "the nearest loaded blocks of a kind", "Searches a cube of RADIUS (default 32, at most 64) around the player; returns the count and the 16 nearest.", ["horizon-ctl find-block oak_log", "horizon-ctl find-block diamond_ore 48"], @@ -264,12 +323,15 @@ pub const COMMANDS: &[Cmd] = &[ "down holds the key until key ... up, release or stop; wait does not release it. move, goto, jump, break and the other actions release the movement keys when they end.", ["horizon-ctl key space tap"], &[p("key", Ty::Str, "key name"), p("action", Ty::Enum(&["down", "up", "tap", "repeat"]), "what to do")], mcp: true, local: false), cmd!("mouse", Act, "mouse left|right|middle down|up|click", "press or release a mouse button in the world", "", - ["horizon-ctl mouse right click"], &[p("button", Ty::Enum(&["left", "right", "middle"]), "button"), p("action", Ty::Enum(&["down", "up", "click"]), "what to do")], mcp: false, local: false), + ["horizon-ctl mouse right click"], &[p("button", Ty::Enum(&["left", "right", "middle"]), "button"), p("action", Ty::Enum(&["down", "up", "click"]), "what to do")], mcp: true, local: false), + cmd!("interact-entity", Act, "interact-entity ID", "right-click an entity: trade with a villager, mount a horse, ride a boat, shear a sheep", + "Faces the entity (from entities), right-clicks it with the held item, waits two ticks and replies with the screen.", + ["horizon-ctl interact-entity 42"], &[p("id", Ty::Int, "entity id from entities")], mcp: true, local: true), cmd!("pad", Act, "pad BUTTON down|up|tap | pad stick left|right X Y | pad trigger left|right V | pad release | pad status", "a virtual controller: buttons, sticks and triggers as a real pad would send them", "Buttons by position: south east west north lb rb lt rt select start ls rs up down left right (south is Xbox A / PlayStation cross). Sticks run -1..1 with up positive and stay tilted until centred; triggers 0..1. Merged with any real controller; status lists the connected ones and what is held.", ["horizon-ctl pad south tap", "horizon-ctl pad stick left 0 1", "horizon-ctl pad trigger right 1", "horizon-ctl pad status"], - &[p("what", Ty::Str, "a button name, stick, trigger, release or status"), opt("a", Ty::Str, "down|up|tap, or left|right"), opt("b", Ty::Num, "stick X or trigger value"), opt("c", Ty::Num, "stick Y")], mcp: false, local: false), - cmd!("release", Act, "release", "release every key and mouse button", "", ["horizon-ctl release"], &[], mcp: false, local: false), + &[p("what", Ty::Str, "a button name, stick, trigger, release or status"), opt("a", Ty::Str, "down|up|tap, or left|right"), opt("b", Ty::Num, "stick X or trigger value"), opt("c", Ty::Num, "stick Y")], mcp: true, local: false), + cmd!("release", Act, "release", "release every key and mouse button", "", ["horizon-ctl release"], &[], mcp: true, local: false), cmd!("stop", Act, "stop", "cancel the running action (goto, break...) and release every key", "", ["horizon-ctl stop"], &[], mcp: true, local: false), // Screens cmd!("open-inventory", Screens, "open-inventory", "open the inventory screen (crafting grid 100-103, result 200)", "", @@ -317,7 +379,31 @@ pub const COMMANDS: &[Cmd] = &[ cmd!("respawn", Screens, "respawn", "respawn from the death screen", "", ["horizon-ctl respawn"], &[], mcp: true, local: false), cmd!("pause", Screens, "pause", "open the pause menu", "", ["horizon-ctl pause"], &[], mcp: true, local: false), cmd!("resume", Screens, "resume", "leave the pause menu", "", ["horizon-ctl resume"], &[], mcp: true, local: false), + cmd!("options", Screens, "options [PAGE]", "open the options screen, or one of its pages (Horizon's too)", + "Then ui lists its widgets and click, set and type change them, as with the mouse. options-set changes an options.txt value without the screen.", + ["horizon-ctl options video", "horizon-ctl options horizon"], &[opt("page", PAGES, "the page (default: the main options)")], mcp: true, local: false), + cmd!("book", Screens, "book [next|back|take|done]", "the open book or lectern: its page text, or press one of its buttons", + "", ["horizon-ctl book", "horizon-ctl book next"], &[opt("action", Ty::Enum(&["next", "back", "take", "done"]), "a button to press")], mcp: true, local: false), + cmd!("signedit", Screens, "signedit X Y Z [front|back]", "open the sign editor of the sign at X Y Z (then type and close)", + "", ["horizon-ctl signedit 3 64 1"], &[BLOCK_XYZ[0], BLOCK_XYZ[1], BLOCK_XYZ[2], opt("side", Ty::Enum(&["front", "back"]), "which side")], mcp: true, local: false), + cmd!("mount-menu", Screens, "mount-menu", "open the inventory of the horse, donkey, mule or llama being ridden", + "As the inventory key does while riding; also opens the nearest one's.", ["horizon-ctl mount-menu"], &[], mcp: true, local: false), cmd!("chat-log", Screens, "chat-log [N]", "the newest N chat messages", "", ["horizon-ctl chat-log 5"], &[], mcp: false, local: false), + // Multiplayer + cmd!("connect", Multiplayer, "connect ADDRESS [NAME]", "join a multiplayer server, or a friend's world by its invite code, from the title screen", + "ADDRESS is HOST[:PORT], or friend:CODE for an invite code. Only when the player asks: it reaches the network.", + ["horizon-ctl connect play.example.net", "horizon-ctl connect localhost:25565", "horizon-ctl connect friend:0B33K-Q405Q-..."], + &[p("address", Ty::Str, "HOST[:PORT] or friend:CODE"), opt("name", Ty::Str, "player name when offline")], mcp: true, local: false), + cmd!("disconnect", Multiplayer, "disconnect", "leave the server, back to the server list", "", ["horizon-ctl disconnect"], &[], mcp: true, local: false), + cmd!("servers", Multiplayer, "servers", "the Multiplayer screen's server list: name and address", + "Add, edit and remove them on the Multiplayer screen (click-button Multiplayer, then ui).", ["horizon-ctl servers"], &[], mcp: true, local: false), + cmd!("lan", Multiplayer, "lan open [PORT] [commands] [force] | lan close | lan status", "open the world to LAN (Open to LAN), stop, or see the guests", + "PORT 0 or none picks one; commands lets guests use cheats; force forces the game mode. Only when the player asks.", + ["horizon-ctl lan open", "horizon-ctl lan status", "horizon-ctl lan close"], + &[p("action", Ty::Enum(&["open", "close", "status"]), "what to do"), opt("port", Ty::Int, "port for open"), opt("commands", Ty::Bool, "allow cheats"), opt("force", Ty::Bool, "force the game mode")], mcp: true, local: false), + cmd!("friends", Multiplayer, "friends host|stop|status", "Play with Friends: share the open world behind an invite code, stop, or see who joined", + "status gives the code: share it only when the player asks. Friends join with connect friend:CODE.", + ["horizon-ctl friends host", "horizon-ctl friends status"], &[p("action", Ty::Enum(&["host", "stop", "status"]), "what to do")], mcp: true, local: false), // World cmd!("give", World, "give ITEM [COUNT]", "add items to the inventory", "", ["horizon-ctl give oak_log 16"], &[p("item", Ty::Str, "item id"), opt("count", Ty::Int, "how many (default 1)")], mcp: true, local: false), @@ -325,8 +411,20 @@ pub const COMMANDS: &[Cmd] = &[ &[p("ticks", Ty::Int, "day time")], mcp: true, local: false), cmd!("setblock", World, "setblock X Y Z BLOCK[props]", "set a block (with neighbour updates)", "", ["horizon-ctl setblock 0 64 0 stone"], &[BLOCK_XYZ[0], BLOCK_XYZ[1], BLOCK_XYZ[2], p("block", Ty::Str, "block state such as oak_stairs[facing=east]")], mcp: true, local: false), - cmd!("summon", World, "summon KIND [X Y Z] [baby]", "spawn a mob", "", ["horizon-ctl summon cow"], &[p("kind", Ty::Str, "mob type")], mcp: true, local: false), - cmd!("effect", World, "effect ID SECONDS [AMPLIFIER] | effect clear", "give a status effect", "", ["horizon-ctl effect speed 30 1"], &[], mcp: false, local: false), + cmd!("summon", World, "summon KIND [X Y Z] [baby]", "spawn a mob (in front of the player without a position)", "Replies with its id.", ["horizon-ctl summon cow", "horizon-ctl summon pig 10 64 3 baby"], + &[p("kind", Ty::Str, "mob type"), opt("x", Ty::Num, "X"), opt("y", Ty::Num, "Y"), opt("z", Ty::Num, "Z"), opt("baby", Ty::Bool, "a baby")], mcp: true, local: false), + cmd!("effect", World, "effect ID SECONDS [AMPLIFIER] | effect clear", "give a status effect, or clear them all", "", ["horizon-ctl effect speed 30 1", "horizon-ctl effect clear"], + &[p("id", Ty::Str, "effect id such as speed, or clear"), opt("seconds", Ty::Num, "duration"), opt("amplifier", Ty::Int, "level - 1 (default 0)")], mcp: true, local: false), + cmd!("effects", World, "effects", "the player's active status effects", "", ["horizon-ctl effects"], &[], mcp: true, local: false), + cmd!("xp", World, "xp LEVELS", "add experience levels (negative removes)", "", ["horizon-ctl xp 30"], &[p("levels", Ty::Int, "levels to add")], mcp: true, local: false), + cmd!("enchant", World, "enchant ID LEVEL", "enchant the held item (a book stores it)", "", ["horizon-ctl enchant sharpness 5"], + &[p("id", Ty::Str, "enchantment id"), p("level", Ty::Int, "level")], mcp: true, local: false), + cmd!("potion", World, "potion ITEM POTION", "give a potion item", "", ["horizon-ctl potion splash_potion healing"], + &[p("item", Ty::Enum(&["potion", "splash_potion", "lingering_potion", "tipped_arrow"]), "which item"), p("potion", Ty::Str, "potion id")], mcp: true, local: false), + cmd!("fill", World, "fill X1 Y1 Z1 X2 Y2 Z2 BLOCK", "set a box of loaded blocks", "", ["horizon-ctl fill 0 64 0 4 64 4 glass"], + &[BOX[0], BOX[1], BOX[2], BOX[3], BOX[4], BOX[5], p("block", Ty::Str, "block state")], mcp: true, local: false), + cmd!("container", World, "container X Y Z [ITEM COUNT]", "list a container's items, or add items to it", "", ["horizon-ctl container 3 64 1", "horizon-ctl container 3 64 1 diamond 3"], + &[BLOCK_XYZ[0], BLOCK_XYZ[1], BLOCK_XYZ[2], opt("item", Ty::Str, "item to add"), opt("count", Ty::Int, "how many")], mcp: true, local: false), cmd!("render-distance", World, "render-distance N", "chunks, 2..64", "", ["horizon-ctl render-distance 8"], &[p("chunks", Ty::Int, "render distance")], mcp: false, local: false), cmd!("wait", World, "wait TICKS", "wait until TICKS game ticks have passed (20 per second)", "Keys and mouse buttons held with key ... down or mouse ... down stay held while it waits. Release them with key ... up, release or stop.", @@ -340,8 +438,8 @@ pub const COMMANDS: &[Cmd] = &[ cmd!("mcp", Scripting, "mcp", "serve the Model Context Protocol on stdin/stdout, one tool per command", "Add it to an MCP client as a stdio server: command horizon-ctl, args [\"mcp\"] (with --socket PATH first if needed). The screenshot tool returns the image.", ["horizon-ctl mcp"], &[], mcp: false, local: true), - cmd!("bench", Scripting, "bench SECONDS", "reset frame stats, wait, reply with the summary", "", ["horizon-ctl bench 10"], &[], mcp: false, local: false), - cmd!("stats", Scripting, "stats [reset]", "frame-time summary since the last reset", "", ["horizon-ctl stats"], &[], mcp: false, local: false), + cmd!("bench", Scripting, "bench SECONDS", "reset frame stats, wait, reply with the summary", "", ["horizon-ctl bench 10"], &[p("seconds", Ty::Num, "how long to measure")], mcp: true, local: false), + cmd!("stats", Scripting, "stats [reset]", "frame-time summary since the last reset", "", ["horizon-ctl stats"], &[opt("reset", Ty::Bool, "start counting again")], mcp: true, local: false), cmd!("fly", Scripting, "fly X1 Y1 Z1 X2 Y2 Z2 SECONDS [PITCH [raw]]", "fly the camera along a line, then reply with the frame summary", "The reply's tick_ms and tick_ms_max are the world's smoothed tick time over the flight (the server thread's when single player runs on one). With raw, the reply also lists every frame time in milliseconds (frame_ms).", ["horizon-ctl fly 0 100 0 500 100 0 20"], &[], mcp: false, local: false), @@ -366,8 +464,9 @@ pub fn overview() -> String { } out.push_str( "\nEvery reply is one JSON line. Errors are {\"error\": \"...\"}; the exit status is 0 on\n\ - success, 1 when the game replied with an error, 2 for a usage error and 3 when the\n\ - game cannot be reached or started. Actions (goto, break, place...) block until done.\n\ + success, 1 when the game replied with an error, 2 for a usage error, 3 when the\n\ + game cannot be reached or started and 4 while No AI is on (the launcher's settings).\n\ + Actions (goto, break, place...) block until done.\n\ horizon-ctl help --game lists the running game's own commands, test hooks included.\n\ The socket is $HORIZON_CONTROL, else $XDG_RUNTIME_DIR/horizon-control.sock (on Windows\n\ %TEMP%\\horizon-control.json, a localhost TCP port with a token; any path ending in .json\n\ @@ -402,6 +501,73 @@ pub fn detail(c: &Cmd) -> String { out } +/// The generated reference, docs/horizon-ctl-commands.md (`horizon-ctl help --markdown`). +pub fn markdown() -> String { + let cell = |s: &str| s.replace('|', "\\|"); + let mut out = String::from( + "\n\ + # horizon-ctl commands\n\n\ + Every command `horizon-ctl` takes, its MCP tool in `horizon-ctl mcp` (the launcher's \ + `horizon-launcher mcp` offers the same tools as `game_`, all but `launch`) and its \ + arguments. Positional arguments come first, in order; `--flags` after them. \ + `horizon-ctl help --game` lists the game's own commands, test hooks included. \ + Design rules and the full inventory: [agent-control.md](agent-control.md).\n", + ); + for group in Group::ALL { + out.push_str(&format!( + "\n## {}\n\n| Command | MCP tool | What it does | Arguments |\n| --- | --- | --- | --- |\n", + group.title() + )); + for c in COMMANDS.iter().filter(|c| c.group == group) { + let tool = if c.mcp { + let mut t = format!("`{}`", tool_name(c)); + if DESTRUCTIVE.contains(&c.name) { + t.push_str(" (destructive)"); + } else if OPEN_WORLD.contains(&c.name) { + t.push_str(" (network)"); + } + t + } else { + "CLI only".to_owned() + }; + let args: Vec = c + .params + .iter() + .map(|p| { + let ty = match p.ty { + Ty::Int => "integer".to_owned(), + Ty::Num => "number".to_owned(), + Ty::Str => "string".to_owned(), + Ty::Rest => "text".to_owned(), + Ty::Bool => "boolean".to_owned(), + Ty::Enum(v) => v.join(", "), + }; + let name = if p.flag { + format!("--{}", p.name) + } else { + p.name.to_owned() + }; + let need = if p.required { ", required" } else { "" }; + format!("`{name}` ({ty}{need}): {}", cell(p.help)) + }) + .collect(); + out.push_str(&format!( + "| `{}` | {} | {} | {} |\n", + cell(c.usage), + tool, + cell(&capitalize(c.summary)), + if args.is_empty() { + "none".to_owned() + } else { + args.join("
") + } + )); + } + } + out +} + fn capitalize(s: &str) -> String { let mut chars = s.chars(); chars @@ -640,6 +806,43 @@ mod tests { assert_eq!(tool_name(find("look-at-entity").unwrap()), "look_at_entity"); } + #[test] + fn the_generated_reference_is_up_to_date() { + let path = concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../docs/horizon-ctl-commands.md" + ); + let on_disk = std::fs::read_to_string(path).unwrap_or_default(); + assert!( + on_disk == markdown(), + "docs/horizon-ctl-commands.md is out of date: run `horizon-ctl help --markdown > docs/horizon-ctl-commands.md`" + ); + for c in COMMANDS { + assert!( + on_disk.contains(&format!("`{}", c.usage.replace('|', "\\|"))), + "{} undocumented", + c.name + ); + } + } + + #[test] + fn destructive_and_network_tools_exist() { + for name in DESTRUCTIVE.iter().chain(OPEN_WORLD) { + assert!(find(name).is_some_and(|c| c.mcp), "{name}"); + } + let delete = find("world-delete").unwrap(); + assert_eq!( + line_for(delete, &json!({ "folder": "A", "confirm": true })).unwrap(), + ["world-delete", "A", "--confirm"] + ); + let lan = find("lan").unwrap(); + assert_eq!( + line_for(lan, &json!({ "action": "open", "commands": true })).unwrap(), + ["lan", "open", "commands"] + ); + } + #[test] fn help_mentions_every_command() { let text = overview(); diff --git a/crates/horizon-client/src/bin/horizon-ctl/main.rs b/crates/horizon-client/src/bin/horizon-ctl/main.rs index 27d9d5ba1..402808e81 100644 --- a/crates/horizon-client/src/bin/horizon-ctl/main.rs +++ b/crates/horizon-client/src/bin/horizon-ctl/main.rs @@ -20,6 +20,8 @@ use serde_json::{Value, json}; const GAME_ERROR: u8 = 1; const USAGE: u8 = 2; const UNREACHABLE: u8 = 3; +/// No AI is on (`horizon_core::no_ai`): agent control is off. +const DENIED: u8 = 4; /// A failure, with the exit status it maps to. #[derive(Debug)] @@ -34,6 +36,13 @@ impl Failure { status: USAGE, } } + /// No AI is on in the game's home. + fn denied() -> Self { + Self { + reply: json!({ "error": horizon_core::no_ai::REFUSAL, "kind": "denied" }), + status: DENIED, + } + } fn unreachable(message: impl Into) -> Self { Self { reply: json!({ "error": message.into(), "kind": "connection" }), @@ -98,6 +107,8 @@ impl Client { pub struct Session { pub socket: PathBuf, pub timeout: Option, + /// The game's home, where No AI is read (`horizon_core::no_ai`). + pub home: PathBuf, client: Option, } @@ -106,9 +117,14 @@ impl Session { Self { socket, timeout, + home: horizon_client::logging::game_home(), client: None, } } + /// A failure while No AI is on: every command refuses (help aside). + pub fn allowed(&self) -> Result<(), Failure> { + horizon_core::no_ai::check(&self.home).map_err(|_| Failure::denied()) + } fn client(&mut self) -> Result<&mut Client, Failure> { if self.client.is_none() { self.client = Some(Client::connect(&self.socket, self.timeout)?); @@ -137,6 +153,7 @@ impl Session { let Some(name) = words.first().map(String::as_str) else { return Err(Failure::usage("no command; try horizon-ctl help")); }; + self.allowed()?; if words.iter().skip(1).any(|w| w == "--help" || w == "-h") { return Err(Failure::usage( "use horizon-ctl COMMAND --help outside scripts", @@ -174,6 +191,18 @@ impl Session { ready["launch"] = reply; Ok(ready) } + "interact-entity" => { + let id = match words { + [_, id] if id.parse::().is_ok() => id, + _ => return Err(Failure::usage(format!("usage: {}", usage(name)))), + }; + self.game(&format!("look-at entity {id}"))?; + self.game("mouse right click")?; + self.game("wait 2")?; + let mut screen = self.game("screen")?; + screen["ok"] = json!(true); + Ok(screen) + } "hold" => { let (key, seconds) = match words { [_, key, _] => (key.clone(), number(2, "SECONDS")?), @@ -183,7 +212,7 @@ impl Session { thread::sleep(Duration::from_secs_f64(seconds.max(0.0))); self.game(&format!("key {key} up")) } - "logs" => logs(&horizon_client::logging::game_home(), &words[1..]), + "logs" => logs(&self.home, &words[1..]), "wait-ready" => { let limit = if words.len() > 1 { number(1, "SECONDS")? @@ -417,6 +446,10 @@ fn main() -> ExitCode { print!("{}", commands::overview()); 0 } + Some("help") if args.get(1).is_some_and(|a| a == "--markdown") => { + print!("{}", commands::markdown()); + 0 + } Some("help") if args.get(1).is_none_or(|a| a != "--game") => match args.get(1) { None => { print!("{}", commands::overview()); @@ -451,6 +484,10 @@ fn main() -> ExitCode { } } } + Some("mcp") if session.allowed().is_err() => { + eprintln!("horizon-ctl mcp: {}", horizon_core::no_ai::REFUSAL); + DENIED + } Some("mcp") => match mcp::serve(&mut session) { Ok(()) => 0, Err(e) => { @@ -581,6 +618,27 @@ mod tests { assert_eq!(f.status, USAGE); } + #[test] + fn no_ai_refuses_every_command() { + let home = std::env::temp_dir().join(format!("horizon-ctl-no-ai-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&home); + let mut s = Session::new(std::env::temp_dir().join("horizon-ctl-nobody.sock"), None); + s.home = home.clone(); + assert_eq!( + s.run(&["state".to_owned()]).unwrap_err().status, + UNREACHABLE + ); + horizon_core::no_ai::set(&home, true).unwrap(); + for words in [vec!["state"], vec!["logs"], vec!["launch", "--world", "A"]] { + let words: Vec = words.into_iter().map(str::to_owned).collect(); + let f = s.run(&words).unwrap_err(); + assert_eq!(f.status, DENIED, "{words:?}"); + assert_eq!(f.reply["kind"], "denied"); + assert_eq!(f.reply["error"], horizon_core::no_ai::REFUSAL); + } + let _ = std::fs::remove_dir_all(&home); + } + #[test] fn screenshot_paths_become_absolute() { let mut words = vec!["screenshot".to_owned(), "a.png".to_owned()]; diff --git a/crates/horizon-client/src/bin/horizon-ctl/mcp.rs b/crates/horizon-client/src/bin/horizon-ctl/mcp.rs index 8d67953a5..ae30b7498 100644 --- a/crates/horizon-client/src/bin/horizon-ctl/mcp.rs +++ b/crates/horizon-client/src/bin/horizon-ctl/mcp.rs @@ -23,7 +23,13 @@ fn tools() -> Vec { schema = json!({ "type": "object", "properties": {} }); description = "Capture the game window and return it as a PNG image.".into(); } - json!({ "name": commands::tool_name(c), "description": description, "inputSchema": schema }) + let mut tool = json!({ "name": commands::tool_name(c), "description": description, "inputSchema": schema }); + if commands::DESTRUCTIVE.contains(&c.name) { + tool["annotations"] = json!({ "destructiveHint": true }); + } else if commands::OPEN_WORLD.contains(&c.name) { + tool["annotations"] = json!({ "openWorldHint": true }); + } + tool }) .collect() } diff --git a/crates/horizon-client/src/component.rs b/crates/horizon-client/src/component.rs index 0e04eab5e..68460054b 100644 --- a/crates/horizon-client/src/component.rs +++ b/crates/horizon-client/src/component.rs @@ -167,6 +167,7 @@ fn object_style(o: &serde_json::Map) -> Style { style.underlined = flag("underlined"); style.strikethrough = flag("strikethrough"); style.obfuscated = flag("obfuscated"); + style.font = o.get("font").and_then(crate::text::font_id); style } /// `ComponentSerialization.CODEC` decoding into text. `selector` components @@ -266,4 +267,26 @@ mod tests { let (v, _) = parse_snbt("[\"a\",{\"text\":\"b\"}]").unwrap(); assert_eq!(to_text(&v, &mut |_| Text::empty()).plain(), "ab"); } + + #[test] + fn the_font_is_inherited_and_kept() { + let (v, _) = + parse_snbt(r#"{text:"a",font:"alt",extra:["b",{text:"c",font:"minecraft:uniform"}]}"#) + .unwrap(); + let t = to_text(&v, &mut |_| Text::empty()); + let fonts: Vec<_> = t.chars().map(|(_, s)| s.font.clone()).collect(); + let (alt, uniform) = ( + Some("minecraft:alt".into()), + Some("minecraft:uniform".into()), + ); + assert_eq!(fonts, [alt.clone(), alt, uniform]); + // Back to JSON with the field, which a re-read keeps. + let again = to_text(&t.component(), &mut |_| Text::empty()); + let kept: Vec<_> = again.chars().map(|(_, s)| s.font.clone()).collect(); + assert_eq!(kept, fonts); + // Not an identifier: no font. + let (v, _) = parse_snbt(r#"{text:"a",font:"Bad Font"}"#).unwrap(); + let t = to_text(&v, &mut |_| Text::empty()); + assert_eq!(t.spans[0].style.font, None); + } } diff --git a/crates/horizon-client/src/control.rs b/crates/horizon-client/src/control.rs index 9749cc9bd..931bcbdf5 100644 --- a/crates/horizon-client/src/control.rs +++ b/crates/horizon-client/src/control.rs @@ -13,7 +13,11 @@ use std::{ io::{self, BufRead, BufReader, Read, Write}, net::{Ipv4Addr, TcpListener, TcpStream}, path::{Path, PathBuf}, - sync::mpsc, + sync::{ + Arc, + atomic::{AtomicBool, AtomicUsize, Ordering}, + mpsc, + }, thread, }; @@ -151,6 +155,12 @@ pub struct Server { path: PathBuf, requests: mpsc::Receiver, sender: mpsc::Sender, + /// Clients connected now (an MCP server keeps one open; horizon-ctl one per command). + clients: Arc, + /// Set when the server is dropped: the listener stops accepting and exits. + closed: Arc, + /// The TCP port, to wake the listener when closing. + port: Option, } /// `$HORIZON_CONTROL`, else `horizon-control.sock` in the user's runtime @@ -174,10 +184,15 @@ impl Server { } let (sender, requests) = mpsc::channel(); let local = sender.clone(); + let clients = Arc::new(AtomicUsize::new(0)); + let counted = clients.clone(); + let closed = Arc::new(AtomicBool::new(false)); + let mut tcp_port = None; if uses_tcp(path) { let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))?; let token = random_token(); let port = listener.local_addr()?.port(); + tcp_port = Some(port); write_private( path, &serde_json::json!({ "transport": "tcp", "port": port, "token": token }) @@ -186,6 +201,8 @@ impl Server { spawn_listener( move || listener.accept().map(|(s, _)| s), sender, + counted, + closed.clone(), move |stream: TcpStream| { let _ = stream.set_nodelay(true); let mut stream = Stream::Tcp(stream); @@ -199,6 +216,8 @@ impl Server { spawn_listener( move || listener.accept().map(|(s, _)| s), sender, + counted, + closed.clone(), |s| Some(Stream::Unix(s)), )?; } @@ -207,6 +226,9 @@ impl Server { path: path.to_owned(), requests, sender: local, + clients, + closed, + port: tcp_port, }) } /// Commands from inside the process only (`--benchmark` without `--control`). @@ -216,8 +238,15 @@ impl Server { path: PathBuf::new(), requests, sender, + clients: Arc::default(), + closed: Arc::default(), + port: None, } } + /// How many clients are connected. + pub fn clients(&self) -> usize { + self.clients.load(Ordering::Relaxed) + } /// Sends commands as a socket client would, from another thread. pub fn sender(&self) -> mpsc::Sender { self.sender.clone() @@ -234,6 +263,8 @@ impl Server { fn spawn_listener( mut accept_next: impl FnMut() -> io::Result + Send + 'static, sender: mpsc::Sender, + clients: Arc, + closed: Arc, accept: impl Fn(S) -> Option + Send + Sync + 'static, ) -> io::Result<()> { let accept = std::sync::Arc::new(accept); @@ -241,17 +272,24 @@ fn spawn_listener( .name("horizon-control".into()) .spawn(move || { loop { - let Ok(stream) = accept_next() else { + let next = accept_next(); + if closed.load(Ordering::Relaxed) { + return; + } + let Ok(stream) = next else { thread::sleep(std::time::Duration::from_millis(10)); continue; }; let sender = sender.clone(); let accept = accept.clone(); + let clients = clients.clone(); let _ = thread::Builder::new() .name("horizon-control-client".into()) .spawn(move || { if let Some(stream) = accept(stream) { + clients.fetch_add(1, Ordering::Relaxed); serve(stream, &sender); + clients.fetch_sub(1, Ordering::Relaxed); } }); } @@ -287,6 +325,18 @@ fn authenticate(stream: &mut Stream, token: &str) -> bool { impl Drop for Server { fn drop(&mut self) { + if self.path.as_os_str().is_empty() { + return; + } + // Wake the listener so it sees `closed` and exits (agent control turned off in-game). + self.closed.store(true, Ordering::Relaxed); + match self.port { + Some(port) => drop(TcpStream::connect((Ipv4Addr::LOCALHOST, port))), + #[cfg(unix)] + None => drop(UnixStream::connect(&self.path)), + #[cfg(not(unix))] + None => {} + } let _ = std::fs::remove_file(&self.path); } } diff --git a/crates/horizon-client/src/enchant.rs b/crates/horizon-client/src/enchant.rs index 039ea658f..ca2ea6f5c 100644 --- a/crates/horizon-client/src/enchant.rs +++ b/crates/horizon-client/src/enchant.rs @@ -193,6 +193,8 @@ impl Enchantments { || k.starts_with("item.minecraft.splash_potion") || k.starts_with("item.minecraft.lingering_potion") || k.starts_with("item.minecraft.tipped_arrow") + || k.starts_with("item.minecraft.firework_rocket.") + || k.starts_with("item.minecraft.firework_star.") || k.starts_with("trim_") || k.starts_with("potion.") || k.starts_with("container.") diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs index cfbdb0636..65536d710 100644 --- a/crates/horizon-client/src/entities.rs +++ b/crates/horizon-client/src/entities.rs @@ -98,12 +98,73 @@ impl ItemEntity { lava_hurt, } } - /// Returns false when the item should be removed. + /// `ItemEntity.tick` on a server: an item whose box is inside a block + /// (one placed where it lay) has no physics this tick + /// (`level.noCollision(box.deflate(1.0E-7))`). + pub fn inside_block(&self, world: &World, collision: &BlockCollisionRegistry<'_>) -> bool { + let mut scene = SceneCollisions { + world, + binding: collision, + subject: None, + }; + let inner = self.bounds().deflate(Vec3::new(1.0e-7, 1.0e-7, 1.0e-7)); + !crate::collisions::no_collision_empty(&mut scene, inner) + } + /// `Entity.moveTowardsClosestSpace` from the middle of the item's box: + /// towards the nearest side of its block (north, south, west, east or + /// up) without a full collision cube, at `speed` (`nextFloat() * 0.2 + + /// 0.1`). + pub fn move_towards_closest_space(&mut self, world: &World, facts: &BlockFacts, speed: f32) { + let bounds = self.bounds(); + let at = Vec3::new( + self.position.x, + (bounds.min_position().y + bounds.max_position().y) / 2.0, + self.position.z, + ); + let pos = [ + at.x.floor() as i32, + at.y.floor() as i32, + at.z.floor() as i32, + ]; + let delta = [ + at.x - f64::from(pos[0]), + at.y - f64::from(pos[1]), + at.z - f64::from(pos[2]), + ]; + // (axis, step): NORTH, SOUTH, WEST, EAST, UP. + let mut closest = (1, 1); + let mut nearest = f64::MAX; + for (axis, step) in [(2, -1), (2, 1), (0, -1), (0, 1), (1, 1)] { + let mut n = pos; + n[axis] += step; + if !facts.get(world.block(n[0], n[1], n[2])).full_collision { + let d = if step > 0 { + 1.0 - delta[axis] + } else { + delta[axis] + }; + if d < nearest { + nearest = d; + closest = (axis, step); + } + } + } + let push = f64::from(closest.1 as f32 * speed); + let v = self.velocity.scale(0.75); + self.velocity = match closest.0 { + 0 => Vec3::new(push, v.y, v.z), + 1 => Vec3::new(v.x, push, v.z), + _ => Vec3::new(v.x, v.y, push), + }; + } + /// Returns false when the item should be removed. `no_physics`: the item + /// moves through blocks this tick ([`ItemEntity::inside_block`]). pub fn tick( &mut self, world: &World, facts: &BlockFacts, collision: &BlockCollisionRegistry<'_>, + no_physics: bool, ) -> bool { self.ticks += 1; self.previous = self.position; @@ -140,15 +201,22 @@ impl ItemEntity { subject: None, }; let wanted = self.velocity; - let moved = scene - .resolve(self.bounds(), wanted, 0.0, self.on_ground) - .unwrap_or(Vec3::ZERO); + // Entity.move with noPhysics: straight through, the ground as it was. + let moved = if no_physics { + wanted + } else { + scene + .resolve(self.bounds(), wanted, 0.0, self.on_ground) + .unwrap_or(Vec3::ZERO) + }; self.position = Vec3::new( self.position.x + moved.x, self.position.y + moved.y, self.position.z + moved.z, ); - self.on_ground = wanted.y < 0.0 && moved.y != wanted.y; + if !no_physics { + self.on_ground = wanted.y < 0.0 && moved.y != wanted.y; + } if moved.x != wanted.x { self.velocity.x = 0.0; } diff --git a/crates/horizon-client/src/entity.wgsl b/crates/horizon-client/src/entity.wgsl index 2c6af26f9..2e865dfb1 100644 --- a/crates/horizon-client/src/entity.wgsl +++ b/crates/horizon-client/src/entity.wgsl @@ -43,6 +43,7 @@ struct Out { @location(8) back_color: vec4, // entity.vsh's lightMapColor, multiplied in after the overlay. @location(9) light_color: vec4, + @location(10) @interpolate(flat) weather_rect: vec4, } // Shipped light.glsl; normals are already transformed and RGBA8_SNORM packed. fn entity_light(normal: vec3, nether: bool) -> f32 { @@ -109,6 +110,13 @@ fn entity_vertex(position: vec3, uv: vec2, @location(2) overlay: u32, @location(3) color: vec4, @location(4) light: vec4, @location(5) normal: vec4) -> Out { return entity_vertex(position, uv, overlay, color, light, normal); } +// Retained bolt-local geometry, translated using the same f64 camera +// subtraction as the former CPU path before adding each local f32 position. +@vertex fn vs_lightning(@location(0) position: vec3, @location(1) uv: vec2, + @location(2) overlay: u32, @location(3) color: vec4, @location(4) light: vec4, @location(5) normal: vec4, + @location(6) offset: vec3) -> Out { + return entity_vertex(offset + position, uv, overlay, color, light, normal); +} struct CloudInfo { offset: vec4, colors: array, 4>, @@ -209,3 +217,135 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 { @fragment fn fs_water_mask() -> @location(0) vec4 { return vec4(0.0); } + +// WEATHER_MATH_BEGIN +// Unsigned 64-bit helpers (low word first). Snow adds a random double to a +// float drift before casting to float. Retaining the 53-bit base avoids early +// rounding, including ties, without requiring optional GPU float64 support. +fn weather_shr_jam(v: vec2, n: u32) -> vec2 { + if n == 0u { return v; } + if n < 32u { + return vec2((v.x >> n) | (v.y << (32u - n)) | select(0u, 1u, (v.x << (32u - n)) != 0u), v.y >> n); + } + if n == 32u { return vec2(v.y | select(0u, 1u, v.x != 0u), 0u); } + if n < 64u { + return vec2((v.y >> (n - 32u)) | select(0u, 1u, v.x != 0u || (v.y << (64u - n)) != 0u), 0u); + } + return vec2(select(0u, 1u, any(v != vec2(0u))), 0u); +} +fn weather_add64(a: vec2, b: vec2) -> vec2 { + let lo = a.x + b.x; + return vec2(lo, a.y + b.y + select(0u, 1u, lo < a.x)); +} +fn weather_sub64(a: vec2, b: vec2) -> vec2 { + return vec2(a.x - b.x, a.y - b.y - select(0u, 1u, a.x < b.x)); +} +fn weather_double_plus_float(base: vec2, delta: f32) -> f32 { + // The random base is nonnegative and either zero or >= 2^-53. + if all(base == vec2(0u)) { return select(delta, 0.0, delta == 0.0); } + let db = bitcast(delta); + let mag = db & 0x7fffffffu; + let be = i32((base.y >> 20u) & 2047u) - 1023; + var de = i32(mag >> 23u) - 127; + var dm = (mag & 0x7fffffu) | 0x800000u; + if mag < 0x800000u { + dm = mag; + if dm == 0u { de = -200; } + else { + let shift = countLeadingZeros(dm) - 8u; + dm <<= shift; + de = -126 - i32(shift); + } + } + let e = max(be, de); + // Leading significand bit at 61, with room for addition and guard bits. + var a = vec2(base.x << 9u, ((base.y & 0xfffffu) | 0x100000u) << 9u | (base.x >> 23u)); + var b = vec2(0u, dm << 6u); + a = weather_shr_jam(a, u32(e - be)); + b = weather_shr_jam(b, u32(e - de)); + var sign = 0u; + var value: vec2; + if (db >> 31u) == 0u { value = weather_add64(a, b); } + else if a.y > b.y || (a.y == b.y && a.x >= b.x) { value = weather_sub64(a, b); } + else { value = weather_sub64(b, a); sign = 0x80000000u; } + if all(value == vec2(0u)) { return 0.0; } + let leading = select(31u - countLeadingZeros(value.x), 63u - countLeadingZeros(value.y), value.y != 0u); + var exponent = e + i32(leading) - 61; + // Normalize the leading bit to 62. After jamming, bit 38 is the guard + // bit and bits 0..37 distinguish a tie from a value above the midpoint. + let shift = 62u - leading; + if shift >= 32u { value = vec2(0u, value.x << (shift - 32u)); } + else if shift != 0u { value = vec2(value.x << shift, (value.y << shift) | (value.x >> (32u - shift))); } + // Vanilla first rounds the addition to double, then casts to float. + // Round at bit 10 (53 retained bits) before the 24-bit rounding below; + // otherwise a double-rounding midpoint can select the wrong float. + let double_guard = (value.x & 512u) != 0u; + let double_sticky = (value.x & 511u) != 0u; + let double_odd = (value.x & 1024u) != 0u; + value.x &= 0xfffffc00u; + if double_guard && (double_sticky || double_odd) { + value = weather_add64(value, vec2(1024u, 0u)); + } + if (value.y & 0x80000000u) != 0u { + value = weather_shr_jam(value, 1u); + exponent += 1; + } + var mantissa = value.y >> 7u; + let guard = (value.y & 64u) != 0u; + let sticky = (value.y & 63u) != 0u || value.x != 0u; + if guard && (sticky || (mantissa & 1u) != 0u) { mantissa += 1u; } + if mantissa >= 0x1000000u { mantissa >>= 1u; exponent += 1; } + return bitcast(sign | (u32(exponent + 127) << 23u) | (mantissa & 0x7fffffu)); +} +fn weather_phase(animation: vec4, bases: vec4, snow: u32, time: vec4) -> vec2 { + if snow == 0u { + let ticks = time.x + animation.y; + let t = ticks + time.z; + let step = -t / 32.0; + let offset = step * animation.x; + return vec2(0.0, offset % 32.0); + } + let t = time.x + time.z; + let u_time = t * 0.01; + let du = u_time * animation.z; + let v_time = t * animation.w; + let dv = v_time * 0.001; + let u = weather_double_plus_float(bases.xy, du); + let v = weather_double_plus_float(bases.zw, dv); + let fall_time = time.y + time.z; + let fall = -fall_time / 512.0; + return vec2(u, fall + v); +} +// Atlas sampler is nearest with no mipmaps. Clamp the integer texel inside +// the sprite even when a fractional coordinate rounds up at its far edge. +fn weather_texel(uv: vec2, rect: vec4, dimensions: vec2) -> vec2 { + let size = vec2(dimensions); + let origin = vec2(round(rect.xy * size)); + let extent = max(vec2(round(rect.zw * size)), vec2(1)); + let local = min(vec2(floor(fract(uv) * vec2(extent))), extent - vec2(1)); + return origin + local; +} +// WEATHER_MATH_END + +struct WeatherTime { values: vec4 } +@group(1) @binding(1) var weather_time: WeatherTime; +@vertex fn vs_weather(@location(0) position: vec3, @location(1) uv: vec2, + @location(2) rect: vec4, @location(3) animation: vec4, + @location(4) bases: vec4, @location(5) color: vec4, + @location(6) light: vec4, @location(7) snow: u32) -> Out { + let phase = weather_phase(animation, bases, snow, weather_time.values); + var out = entity_vertex(position, uv + phase, 0u, color, light, vec4(0.0)); + out.weather_rect = rect; + return out; +} +@fragment fn fs_weather(in: Out) -> @location(0) vec4 { + // Repeat within this sprite, never across the atlas. The atlas uses nearest + // filtering and no mipmaps, so fractional UVs have no seam derivatives. + let texel = weather_texel(in.uv, in.weather_rect, textureDimensions(atlas)); + var color = textureLoad(atlas, texel, 0) * in.color; + if color.a < 0.1 { discard; } + color *= in.light_color; + let f = max(linear_fog(in.spherical, globals.fog.x, globals.fog.y), + linear_fog(in.cylindrical, globals.fog.z, globals.fog.w)); + return vec4(mix(color.rgb, globals.fog_color.rgb, f * globals.fog_color.a), color.a); +} diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index aaccdd844..49ea776ba 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -89,6 +89,47 @@ impl Base<'_> { } /// `LivingEntity` + `Mob` (+ `AgeableMob`, creeper and skeleton specifics). +/// The mobs whose class extends vanilla's `Animal` (and so save `InLove`): +/// not allays, villagers, golems, dolphins or fish. +fn is_animal(id: &str) -> bool { + matches!( + id.strip_prefix("minecraft:").unwrap_or(id), + "pig" + | "cow" + | "mooshroom" + | "sheep" + | "chicken" + | "rabbit" + | "horse" + | "donkey" + | "mule" + | "zombie_horse" + | "skeleton_horse" + | "llama" + | "trader_llama" + | "goat" + | "panda" + | "polar_bear" + | "fox" + | "wolf" + | "cat" + | "ocelot" + | "parrot" + | "bee" + | "turtle" + | "armadillo" + | "frog" + | "axolotl" + | "hoglin" + | "strider" + | "camel" + | "camel_husk" + | "sniffer" + | "happy_ghast" + | "nautilus" + | "zombie_nautilus" + ) +} pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { let base = Base { id: &m.kind.id, @@ -175,12 +216,15 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { for (key, value) in [ ("Age", Tag::Int(0)), ("ForcedAge", Tag::Int(0)), - ("InLove", Tag::Int(0)), ("AgeLocked", Tag::Byte(0)), ] { map.entry(key.into()).or_insert(value); } } + // Animal.addAdditionalSaveData: the love ticks left, whatever the save had. + if is_animal(id) { + map.insert("InLove".into(), Tag::Int(m.extra.in_love.max(0))); + } match id { "minecraft:creeper" => { for (key, value) in [("Fuse", Tag::Short(30)), ("ExplosionRadius", Tag::Byte(3))] { @@ -445,10 +489,10 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { map.entry(key.into()).or_insert(value); } } + // Sheep.addAdditionalSaveData: its wool as it is now. "minecraft:sheep" => { - for (key, value) in [("Color", Tag::Byte(0)), ("Sheared", Tag::Byte(0))] { - map.entry(key.into()).or_insert(value); - } + map.insert("Color".into(), Tag::Byte((m.extra.color & 15) as i8)); + map.insert("Sheared".into(), Tag::Byte(i8::from(m.extra.sheared))); } // CopperGolem.addAdditionalSaveData. "minecraft:copper_golem" => { @@ -621,6 +665,9 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.extra.forced_age = number(tag.get("ForcedAge")).unwrap_or(0) as i32; m.extra.age_locked = flag(tag, "AgeLocked"); } + if is_animal(&m.kind.id) { + m.extra.in_love = number(tag.get("InLove")).unwrap_or(0) as i32; + } m.name_visible = flag(tag, "CustomNameVisible"); m.no_ai = flag(tag, "NoAI"); m.no_gravity = flag(tag, "NoGravity"); @@ -832,6 +879,11 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - } m.extra.egg_time = number(tag.get("life_ticks")).map_or(-1, |v| v as i32); } + // Sheep.readAdditionalSaveData: white and unsheared when absent. + if m.species() == crate::mobs::Species::Sheep { + m.extra.color = number(tag.get("Color")).map_or(0, |c| (c as u8) & 15); + m.extra.sheared = flag(tag, "Sheared"); + } if m.species() == crate::mobs::Species::Shulker { m.extra.variant3 = number(tag.get("AttachFace")).unwrap_or(0).clamp(0, 5) as u8; m.extra.counter = number(tag.get("Peek")).unwrap_or(0).clamp(0, 100) as i32; @@ -2051,3 +2103,39 @@ mod axolotl_nbt_tests { assert_eq!(mm.temptation_cooldown_ticks.value(), Some(42)); } } + +#[cfg(test)] +mod sheep_nbt_tests { + use super::*; + #[test] + fn a_sheep_keeps_its_dyed_and_sheared_wool() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION); + if !root.join("items.json").exists() { + return; + } + let data = crate::mobs::MobTypes::load(&root).unwrap(); + let mut m = Mob::new( + 1, + Arc::new(data.types["minecraft:sheep"].clone()), + Vec3::new(0.0, 4.0, 0.0), + 0.0, + ); + // Summoned white, then dyed red and sheared: the save has it now. + let raw = Tag::compound([("Color", Tag::Byte(0)), ("Sheared", Tag::Byte(0))]); + (m.extra.color, m.extra.sheared) = (14, true); + let tag = mob_to_nbt(&m, [1, 2, 3, 4], Some(&raw)); + assert_eq!( + (number(tag.get("Color")), number(tag.get("Sheared"))), + (Some(14), Some(1)) + ); + let types: HashMap> = data + .types + .iter() + .map(|(k, v)| (k.clone(), Arc::new(v.clone()))) + .collect(); + let back = mob_from_nbt(&tag, &types, 2).unwrap(); + assert_eq!((back.extra.color, back.extra.sheared), (14, true)); + } +} diff --git a/crates/horizon-client/src/extras.rs b/crates/horizon-client/src/extras.rs index c7be78019..698741846 100644 --- a/crates/horizon-client/src/extras.rs +++ b/crates/horizon-client/src/extras.rs @@ -107,6 +107,11 @@ pub struct Extras { pub sort: bool, /// A vanilla key name: sorts the part under the cursor. pub sort_key: String, + /// No AI: every AI feature hidden and off (`horizon_core::no_ai`; the launcher writes it too). + pub no_ai: bool, + /// Agents may control the game the player starts: it opens its control socket for + /// horizon-ctl and MCP clients (off by default; an agent's own launch always opens it). + pub agent_control: bool, } impl Default for Extras { fn default() -> Self { @@ -135,6 +140,8 @@ impl Default for Extras { mouse_tweaks_wheel: true, sort: false, sort_key: "key.keyboard.unknown".into(), + no_ai: false, + agent_control: false, } } } @@ -198,6 +205,8 @@ impl Extras { "mouseTweaksWheel" => e.mouse_tweaks_wheel = flag(e.mouse_tweaks_wheel), "sort" => e.sort = flag(e.sort), "sortKey" if value.starts_with("key.") => e.sort_key = value.to_owned(), + horizon_core::no_ai::KEY => e.no_ai = flag(e.no_ai), + "agentControl" => e.agent_control = flag(e.agent_control), _ => {} } } @@ -205,7 +214,7 @@ impl Extras { } pub fn serialize(&self) -> String { format!( - "fullbright:{}\ndynamicLights:{}\nzoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\nmouseTweaks:{}\nmouseTweaksWheel:{}\nsort:{}\nsortKey:{}\n", + "fullbright:{}\ndynamicLights:{}\nzoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\nmouseTweaks:{}\nmouseTweaksWheel:{}\nsort:{}\nsortKey:{}\n{}:{}\nagentControl:{}\n", bool_text(self.fullbright), bool_text(self.dynamic_lights), bool_text(self.zoom), @@ -234,6 +243,9 @@ impl Extras { bool_text(self.mouse_tweaks_wheel), bool_text(self.sort), self.sort_key, + horizon_core::no_ai::KEY, + bool_text(self.no_ai), + bool_text(self.agent_control), ) } /// Binds the extra key `name` (`ZOOM_KEY`, `SORT_KEY`); false for @@ -451,6 +463,9 @@ pub enum Item { MouseTweaksWheel, Sort, SortKey, + /// Not on the Extras page: Horizon Settings shows No AI, its AI Agent page Agent Control. + NoAi, + AgentControl, } /// The Extras page: headers and items. pub fn rows() -> Vec> { @@ -529,6 +544,8 @@ impl Item { Item::FpsLows => "Minimum and 1% low", Item::Keystrokes => "Keystrokes", Item::KeystrokesCps => "Clicks per second", + Item::NoAi => "No AI", + Item::AgentControl => "Agent Control", } } /// The switch this setting belongs to: it does nothing while that is off. @@ -542,7 +559,7 @@ impl Item { MouseTweaksWheel => MouseTweaks, SortKey => Sort, Fullbright | DynamicLights | Zoom | Minimap | Fps | Keystrokes | MouseTweaks | Sort - | AutoReconnect => { + | AutoReconnect | NoAi | AgentControl => { return None; } }) @@ -586,6 +603,12 @@ impl Item { } Item::Keystrokes => "Movement keys, jump and mouse buttons as you press them.", Item::KeystrokesCps => "Clicks in the last second under each mouse button.", + Item::NoAi => { + "Hides and turns off every AI feature: agent control, horizon-ctl and the MCP servers. The launcher's switch too." + } + Item::AgentControl => { + "Your own AI agent can play this game through horizon-ctl or an MCP client, on this computer only." + } } } /// The frame-time cost the main switch of an extra shows. @@ -616,6 +639,8 @@ impl Item { Item::MouseTweaks => e.mouse_tweaks, Item::MouseTweaksWheel => e.mouse_tweaks_wheel, Item::Sort => e.sort, + Item::NoAi => e.no_ai, + Item::AgentControl => e.agent_control, _ => return None, }) } @@ -671,6 +696,8 @@ impl Item { } Item::MinimapShape => e.minimap_round = !e.minimap_round, Item::MinimapZoom => e.minimap_zoom = next(&MINIMAP_ZOOMS, e.minimap_zoom, back), + Item::NoAi => e.no_ai = !e.no_ai, + Item::AgentControl => e.agent_control = !e.agent_control, Item::ZoomKey | Item::SortKey => {} } } diff --git a/crates/horizon-client/src/font.rs b/crates/horizon-client/src/font.rs index aeedb92bd..c5e5760f3 100644 --- a/crates/horizon-client/src/font.rs +++ b/crates/horizon-client/src/font.rs @@ -1,19 +1,27 @@ -//! The default font (FontSet over `font/default.json`): space and bitmap -//! providers from the shared atlas, the unihex (GNU Unifont) fallback whose -//! glyphs are rasterized on demand into a reserved atlas region, vanilla -//! glyph metrics (ascent, oversampling, advances, bold/shadow offsets), -//! styled drawing and StringSplitter-style line wrapping. +//! Fonts (FontManager / FontSet): `font/default.json` and every other font a +//! text component names (`minecraft:alt`, `minecraft:uniform`, a pack's own), +//! each a list of providers tried in order: `space`, `bitmap` (sheets in the +//! shared atlas, or rasterized on demand when a pack's sheet is not in it), +//! `unihex` (GNU Unifont) and `ttf` (TrueTypeGlyphProvider, rasterized with +//! ab_glyph). Glyphs drawn at run time go into a reserved atlas region. +//! Vanilla glyph metrics (ascent, oversampling, advances, bold/shadow +//! offsets), styled drawing and StringSplitter-style line wrapping. use crate::{ hud::Rect, text::{Style, Text}, zip::Zip, }; +use ab_glyph::{Font as _, ScaleFont as _}; use std::{ cell::RefCell, collections::HashMap, path::{Path, PathBuf}, + sync::Arc, }; +/// `FontDescription.DEFAULT`. +pub const DEFAULT: &str = "minecraft:default"; + /// A glyph ready to draw: atlas UVs and its box relative to the pen /// position (GlyphBitmap left/top/right/bottom), in GUI pixels. #[derive(Clone, Copy, Debug)] @@ -24,7 +32,7 @@ pub struct Glyph { pub right: f32, pub bottom: f32, pub advance: f32, - /// Shadow and bold offset (1 for bitmap glyphs, 0.5 for unihex). + /// Shadow and bold offset (1 for bitmap and TrueType glyphs, 0.5 for unihex). pub offset: f32, } /// Pixels to copy into the shared atlas before the next HUD draw. @@ -43,19 +51,77 @@ struct HexGlyph { left: u32, right: u32, } -#[derive(Default)] -struct HexProvider { - glyphs: HashMap, +/// A provider's `filter` (`FontOption.Filter`): the options it needs. +#[derive(Clone, Copy, Default)] +struct Filter { + uniform: Option, + jp: Option, +} +impl Filter { + fn of(provider: &serde_json::Value) -> Self { + let f = &provider["filter"]; + Self { + uniform: f["uniform"].as_bool(), + jp: f["jp"].as_bool(), + } + } + fn passes(self, uniform: bool, japanese: bool) -> bool { + self.uniform.is_none_or(|v| v == uniform) && self.jp.is_none_or(|v| v == japanese) + } +} +/// A bitmap glyph whose sheet is not in the atlas: the cell to copy. +struct SheetCell { + sheet: Arc<(u32, Vec)>, + x: u32, + y: u32, + w: u32, + h: u32, + glyph: Glyph, +} +enum BitmapGlyph { + Atlas(Glyph), + Sheet(SheetCell), +} +/// `TrueTypeGlyphProvider`. +struct TrueType { + font: ab_glyph::FontVec, + ids: HashMap, + /// FT_Set_Pixel_Sizes: `size * oversample` pixels to the em. + scale: ab_glyph::PxScale, + oversample: f32, + /// FT_Set_Transform's delta, in oversampled pixels (y down). + shift: (f32, f32), +} +enum Provider { + Space(HashMap), + Bitmap(Filter, HashMap), + /// The definition, and its glyphs once read. + Unihex(Filter, serde_json::Value, Option>), + TrueType(Filter, Box), +} +/// One font (`FontSet`): its providers and the glyphs resolved so far. +struct FontSet { + providers: Vec, + glyphs: HashMap, + /// `glyphsByWidth` for obfuscated text (built on first use). + by_width: Option>>, +} +/// The atlas region glyphs are rasterized into, filled in rows. +struct Region { + cursor: (u32, u32), + row: u32, + pending: Vec, } struct Cache { - glyphs: HashMap, - cursor: (u32, u32), - pending: Vec, - hex: Option>, + /// Every font by id, the default one first (the common lookup). + sets: Vec<(String, FontSet)>, + region: Region, + /// `Font.random`: picks obfuscated glyphs. + random: horizon_core::random::LegacyRandom, } pub struct Font { - bitmap: HashMap, - space: HashMap, + /// The atlas rects of the sheets under `textures/font`. + sheets: HashMap, missing: Glyph, white: Rect, root: PathBuf, @@ -63,9 +129,9 @@ pub struct Font { atlas: (u32, u32), region: (u32, u32), cache: RefCell, - /// "Force Unicode Font": skip the bitmap providers (font/uniform.json). + /// "Force Unicode Font": the `uniform` filter option. pub uniform: bool, - /// "Japanese Glyph Variants": enable providers filtered on `jp`. + /// "Japanese Glyph Variants": the `jp` filter option. pub japanese: bool, } fn parse_hex_digit(b: u8) -> Option { @@ -174,9 +240,324 @@ fn glyph_rect(x: u32, y: u32, w: u32, h: u32, atlas: (u32, u32)) -> Rect { h, } } +/// The unscaled pixel width of a bitmap cell (`BitmapProvider.getActualGlyphWidth`). +fn used_width(pixels: &[u8], stride: u32, (cx, cy, cw, ch): (u32, u32, u32, u32)) -> u32 { + (0..cw) + .rev() + .find(|&x| { + (0..ch).any(|y| { + pixels + .get((((cy + y) * stride + cx + x) * 4 + 3) as usize) + .is_some_and(|a| *a != 0) + }) + }) + .map_or(0, |x| x + 1) +} +/// `BitmapProvider.Definition.load`: each character's glyph, from the atlas +/// when the sheet is in it (`pixels` its RGBA), else from the sheet's own +/// pixels, copied into the atlas when first drawn. +fn load_bitmap( + root: &Path, + p: &serde_json::Value, + sheets: &HashMap, + pixels: &[u8], + atlas: (u32, u32), +) -> HashMap { + let mut out = HashMap::new(); + let file = p["file"].as_str().unwrap_or(""); + let (ns, name) = file.split_once(':').unwrap_or(("minecraft", file)); + let in_atlas = (ns == "minecraft") + .then(|| sheets.get(name.trim_end_matches(".png")).copied()) + .flatten(); + // The sheet: its size, and its pixels when they are not in the atlas. + let (sw, sh, sheet) = match in_atlas { + Some(rect) => (rect.w, rect.h, None), + None => match crate::hud::decode(&root.join(resource_path(file, "textures", ""))) { + Ok((w, h, rgba)) => (w, h, Some(Arc::new((w, rgba)))), + Err(_) => { + log::warn!("font sheet {file} could not be read"); + return out; + } + }, + }; + let rows: Vec> = p["chars"] + .as_array() + .into_iter() + .flatten() + .filter_map(|r| r.as_str().map(|s| s.chars().collect())) + .collect(); + if rows.is_empty() || rows[0].is_empty() { + return out; + } + let cell_w = sw / rows[0].len() as u32; + let cell_h = sh / rows.len() as u32; + let height = p["height"].as_f64().unwrap_or(8.0) as f32; + let ascent = p["ascent"].as_f64().unwrap_or(7.0) as f32; + let scale = height / cell_h as f32; + let origin = in_atlas.map_or((0, 0), |rect| { + ( + (rect.u0 * atlas.0 as f32).round() as u32, + (rect.v0 * atlas.1 as f32).round() as u32, + ) + }); + for (r, row) in rows.iter().enumerate() { + for (c, ch) in row.iter().enumerate() { + if *ch == '\0' || out.contains_key(ch) { + continue; + } + let (x, y) = (c as u32 * cell_w, r as u32 * cell_h); + let used = match &sheet { + Some(s) => used_width(&s.1, s.0, (x, y, cell_w, cell_h)), + None => used_width( + pixels, + atlas.0, + (origin.0 + x, origin.1 + y, cell_w, cell_h), + ), + }; + let top = 7.0 - ascent; + let glyph = Glyph { + rect: None, + left: 0.0, + top, + right: cell_w as f32 * scale, + bottom: top + cell_h as f32 * scale, + advance: (0.5 + used as f32 * scale).floor() + 1.0, + offset: 1.0, + }; + let glyph = match &sheet { + None => BitmapGlyph::Atlas(Glyph { + rect: Some(glyph_rect( + origin.0 + x, + origin.1 + y, + cell_w, + cell_h, + atlas, + )), + ..glyph + }), + Some(s) => BitmapGlyph::Sheet(SheetCell { + sheet: s.clone(), + x, + y, + w: cell_w, + h: cell_h, + glyph, + }), + }; + out.insert(*ch, glyph); + } + } + out +} +/// `TrueTypeGlyphProviderDefinition.load`: a TrueType file (not CFF) under +/// `font/`, its Unicode characters but the `skip` ones. +fn load_true_type(root: &Path, p: &serde_json::Value) -> Option { + let file = p["file"].as_str()?; + let data = std::fs::read(root.join(resource_path(file, "font", ""))) + .map_err(|e| log::warn!("font file {file}: {e}")) + .ok()?; + // FT_Get_Font_Format must say TrueType: CFF outlines ("OTTO") are refused. + if data.starts_with(b"OTTO") { + log::warn!("font file {file} is not in TTF format"); + return None; + } + let font = ab_glyph::FontVec::try_from_vec(data) + .map_err(|e| log::warn!("font file {file}: {e}")) + .ok()?; + let size = p["size"].as_f64().unwrap_or(11.0) as f32; + let oversample = p["oversample"].as_f64().unwrap_or(1.0) as f32; + let shift = p["shift"].as_array().map_or((0.0, 0.0), |s| { + let f = |i: usize| s.get(i).and_then(|v| v.as_f64()).unwrap_or(0.0) as f32; + (f(0), f(1)) + }); + let skip: Vec = match &p["skip"] { + serde_json::Value::String(s) => s.chars().collect(), + serde_json::Value::Array(a) => a + .iter() + .filter_map(|v| v.as_str()) + .flat_map(str::chars) + .collect(), + _ => Vec::new(), + }; + let ids = font + .codepoint_ids() + .filter(|(id, c)| id.0 != 0 && !skip.contains(c)) + .map(|(id, c)| (c, id)) + .collect(); + let pixels_per_em = (size * oversample).round(); + // ab_glyph scales by the font's height; FreeType by its em. + let units = font.units_per_em().unwrap_or(1000.0); + let scale = ab_glyph::PxScale::from(pixels_per_em * font.height_unscaled() / units); + Some(TrueType { + font, + ids, + scale, + oversample, + shift: (shift.0 * oversample, shift.1 * oversample), + }) +} +impl TrueType { + /// The advance in GUI pixels: hinted FreeType advances are whole + /// oversampled pixels. + fn advance(&self, id: ab_glyph::GlyphId) -> f32 { + self.font.as_scaled(self.scale).h_advance(id).round() / self.oversample + } + /// `loadGlyph` and its bitmap: the grey coverage as `rrrr` texels + /// (`text_intensity`), below 0.1 cut (its discard). + fn glyph(&self, id: ab_glyph::GlyphId) -> (Glyph, Option<(u32, u32, Vec)>) { + let advance = self.advance(id); + let glyph = + id.with_scale_and_position(self.scale, ab_glyph::point(self.shift.0, self.shift.1)); + let empty = Glyph { + rect: None, + left: 0.0, + top: 0.0, + right: 0.0, + bottom: 0.0, + advance, + offset: 1.0, + }; + let Some(outline) = self.font.outline_glyph(glyph) else { + return (empty, None); + }; + let bounds = outline.px_bounds(); + let (w, h) = (bounds.width() as u32, bounds.height() as u32); + if w == 0 || h == 0 { + return (empty, None); + } + let mut rgba = vec![0u8; (w * h * 4) as usize]; + outline.draw(|x, y, coverage| { + let v = if coverage < 0.1 { + 0 + } else { + (coverage.min(1.0) * 255.0).round() as u8 + }; + let i = ((y * w + x) * 4) as usize; + if let Some(px) = rgba.get_mut(i..i + 4) { + px.copy_from_slice(&[v; 4]); + } + }); + let os = self.oversample; + // GlyphBitmap: bitmap_left / bitmap_top over the oversampling, and + // top = 7 - bearingTop. + let (left, top) = (bounds.min.x / os, 7.0 + bounds.min.y / os); + ( + Glyph { + rect: None, + left, + top, + right: left + w as f32 / os, + bottom: top + h as f32 / os, + advance, + offset: 1.0, + }, + Some((w, h, rgba)), + ) + } +} +fn load_hex(root: &Path, p: &serde_json::Value) -> HashMap { + let mut glyphs = HashMap::new(); + let Some(file) = p["hex_file"].as_str() else { + return glyphs; + }; + let path = root.join(resource_path(file, "", "").replace("//", "/")); + let Ok(zip) = Zip::open(&path) else { + return glyphs; + }; + let names: Vec = zip + .names() + .filter(|n| n.ends_with(".hex")) + .map(str::to_owned) + .collect(); + for name in names { + if let Ok(bytes) = zip.read(&name) { + parse_hex(&bytes, &mut glyphs); + } + } + for o in p["size_overrides"].as_array().into_iter().flatten() { + let bound = |k: &str| { + o[k].as_str() + .and_then(|s| s.chars().next()) + .map_or(0, u32::from) + }; + let (left, right) = ( + o["left"].as_u64().unwrap_or(0) as u32, + o["right"].as_u64().unwrap_or(15) as u32, + ); + for c in bound("from")..=bound("to") { + if let Some(g) = glyphs.get_mut(&c) { + g.left = left; + g.right = right; + } + } + } + glyphs +} +/// The ids of every font definition (`font/**/*.json` of each namespace). +fn font_ids(root: &Path) -> Vec { + fn walk(dir: &Path, prefix: &str, out: &mut Vec) { + for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() { + let path = entry.path(); + let name = entry.file_name().to_string_lossy().into_owned(); + if path.is_dir() { + walk(&path, &format!("{prefix}{name}/"), out); + } else if let Some(stem) = name.strip_suffix(".json") { + out.push(format!("{prefix}{stem}")); + } + } + } + let mut ids = Vec::new(); + for ns in std::fs::read_dir(root.join("assets")) + .into_iter() + .flatten() + .flatten() + { + let ns = ns.file_name().to_string_lossy().into_owned(); + walk( + &root.join("assets").join(&ns).join("font"), + &format!("{ns}:"), + &mut ids, + ); + } + ids.sort(); + ids +} +impl Region { + /// Place `w x h` pixels in the region (rows left to right); their atlas + /// position, or none when it is full. + fn place( + &mut self, + w: u32, + h: u32, + rgba: Vec, + atlas: (u32, u32), + region: (u32, u32), + ) -> Option<(u32, u32)> { + let (mut x, mut y) = self.cursor; + if x + w + 1 > atlas.0 { + x = 0; + y += self.row + 1; + self.row = 0; + } + if y + h > region.1 { + return None; + } + let (ax, ay) = (x, region.0 + y); + self.pending.push(Patch { + x: ax, + y: ay, + width: w, + height: h, + rgba, + }); + self.cursor = (x + w + 1, y); + self.row = self.row.max(h); + Some((ax, ay)) + } +} impl Font { - /// Build from the atlas holding the bitmap font sheets. `pixels` is the - /// RGBA atlas (for glyph widths) and `region` the reserved rows. + /// Build from the atlas holding the bitmap font sheets (`sprites`, of + /// `atlas` size) with `region` the reserved rows. pub fn load( root: &Path, sprites: &HashMap, @@ -185,222 +566,196 @@ impl Font { region: (u32, u32), white: Rect, ) -> Self { - let mut bitmap = HashMap::new(); - let mut space = HashMap::new(); - let mut all = Vec::new(); - providers(root, "minecraft:default", 0, &mut all); - for provider in &all { - match provider["type"].as_str() { - Some("space") => { - for (k, v) in provider["advances"].as_object().into_iter().flatten() { - if let (Some(c), Some(a)) = (k.chars().next(), v.as_f64()) { - space.entry(c).or_insert(a as f32); - } - } - } - Some("bitmap") => { - // Only non-uniform bitmap sheets exist in the default font. - let file = provider["file"].as_str().unwrap_or(""); - let name = file - .trim_start_matches("minecraft:") - .trim_end_matches(".png"); - let name = name.to_string(); - let Some(rect) = sprites.get(&name).copied() else { - continue; - }; - let rows: Vec> = provider["chars"] - .as_array() - .into_iter() - .flatten() - .filter_map(|r| r.as_str().map(|s| s.chars().collect())) - .collect(); - if rows.is_empty() || rows[0].is_empty() { - continue; - } - let cell_w = rect.w / rows[0].len() as u32; - let cell_h = rect.h / rows.len() as u32; - let height = provider["height"].as_f64().unwrap_or(8.0) as f32; - let ascent = provider["ascent"].as_f64().unwrap_or(7.0) as f32; - let scale = height / cell_h as f32; - let (ax, ay) = ( - (rect.u0 * atlas.0 as f32).round() as u32, - (rect.v0 * atlas.1 as f32).round() as u32, - ); - for (r, row) in rows.iter().enumerate() { - for (c, ch) in row.iter().enumerate() { - if *ch == '\0' || bitmap.contains_key(ch) { - continue; - } - let (cx, cy) = (ax + c as u32 * cell_w, ay + r as u32 * cell_h); - // BitmapProvider.getActualGlyphWidth. - let mut used = 0; - for x in (0..cell_w).rev() { - if (0..cell_h).any(|y| { - pixels - .get((((cy + y) * atlas.0 + cx + x) * 4 + 3) as usize) - .is_some_and(|a| *a != 0) - }) { - used = x + 1; - break; - } - } - let top = 7.0 - ascent; - bitmap.insert( - *ch, - Glyph { - rect: Some(glyph_rect(cx, cy, cell_w, cell_h, atlas)), - left: 0.0, - top, - right: cell_w as f32 * scale, - bottom: top + cell_h as f32 * scale, - advance: (0.5 + used as f32 * scale).floor() + 1.0, - offset: 1.0, - }, - ); - } - } - } - _ => {} - } - } - let missing = Glyph { - rect: None, - left: 0.0, - top: 0.0, - right: 5.0, - bottom: 8.0, - advance: 6.0, - offset: 1.0, - }; - Self { - bitmap, - space, - missing, + let sheets = sprites + .iter() + .filter(|(k, _)| k.starts_with("font/")) + .map(|(k, v)| (k.clone(), *v)) + .collect(); + let font = Self { + sheets, + missing: Glyph { + rect: None, + left: 0.0, + top: 0.0, + right: 5.0, + bottom: 8.0, + advance: 6.0, + offset: 1.0, + }, white, root: root.to_owned(), atlas, region, cache: RefCell::new(Cache { - glyphs: HashMap::new(), - cursor: (0, 0), - pending: Vec::new(), - hex: None, + sets: Vec::new(), + region: Region { + cursor: (0, 0), + row: 0, + pending: Vec::new(), + }, + random: horizon_core::random::LegacyRandom::new( + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos() as i64), + ), }), uniform: false, japanese: false, - } + }; + // FontManager.prepare: every font definition of the resources. + let mut ids = font_ids(root); + ids.sort_by_key(|id| id != DEFAULT); + let sets = ids + .into_iter() + .map(|id| { + let set = font.load_set(&id, pixels); + (id, set) + }) + .collect(); + font.cache.borrow_mut().sets = sets; + font } - fn load_hex(&self) -> Vec { + /// `FontManager`: a font's providers with references expanded. + fn load_set(&self, id: &str, pixels: &[u8]) -> FontSet { let mut all = Vec::new(); - providers(&self.root, "minecraft:default", 0, &mut all); - let mut out = Vec::new(); - for p in all.iter().filter(|p| p["type"] == "unihex") { - if let Some(filter) = p["filter"].as_object() { - let pass = filter.iter().all(|(k, v)| match k.as_str() { - "jp" => v.as_bool() == Some(self.japanese), - "uniform" => v.as_bool() == Some(self.uniform), - _ => true, - }); - if !pass { - continue; - } - } - let Some(file) = p["hex_file"].as_str() else { - continue; - }; - let path = self - .root - .join(resource_path(file, "", "").replace("//", "/")); - let Ok(zip) = Zip::open(&path) else { continue }; - let mut provider = HexProvider::default(); - let names: Vec = zip - .names() - .filter(|n| n.ends_with(".hex")) - .map(str::to_owned) - .collect(); - for name in names { - if let Ok(bytes) = zip.read(&name) { - parse_hex(&bytes, &mut provider.glyphs); - } - } - for o in p["size_overrides"].as_array().into_iter().flatten() { - let from = o["from"] - .as_str() - .and_then(|s| s.chars().next()) - .map_or(0, u32::from); - let to = o["to"] - .as_str() - .and_then(|s| s.chars().next()) - .map_or(0, u32::from); - let (left, right) = ( - o["left"].as_u64().unwrap_or(0) as u32, - o["right"].as_u64().unwrap_or(15) as u32, - ); - for c in from..=to { - if let Some(g) = provider.glyphs.get_mut(&c) { - g.left = left; - g.right = right; - } - } - } - out.push(provider); + providers(&self.root, id, 0, &mut all); + let providers = all + .iter() + .filter_map(|p| match p["type"].as_str()? { + "space" => Some(Provider::Space( + p["advances"] + .as_object() + .into_iter() + .flatten() + .filter_map(|(k, v)| Some((k.chars().next()?, v.as_f64()? as f32))) + .collect(), + )), + "bitmap" => Some(Provider::Bitmap( + Filter::of(p), + load_bitmap(&self.root, p, &self.sheets, pixels, self.atlas), + )), + "unihex" => Some(Provider::Unihex(Filter::of(p), p.clone(), None)), + "ttf" => Some(Provider::TrueType( + Filter::of(p), + Box::new(load_true_type(&self.root, p)?), + )), + _ => None, + }) + .collect(); + FontSet { + providers, + glyphs: HashMap::new(), + by_width: None, } - out } - /// Forget rasterized fallback glyphs (after changing font options). + /// Forget rasterized glyphs (after changing font options). pub fn reset_cache(&self) { let mut cache = self.cache.borrow_mut(); - cache.glyphs.clear(); - cache.cursor = (0, 0); - cache.hex = None; + for (_, set) in &mut cache.sets { + set.glyphs.clear(); + set.by_width = None; + } + cache.region.cursor = (0, 0); + cache.region.row = 0; } - /// The glyph for a character (FontSet.getGlyph). + /// The glyph for a character in the default font (FontSet.getGlyph). pub fn glyph(&self, c: char) -> Glyph { - if let Some(a) = self.space.get(&c) { - return Glyph { - rect: None, - left: 0.0, - top: 0.0, - right: 0.0, - bottom: 0.0, - advance: *a, - offset: 1.0, - }; - } - if !self.uniform - && let Some(g) = self.bitmap.get(&c) - { - return *g; - } - if let Some(g) = self.cache.borrow().glyphs.get(&c) { - return *g; + self.glyph_of(DEFAULT, c) + } + /// The glyph for a character drawn in `style`'s font (its id is + /// already complete, see `text::font_id`). + pub fn glyph_styled(&self, c: char, style: &Style) -> Glyph { + self.glyph_of(style.font.as_deref().unwrap_or(DEFAULT), c) + } + /// The glyph for a character in the font `id` (`alt` is `minecraft:alt`). + pub fn glyph_in(&self, id: &str, c: char) -> Glyph { + if id.contains(':') { + self.glyph_of(id, c) + } else { + self.glyph_of(&format!("minecraft:{id}"), c) } + } + /// The first active provider's glyph, else the missing glyph. + fn glyph_of(&self, id: &str, c: char) -> Glyph { let mut cache = self.cache.borrow_mut(); - if cache.hex.is_none() { - cache.hex = Some(self.load_hex()); - } - let hex = cache.hex.as_ref().and_then(|providers| { - providers - .iter() - .find_map(|p| p.glyphs.get(&u32::from(c)).copied()) - }); - let glyph = match hex { - Some(h) => self.rasterize(&mut cache, h).unwrap_or(self.missing), - None => self.missing, + let Cache { sets, region, .. } = &mut *cache; + // FontManager.getFontSetRaw: a font that doesn't exist draws every + // character as the missing glyph. + let Some((_, set)) = sets.iter_mut().find(|(k, _)| k == id) else { + return self.missing; }; - cache.glyphs.insert(c, glyph); + if let Some(g) = set.glyphs.get(&c) { + return *g; + } + let glyph = self.resolve(set, region, c).unwrap_or(self.missing); + set.glyphs.insert(c, glyph); glyph } - fn rasterize(&self, cache: &mut Cache, h: HexGlyph) -> Option { + fn resolve(&self, set: &mut FontSet, region: &mut Region, c: char) -> Option { + let (uniform, japanese) = (self.uniform, self.japanese); + for provider in &mut set.providers { + match provider { + Provider::Space(advances) => { + if let Some(a) = advances.get(&c) { + return Some(Glyph { + rect: None, + left: 0.0, + top: 0.0, + right: 0.0, + bottom: 0.0, + advance: *a, + offset: 1.0, + }); + } + } + Provider::Bitmap(filter, glyphs) if filter.passes(uniform, japanese) => { + match glyphs.get(&c) { + Some(BitmapGlyph::Atlas(g)) => return Some(*g), + Some(BitmapGlyph::Sheet(cell)) => { + let (stride, pixels) = (&cell.sheet.0, &cell.sheet.1); + let mut rgba = Vec::with_capacity((cell.w * cell.h * 4) as usize); + for y in cell.y..cell.y + cell.h { + let at = ((y * stride + cell.x) * 4) as usize; + rgba.extend_from_slice(&pixels[at..at + (cell.w * 4) as usize]); + } + let (x, y) = + region.place(cell.w, cell.h, rgba, self.atlas, self.region)?; + return Some(Glyph { + rect: Some(glyph_rect(x, y, cell.w, cell.h, self.atlas)), + ..cell.glyph + }); + } + None => {} + } + } + Provider::Unihex(filter, def, glyphs) if filter.passes(uniform, japanese) => { + let glyphs = glyphs.get_or_insert_with(|| load_hex(&self.root, def)); + if let Some(h) = glyphs.get(&u32::from(c)).copied() { + return self.rasterize_hex(region, h); + } + } + Provider::TrueType(filter, ttf) if filter.passes(uniform, japanese) => { + if let Some(id) = ttf.ids.get(&c) { + let (glyph, bitmap) = ttf.glyph(*id); + return match bitmap { + Some((w, h, rgba)) => { + let (x, y) = region.place(w, h, rgba, self.atlas, self.region)?; + Some(Glyph { + rect: Some(glyph_rect(x, y, w, h, self.atlas)), + ..glyph + }) + } + None => Some(glyph), + }; + } + } + _ => {} + } + } + None + } + fn rasterize_hex(&self, region: &mut Region, h: HexGlyph) -> Option { let width = h.right.saturating_sub(h.left) + 1; - let (mut x, mut y) = cache.cursor; - if x + width + 1 > self.atlas.0 { - x = 0; - y += 17; - } - if y + 16 > self.region.1 { - return None; - } let mut rgba = Vec::with_capacity((width * 16 * 4) as usize); for row in h.rows { for bit in h.left..=h.right { @@ -408,17 +763,9 @@ impl Font { rgba.extend(if set { [255; 4] } else { [0; 4] }); } } - let (ax, ay) = (x, self.region.0 + y); - cache.pending.push(Patch { - x: ax, - y: ay, - width, - height: 16, - rgba, - }); - cache.cursor = (x + width + 1, y); + let (x, y) = region.place(width, 16, rgba, self.atlas, self.region)?; Some(Glyph { - rect: Some(glyph_rect(ax, ay, width, 16, self.atlas)), + rect: Some(glyph_rect(x, y, width, 16, self.atlas)), left: 0.0, top: 0.0, right: width as f32 / 2.0, @@ -427,12 +774,110 @@ impl Font { offset: 0.5, }) } + /// `FontSet.getRandomGlyph`: what an obfuscated character draws, a random + /// glyph of the font as wide as `advance` (rounded up), else the missing + /// glyph. + /// + /// Vanilla picks among every glyph of the font set, Unifont's included. + /// Those are rasterized into a fixed atlas region on demand, which a + /// line of obfuscated text would fill in seconds, so the candidates are + /// the glyphs already in the atlas (the bitmap sheets there and spaces), + /// or for a font without any (Force Unicode Font, a TrueType font) its + /// glyphs below U+0250. + pub fn random_glyph(&self, style: &Style, advance: f32) -> Glyph { + use horizon_core::random::RandomSource; + let id = style.font.as_deref().unwrap_or(DEFAULT); + let width = advance.ceil() as u32; + let pick = { + let mut cache = self.cache.borrow_mut(); + let Cache { sets, random, .. } = &mut *cache; + let Some((_, set)) = sets.iter_mut().find(|(k, _)| k == id) else { + return self.missing; + }; + if set.by_width.is_none() { + set.by_width = Some(self.glyphs_by_width(set)); + } + set.by_width + .as_ref() + .and_then(|m| m.get(&width)) + .and_then(|chars| { + let i = random.next_int_bound(chars.len() as i32).ok()?; + chars.get(i as usize).copied() + }) + }; + pick.map_or(self.missing, |c| self.glyph_of(id, c)) + } + fn glyphs_by_width(&self, set: &mut FontSet) -> HashMap> { + let (uniform, japanese) = (self.uniform, self.japanese); + let mut chars = std::collections::BTreeSet::new(); + let mut in_atlas = false; + for provider in &set.providers { + match provider { + Provider::Space(advances) => chars.extend(advances.keys().copied()), + Provider::Bitmap(filter, glyphs) if filter.passes(uniform, japanese) => { + for (c, g) in glyphs { + if matches!(g, BitmapGlyph::Atlas(_)) { + in_atlas = true; + chars.insert(*c); + } + } + } + _ => {} + } + } + if !in_atlas { + // Nothing in the atlas: the glyphs below U+0250, rasterized as used. + chars.extend((0..0x250u32).filter_map(char::from_u32)); + } + let mut out: HashMap> = HashMap::new(); + for c in chars { + if let Some(advance) = self.provider_advance(set, c) { + out.entry(advance.ceil() as u32).or_default().push(c); + } + } + out + } + /// A character's advance in `set` (its first provider that has it), + /// without rasterizing it. + fn provider_advance(&self, set: &mut FontSet, c: char) -> Option { + let (uniform, japanese) = (self.uniform, self.japanese); + for provider in &mut set.providers { + match provider { + Provider::Space(advances) => { + if let Some(a) = advances.get(&c) { + return Some(*a); + } + } + Provider::Bitmap(filter, glyphs) if filter.passes(uniform, japanese) => { + match glyphs.get(&c) { + Some(BitmapGlyph::Atlas(g)) => return Some(g.advance), + Some(BitmapGlyph::Sheet(cell)) => return Some(cell.glyph.advance), + None => {} + } + } + Provider::Unihex(filter, def, glyphs) if filter.passes(uniform, japanese) => { + let glyphs = glyphs.get_or_insert_with(|| load_hex(&self.root, def)); + if let Some(h) = glyphs.get(&u32::from(c)) { + let width = h.right.saturating_sub(h.left) + 1; + return Some((width / 2 + 1) as f32); + } + } + Provider::TrueType(filter, ttf) if filter.passes(uniform, japanese) => { + if let Some(id) = ttf.ids.get(&c) { + return Some(ttf.advance(*id)); + } + } + _ => {} + } + } + None + } /// Atlas pixels rasterized since the last call. pub fn take_patches(&self) -> Vec { - std::mem::take(&mut self.cache.borrow_mut().pending) + std::mem::take(&mut self.cache.borrow_mut().region.pending) } pub fn advance(&self, c: char, style: &Style) -> f32 { - let g = self.glyph(c); + let g = self.glyph_styled(c, style); g.advance + if style.is_bold() { g.offset } else { 0.0 } } /// Font.width of plain text (legacy codes are formatting, not glyphs). @@ -618,4 +1063,155 @@ mod tests { assert_eq!(r.v1, ((y + h) as f32 - 0.01) / 4096.0); } } + + /// A resource root with these font definitions and files. + fn root(name: &str, files: &[(&str, &[u8])]) -> PathBuf { + let root = std::env::temp_dir().join(format!("horizon-font-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + for (path, bytes) in files { + let path = root.join(path); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, bytes).unwrap(); + } + root + } + fn white() -> Rect { + Rect { + u0: 0.0, + v0: 0.0, + u1: 0.0, + v1: 0.0, + w: 1, + h: 1, + } + } + fn load(root: &Path) -> Font { + Font::load( + root, + &HashMap::new(), + &[], + (4096, 1024), + (512, 512), + white(), + ) + } + fn png(width: u32, height: u32, opaque: impl Fn(u32, u32) -> bool) -> Vec { + let mut pixels = Vec::new(); + for y in 0..height { + for x in 0..width { + pixels.extend(if opaque(x, y) { [255; 4] } else { [0; 4] }); + } + } + let mut out = Vec::new(); + let mut encoder = png::Encoder::new(&mut out, width, height); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + encoder + .write_header() + .unwrap() + .write_image_data(&pixels) + .unwrap(); + out + } + + #[test] + fn true_type_glyphs_are_rasterized_at_the_provider_size() { + let def = br#"{"providers":[{"type":"ttf","file":"minecraft:mono.ttf","size":11,"oversample":2,"shift":[0.5,1],"skip":["B"]}]}"#; + let root = root( + "ttf", + &[ + ("assets/minecraft/font/default.json", def), + ( + "assets/minecraft/font/mono.ttf", + horizon_theme::fonts::GEIST_MONO, + ), + ], + ); + let font = load(&root); + let _ = std::fs::remove_dir_all(&root); + let a = font.glyph('A'); + let rect = a.rect.expect("A is drawn"); + // Oversampled 2x: the bitmap is twice the glyph's GUI size. + assert_eq!(rect.w as f32 / 2.0, a.right - a.left); + assert_eq!(rect.h as f32 / 2.0, a.bottom - a.top); + // A monospaced font: every advance is the same, in half pixels. + assert_eq!(a.advance, font.glyph('i').advance); + assert_eq!((a.advance * 2.0).fract(), 0.0); + assert!(a.advance > 4.0 && a.advance < 9.0, "{}", a.advance); + // Capitals sit on the baseline at y = 7, shifted down a pixel. + assert!((a.bottom - 8.0).abs() <= 0.5, "{}", a.bottom); + assert_eq!(a.offset, 1.0); + // The space has an advance and nothing to draw. + let space = font.glyph(' '); + assert!(space.rect.is_none() && space.advance > 0.0); + // Skipped characters fall through to the missing glyph. + assert_eq!(font.glyph('B').advance, 6.0); + // Coverage as `rrrr` texels, faint coverage cut. + let patches = font.take_patches(); + assert_eq!(patches.len(), 2); + let texels: Vec<&[u8]> = patches.iter().flat_map(|p| p.rgba.chunks(4)).collect(); + assert!(texels.iter().all(|t| t.iter().all(|v| *v == t[0]))); + assert!(texels.iter().all(|t| t[0] == 0 || t[0] >= 25)); + assert!(texels.iter().any(|t| t[0] == 255)); + } + + #[test] + fn styles_pick_their_font_and_unknown_fonts_draw_missing_glyphs() { + let sheet = png(16, 8, |x, _| x < 2 || (8..14).contains(&x)); + let default = br#"{"providers":[{"type":"space","advances":{" ":4}},{"type":"bitmap","file":"minecraft:font/a.png","ascent":7,"chars":["ab"]}]}"#; + let alt = br#"{"providers":[{"type":"bitmap","file":"minecraft:font/a.png","ascent":7,"chars":["ba"]}]}"#; + let root = root( + "styles", + &[ + ("assets/minecraft/font/default.json", default), + ("assets/minecraft/font/alt.json", alt), + ("assets/minecraft/textures/font/a.png", &sheet), + ], + ); + let font = load(&root); + let _ = std::fs::remove_dir_all(&root); + // The sheet is not in this atlas: glyphs are copied in when first drawn. + assert_eq!(font.glyph('a').advance, 3.0); + assert_eq!(font.glyph('b').advance, 7.0); + let alt = Style { + font: Some("minecraft:alt".into()), + ..Style::default() + }; + assert_eq!(font.glyph_styled('a', &alt).advance, 7.0); + assert_eq!(font.glyph_in("alt", 'b').advance, 3.0); + assert!(font.glyph_styled('a', &alt).rect.is_some()); + // Not in alt (no space provider there), or no such font at all. + assert_eq!(font.glyph_styled(' ', &alt).advance, 6.0); + let missing = Style { + font: Some("minecraft:nope".into()), + ..Style::default() + }; + assert_eq!(font.glyph_styled(' ', &missing).advance, 6.0); + assert_eq!(font.advance('a', &alt), 7.0); + let text = Text::literal("ab").with_style(&alt); + assert_eq!(font.width_text(&text), 10.0); + assert_eq!(font.random_glyph(&alt, 7.0).advance, 7.0); + assert!(!font.take_patches().is_empty()); + } + + #[test] + fn provider_filters_follow_the_font_options() { + let sheet = png(8, 8, |x, _| x < 4); + let default = br#"{"providers":[{"type":"reference","id":"minecraft:include/sheet","filter":{"uniform":false}},{"type":"space","advances":{"a":2}}]}"#; + let sheet_def = br#"{"providers":[{"type":"bitmap","file":"minecraft:font/s.png","ascent":7,"chars":["a"]}]}"#; + let root = root( + "filters", + &[ + ("assets/minecraft/font/default.json", default), + ("assets/minecraft/font/include/sheet.json", sheet_def), + ("assets/minecraft/textures/font/s.png", &sheet), + ], + ); + let mut font = load(&root); + let _ = std::fs::remove_dir_all(&root); + assert_eq!(font.glyph('a').advance, 5.0); + font.uniform = true; + font.reset_cache(); + assert_eq!(font.glyph('a').advance, 2.0); + } } diff --git a/crates/horizon-client/src/friends_screen.rs b/crates/horizon-client/src/friends_screen.rs new file mode 100644 index 000000000..7577e2add --- /dev/null +++ b/crates/horizon-client/src/friends_screen.rs @@ -0,0 +1,303 @@ +//! Play with Friends: Horizon's own sharing of the open world behind an +//! invite code (`game/friends.rs`). The pause menu's Friends button, the icon +//! vanilla's PauseScreen already has, opens it. It is drawn the way a mod adds +//! a screen to vanilla: the menu background, a centred title and text, +//! vanilla's buttons and Done in the footer. +use crate::{ + hud::{HudAtlas, HudBatch, rgba}, + multiplayer::wrap, + text::Text, + ui, +}; + +pub const TITLE: &str = "Play with Friends"; +/// What the screen shows (game/friends.rs fills it). +#[derive(Clone, Debug, Default)] +pub struct FriendsView { + /// A singleplayer world (not a server): sharing is offered. + pub shown: bool, + pub sharing: bool, + pub code: Option, + /// Who can join and what to do when friends on the internet can't (or, + /// before the code, what the game is doing). + pub status: String, + /// Friends on the internet can reach the host. + pub reachable: bool, + /// Where the troubleshooting is, when they can't. + pub help: Option, + /// The players in the world besides the host. + pub guests: Vec, + pub notice: Option, + /// The code was just copied. + pub copied: bool, +} + +/// A button's action. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Action { + Share, + Copy, + Stop, + /// Open the troubleshooting page. + Help, + Done, +} + +fn grey() -> u32 { + rgba(160, 160, 160, 255) +} +const WHITE: u32 = u32::MAX; +const HINT: &str = "Friends paste the code after the title screen's Friends button, in Direct Connection, or on the launcher's Play page."; + +struct Button { + x: f32, + y: f32, + w: f32, + label: &'static str, + action: Action, + active: bool, +} + +/// The centred lines (text, colour, y) and the buttons. +fn layout( + atlas: &HudAtlas, + (w, h): (f32, f32), + view: &FriendsView, +) -> (Vec<(String, u32, f32)>, Vec - - -
The launcher's Play page: the version, Client and Server, the version picker and Play, the prepared resources and the Minecraft folder as a numbered list
-
Horizon's title screen: the mark and the pages on the left, the Horizon title, Singleplayer and Multiplayer, the last world played and the faint wordmark, over a veiled snowy landscape
-
The Singleplayer page: the worlds as a numbered list with their dates and game modes, and Create world and Play
-
The Video settings in their Simple view: a preset, render distance, field of view, framerate, VSync and GUI scale, each with what it costs
-
The pause screen of a world, with Back to game, Open to LAN and Save and quit
+
Vanilla's Video Settings screen with Horizon's own buttons at the top: Horizon Graphics, Advanced Graphics and Shader Packs
-

The launcher, and Horizon's own menus in the game. The launcher opens them, or vanilla's.

+

The launcher, and Horizon's graphics settings in the game: vanilla's menus, with Horizon's pages added the way mods add theirs.

-
+
-

05Patch notes

-

What changed

+

05Releases

+

Recently added

+

New versions come out many times a day, as changes land, and the launcher installs each one once it has passed its test. The newest, and what they added:

-
- {{NOTES}} +
+ {{RECENT}}
@@ -236,7 +238,7 @@ diff --git a/website/src/main.js b/website/src/main.js index e61453730..7a0714d1b 100644 --- a/website/src/main.js +++ b/website/src/main.js @@ -1,10 +1,12 @@ // The page's behaviour: the download buttons for this platform, the latest releases, the -// links and contributors, the navigation, the menus' tabs, the lightbox and the motion. +// links and contributors, how many play now, the navigation, the menus' tabs, the lightbox +// and the motion. // Everything degrades to the baked-in content when GitHub can't be reached. import { escape } from "./markdown.js"; -import { releasesHtml } from "./releases.js"; +import { recentHtml } from "./releases.js"; import { contributorsFrom, contributorsHtml } from "./contributors.js"; import { isGame, isLauncher as isLauncherTag, launcherVersion, newestFirst } from "./versions.js"; +import { cached, get, setUpMenu, setUpTheme, slim } from "./chrome.js"; const REPO = "ludovic111/horizon"; const RELEASES_PAGE = `https://github.com/${REPO}/releases?q=launcher&expanded=true`; @@ -13,38 +15,11 @@ const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)").matches; // --- GitHub -------------------------------------------------------------------------- -async function cached(key, load) { - try { - const hit = JSON.parse(sessionStorage.getItem(key) || "null"); - if (hit && Date.now() - hit.at < 10 * 60 * 1000) return hit.value; - } catch {} - const value = await load(); - try { - sessionStorage.setItem(key, JSON.stringify({ at: Date.now(), value })); - } catch {} - return value; -} - -async function get(url, as = "json") { - const res = await fetch(url, { headers: as === "json" ? { Accept: "application/vnd.github+json" } : {} }); - if (!res.ok) throw new Error(`${res.status}`); - return as === "json" ? res.json() : res.text(); -} - -const slim = (r) => ({ - tag_name: r.tag_name, - name: r.name, - published_at: r.published_at, - html_url: r.html_url, - prerelease: r.prerelease, - body: r.body || "", - assets: r.assets.map((a) => ({ name: a.name, browser_download_url: a.browser_download_url, size: a.size })), -}); const isLauncher = (r) => isLauncherTag(r.tag_name) && !r.prerelease; -// The newest 100 releases (GitHub's most per page). Game betas come out several times a day, so the stable game -// release and the newest launcher release can both be older than all of them. The stable game release is then -// GitHub's "latest" (betas and launcher releases are never marked latest); the launcher release is looked up by its +// The newest 100 releases (GitHub's most per page). The newest game release that is not a pre-release (the old +// Alpha channel's, docs/release-flow.md) and the newest launcher release can be older than all of them. The game +// release is then GitHub's "latest" (pre-releases and launcher releases never are); the launcher release is looked up by its // tag (the newest launcher@ tag with a published release, or launcher-v before 0.2: docs/versioning.md). async function loadReleases() { const list = (await get(`https://api.github.com/repos/${REPO}/releases?per_page=100`)).filter((r) => !r.draft).map(slim); @@ -106,11 +81,12 @@ async function setUpDownload() { document.querySelectorAll("[data-download-meta]").forEach((p) => (p.innerHTML = meta)); } -// --- Patch notes and the links from main --------------------------------- +// --- Recently added and the links from main --------------------------------- -async function setUpNotes() { - const list = (await releases).filter((r) => isGame(r.tag_name) && !r.prerelease).sort((a, b) => newestFirst(a.tag_name, b.tag_name)); - if (list.length) document.getElementById("releases").innerHTML = releasesHtml(list.slice(0, 3)); +// "Recently added": the newest game releases. +async function setUpRecent() { + const html = recentHtml((await releases).filter((r) => isGame(r.tag_name))); + if (html) document.getElementById("recent-releases").innerHTML = html; } async function setUpLinks() { @@ -128,6 +104,34 @@ async function setUpLinks() { }); } +// --- Playing now --------------------------------------------------------------------- + +const TELEMETRY = "https://telemetry.playhorizon.dev"; + +// How many play right now, from the games' anonymous "I'm playing" pings (Privacy explains them). The +// server rounds it and makes it again at most every 15 seconds; the row stays hidden while nobody plays +// or the server doesn't answer. +async function setUpLive() { + const row = document.querySelector("[data-live]"); + if (!row) return; + const update = async () => { + try { + const res = await fetch(`${TELEMETRY}/v1/live`, { signal: AbortSignal.timeout(3000) }); + if (!res.ok) throw new Error(String(res.status)); + const { playing } = await res.json(); + if (!Number.isInteger(playing) || playing < 1) throw new Error("nobody"); + row.querySelector("[data-live-count]").textContent = playing.toLocaleString("en"); + row.hidden = false; + // It shows up after the others came in, so it skips their entrance. + row.classList.add("is-visible"); + } catch { + row.hidden = true; + } + }; + await update(); + setInterval(() => document.visibilityState === "visible" && update(), 60_000); +} + // --- Navigation ---------------------------------------------------------------------- function setUpNav() { @@ -151,40 +155,6 @@ function setUpNav() { }; onScroll(update); update(); - - // The phone menu: a full-screen sheet; the page behind it is inert while it is open. - const button = document.querySelector(".menu-button"); - const menu = document.getElementById("menu"); - const main = document.getElementById("main"); - const label = button.querySelector(".menu-label"); - const items = [...menu.querySelectorAll("nav a")]; - items.forEach((a, i) => a.style.setProperty("transition-delay", `${60 + i * 35}ms`)); - let closing; - const setOpen = (open) => { - clearTimeout(closing); - button.setAttribute("aria-expanded", String(open)); - label.textContent = open ? "Close" : "Menu"; - bar.classList.toggle("is-menu", open); - main.inert = open; - document.body.style.overflow = open ? "hidden" : ""; - if (open) { - menu.hidden = false; - requestAnimationFrame(() => requestAnimationFrame(() => menu.classList.add("is-open"))); - items[0].focus({ preventScroll: true }); - } else { - menu.classList.remove("is-open"); - closing = setTimeout(() => (menu.hidden = true), reducedMotion ? 0 : 320); - } - }; - button.addEventListener("click", () => setOpen(button.getAttribute("aria-expanded") !== "true")); - items.forEach((a) => a.addEventListener("click", () => setOpen(false))); - addEventListener("keydown", (e) => { - if (e.key === "Escape" && button.getAttribute("aria-expanded") === "true") { - setOpen(false); - button.focus(); - } - }); - matchMedia("(min-width: 1120px)").addEventListener("change", (e) => e.matches && setOpen(false)); } // One rAF-throttled scroll listener for everything that follows the scroll. @@ -254,27 +224,6 @@ function setUpLightbox() { }); } -// --- Light and dark ------------------------------------------------------------------ - -// The page follows the system; the toggle picks the other appearance and remembers it. -function setUpTheme() { - const root = document.documentElement; - const button = document.querySelector(".theme-toggle"); - const label = button.querySelector("[data-theme-label]"); - const system = matchMedia("(prefers-color-scheme: dark)"); - const dark = () => (root.dataset.theme ? root.dataset.theme === "dark" : system.matches); - const show = () => (label.textContent = dark() ? "Light" : "Dark"); - button.addEventListener("click", () => { - root.dataset.theme = dark() ? "light" : "dark"; - try { - localStorage.setItem("theme", root.dataset.theme); - } catch {} - show(); - }); - system.addEventListener("change", show); - show(); -} - // --- Motion --------------------------------------------------------------------------- function setUpReveal() { @@ -308,9 +257,11 @@ function setUpReveal() { setUpReveal(); setUpTheme(); setUpNav(); +setUpMenu(); setUpTabs(); setUpLightbox(); setUpDownload(); -setUpNotes(); +setUpRecent(); setUpLinks(); setUpContributors(); +setUpLive(); diff --git a/website/src/privacy.html b/website/src/privacy.html index def61dcc9..3e5729775 100644 --- a/website/src/privacy.html +++ b/website/src/privacy.html @@ -5,8 +5,8 @@ Privacy · Horizon - - + + @@ -26,25 +26,35 @@
  • Performance statistics, after each play session of a minute or more. These are the frame-time and tick-time percentiles and a 14-bucket histogram (never a recording of each frame), the peak memory, how long the game took to start and to load the world, and the settings that change performance (render and simulation distance, frame limit, VSync, fullscreen, graphics mode).
  • Crash reports, when the game crashes. They hold the error, where it happened in Horizon's code, your graphics adapter and settings. They hold no log, no world, no server and no resource packs.
  • Bug reports that you write and send yourself. The end of the game's log goes with one only if you add it after reading it, and lines of chat are removed first.
  • -
  • Benchmark uploads of the benchmarks you run. These are shown publicly in the community results.
  • +
  • Benchmark uploads of the benchmarks you run. They are shown publicly on the Benchmarks page, only as medians of groups of at least 3 different installs with the same graphics card, processor and render distance; never one by one, and never with your install ID, the day, your OS version, driver, exact memory or screen.
  • -

    Each one also carries the Horizon version, the day it was made (not the time), and a description of your machine: the operating system and version, the CPU model and thread count, the memory rounded to the gigabyte, and the GPU, its driver and the graphics backend. It also carries a random install ID. The launcher makes that ID the first time you allow something; it says nothing about you and exists only so that your data can be deleted.

    +

    Each one also carries the Horizon version, the day it was made (not the time), and a description of your machine, because that is what explains how fast the game runs on it:

    +
      +
    • the operating system, its version and the processor architecture;
    • +
    • the processor model, its cores and threads, and its base and boost clock where the system gives them;
    • +
    • the memory, rounded to the gigabyte;
    • +
    • the graphics card the game draws with: its model, maker, whether it is built into the processor or separate, its own memory, its driver version and the graphics interface (Vulkan, Metal, DirectX 12);
    • +
    • the kind of drive the game folder is on (NVMe, SSD or hard disk);
    • +
    • the screen the game opened on: its size in pixels, refresh rate and scaling;
    • +
    • whether the computer is a laptop or a desktop, and whether it runs on battery.
    • +
    +

    No serial number, computer name, user name, network address or file path is read. Each item also carries a random install ID. The launcher makes that ID the first time you allow something; it says nothing about you and exists only so that your data can be deleted.

    Never sent: your Microsoft or Minecraft account name or UUID, world names, server or LAN addresses, chat, and your user name or home folder in file paths. Before anything is kept, those are replaced with placeholders, along with e-mail and IP addresses. The server does not store the IP address requests come from.

    The launcher shows exactly what would be sent: Settings → Data collection → View what would be sent, or horizon-launcher data show. Every field is listed in docs/telemetry.md.

    The "I'm playing" ping

    -

    The game has an anonymous "I'm playing" ping, so the launcher can show how many people play Horizon right now. It is off today: no server receives it yet, so the game sends nothing. This is what it would hold, so you know before it is ever switched on. It would be sent once a minute while you play, whatever the switches say.

    -

    It would hold: a random number made when the game starts and forgotten when it closes, the Horizon version, your operating system (Linux, macOS or Windows), and whether you have a world open to LAN or to friends. It would not hold: your account, your install ID, world or server names, your hardware or settings, or anything you do in the game. The random number changes every time you start the game, so two of your sessions can't be linked to each other or to you.

    -

    The server would keep the pings in memory only, never on disk, and not with the address they came from (that is used only to stop abuse, as below). A session would count while it pinged in the last two minutes and is then forgotten. What it would show is the number playing now, per version and with a world open, rounded.

    +

    The game sends an anonymous "I'm playing" ping, so the launcher can show how many people play Horizon right now. It is sent once a minute while you play, whatever the switches say.

    +

    It holds: a random number made when the game starts and forgotten when it closes, the Horizon version, your operating system (Linux, macOS or Windows), and whether you have a world open to LAN or to friends. It does not hold: your account, your install ID, world or server names, your hardware or settings, or anything you do in the game. The random number changes every time you start the game, so two of your sessions can't be linked to each other or to you.

    +

    The server keeps the pings in memory only, never on disk, and not with the address they came from (that is used only to stop abuse, as below). A session counts while it pinged in the last two minutes and is then forgotten. What it shows is the number playing now, per version and with a world open, rounded.

    Why

    -

    To find what is slow or crashes on which machines, and fix it. If it is switched on, the ping shows players, and Horizon, how many people play right now. Benchmark uploads also show other players how Horizon runs on hardware like theirs. Nothing is sold, shared for advertising, or used to identify you.

    +

    To find what is slow or crashes on which machines, and fix it. The ping shows players, and Horizon, how many people play right now. Benchmark uploads also show other players how Horizon runs on hardware like theirs. Nothing is sold, shared for advertising, or used to identify you.

    On what basis

    -

    For the switches: your consent (Article 6(1)(a) of the EU's General Data Protection Regulation). It is given kind by kind, recorded on your computer with the version of the question you answered and when, and withdrawn at any time with the same switches. Withdrawing deletes what was waiting to be sent. When what is collected changes, the launcher asks again, and nothing new is sent until you answer. The ping would hold nothing that identifies you; the address it comes from would be used only to limit how often one address may send, kept in memory for an hour at most and never stored.

    +

    For the switches: your consent (Article 6(1)(a) of the EU's General Data Protection Regulation). It is given kind by kind, recorded on your computer with the version of the question you answered and when, and withdrawn at any time with the same switches. Withdrawing deletes what was waiting to be sent. When what is collected changes, the launcher asks again, and nothing new is sent until you answer. The ping holds nothing that identifies you; the address it comes from is used only to limit how often one address may send, kept in memory for an hour at most and never stored.

    Where and how long

    -

    Items wait on your computer (telemetry/ in the game folder) and are sent compressed when the launcher starts or closes, to Horizon's own server at Railway. The server keeps them for 180 days, then deletes them. What stays after that are anonymous totals per day, Horizon version, operating system, GPU maker and render distance (for example "120 sessions on macOS with Apple GPUs at render distance 12"). They hold no install ID, and groups too small to be anonymous are never shown.

    +

    Items wait on your computer (telemetry/ in the game folder) and are sent compressed when the launcher starts or closes, to Horizon's own server, telemetry.playhorizon.dev, hosted by Railway in the European Union (Amsterdam, the Netherlands). The server keeps them for 180 days, then deletes them. What stays after that are anonymous totals per day, Horizon version, operating system, GPU maker and render distance (for example "120 sessions on macOS with Apple GPUs at render distance 12"). They hold no install ID, and groups too small to be anonymous are never shown. Published results also show how players split by memory size (in steps: 8, 16, 32 GB…), graphics memory, drive type, operating system and built-in or separate graphics, each class only once it holds at least 3 different installs; the exact values, the driver, the clocks and the screen are never published.

    Deleting your data

    Settings → Data collection → Delete my data, or horizon-launcher data delete. The server deletes everything sent under your install ID, your share of the totals is recomputed, anything waiting on your computer is removed, and you get a new install ID. You can also turn everything off, or delete the telemetry/ folder.

    diff --git a/website/src/releases-page.js b/website/src/releases-page.js new file mode 100644 index 000000000..ace84f63d --- /dev/null +++ b/website/src/releases-page.js @@ -0,0 +1,78 @@ +// The Releases page: the list baked at build time, refreshed from GitHub when a newer release is out, and the +// channel filter. Without JavaScript the baked list reads as it is. +import { releasesPageHtml } from "./releases.js"; +import { isGame, isLauncher, newestFirst } from "./versions.js"; +import { cached, get, setUpMenu, setUpTheme, slim } from "./chrome.js"; + +const REPO = "ludovic111/horizon"; +const list = document.getElementById("release-list"); +const counter = document.querySelector("[data-release-count]"); +const buttons = [...document.querySelectorAll("[data-filter]")]; +let filter = "all"; + +const ours = (r) => !r.draft && (isGame(r.tag_name) || isLauncher(r.tag_name)); + +// Every release, a page of 100 at a time (GitHub's most), up to 500. +async function loadAll() { + const all = []; + for (let page = 1; page <= 5; page++) { + const batch = await get(`https://api.github.com/repos/${REPO}/releases?per_page=100&page=${page}`); + all.push(...batch.filter(ours).map(slim)); + if (batch.length < 100) break; + } + return all; +} + +function apply() { + const entries = [...list.querySelectorAll(".release-entry")]; + let shown = 0; + for (const el of entries) { + const on = filter === "all" || el.dataset.channel === filter; + el.hidden = !on; + if (on) shown++; + } + counter.textContent = `${shown} release${shown === 1 ? "" : "s"}`; + buttons.forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.filter === filter))); +} + +async function refresh() { + // One small request first: the full list only when GitHub has something newer than the page. + const newest = await cached("horizon:releases-newest", () => get(`https://api.github.com/repos/${REPO}/releases?per_page=5`)).catch(() => null); + if (!newest) return; + const top = newest.filter(ours).map((r) => r.tag_name).sort(newestFirst)[0]; + if (!top || top === list.dataset.newest) return; + const all = await cached("horizon:releases-all", loadAll).catch(() => null); + if (!all || !all.length) return; + const open = new Set([...list.querySelectorAll(".release-entry[open]")].map((el) => el.id)); + list.innerHTML = releasesPageHtml(all); + list.dataset.newest = top; + // Keep what the reader opened open. + open.forEach((id) => document.getElementById(id)?.setAttribute("open", "")); + apply(); +} + +// A link to one release (/releases#release-v0.2.1) opens it. +function openTarget() { + const el = location.hash && document.getElementById(location.hash.slice(1)); + if (el && el.classList.contains("release-entry")) { + if (el.hidden) { + filter = "all"; + apply(); + } + el.open = true; + el.scrollIntoView(); + } +} + +buttons.forEach((b) => + b.addEventListener("click", () => { + filter = b.dataset.filter; + apply(); + }), +); +addEventListener("hashchange", openTarget); +setUpTheme(); +setUpMenu(); +apply(); +openTarget(); +refresh().then(openTarget); diff --git a/website/src/releases.html b/website/src/releases.html new file mode 100644 index 000000000..989164653 --- /dev/null +++ b/website/src/releases.html @@ -0,0 +1,49 @@ + + + + + + Releases · Horizon + + + + + + + + + + + + + + + + + + + + + +{{SITE_NAV}} +
    +
    +

    ReleasesEvery version, newest first

    +

    What's new in Horizon

    +

    Each release lists what it adds and fixes, then its full notes and its downloads. New versions come out many times a day as changes land, and the launcher installs each one once it has passed its test. The launcher has its own releases.

    +
    + + + +
    +

    {{RELEASE_COUNT}}

    +
    +{{RELEASE_LIST}} +
    +

    The releases on GitHub

    +

    Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft.

    +
    +
    +{{SITE_FOOTER}} + + diff --git a/website/src/releases.js b/website/src/releases.js index 1b7011999..de59c8fef 100644 --- a/website/src/releases.js +++ b/website/src/releases.js @@ -1,42 +1,152 @@ -// The patch notes: the latest game release in full, the ones before it folded. Shared by -// build.mjs (baked into the page) and main.js (refreshed from GitHub). -import { markdown, escape } from "./markdown.js"; +// The release notes on the site: the home page's "Recently added" block and the Releases page (every release, +// newest first). Shared by build.mjs (baked into the pages) and the pages' scripts (refreshed from GitHub). +// Tags: the game's vX.Y.Z and the launcher's launcher@X.Y.Z from 0.2, vYYYY.MM.DD[.N] and launcher-vX.Y.Z before +// (src/versions.js). One channel (docs/release-flow.md, "One channel"): a release is the game's or the launcher's. +import { markdown, inline, escape } from "./markdown.js"; +import { isLauncher, launcherVersion, newestFirst } from "./versions.js"; const REPO = "ludovic111/horizon"; +export const channel = (r) => (isLauncher(r.tag_name) ? "Launcher" : "Game"); +const anchor = (r) => `release-${r.tag_name.replace(/[^\w.-]/g, "-")}`; + // "Horizon 0.2.3: Cave culling, weather" (before 0.2, "Horizon 2026.10.13: …") reads as the version and its line. -function parts(r) { - const version = r.tag_name.replace(/^v/, ""); - const name = r.name || ""; - const line = name.includes(": ") ? name.slice(name.indexOf(": ") + 2) : name.replace(/^Horizon\s*/, "").replace(version, "").trim(); +export function parts(r) { + const version = launcherVersion(r.tag_name) ?? r.tag_name.replace(/^v/, ""); + const name = (r.name || "").trim(); + let line = name.includes(": ") ? name.slice(name.indexOf(": ") + 2) : name.replace(/^Horizon( launcher)?\s*/i, "").replace(version, "").trim(); + if (junk(line)) line = fromNotes(r.body) || line; return { version, line: line.charAt(0).toUpperCase() + line.slice(1), date: (r.published_at || "").slice(0, 10) }; } -export function releasesHtml(list) { - if (!list.length) return ""; - const [latest, ...older] = list; - const l = parts(latest); - const head = `
    -
    -

    Latest release

    -

    ${escape(l.version)}

    - ${l.line ? `

    ${escape(l.line)}

    ` : ""} - Downloads and full notes -
    -
    ${markdown(latest.body || "")}
    -
    `; - const rest = older +// A title made of issue numbers and "fix" ("#1255, mob pushes, fix, #1222") says nothing. +const junk = (line) => { + const bits = line.split(",").map((b) => b.trim()).filter(Boolean); + return bits.length > 1 && bits.filter((b) => /^(#\d+|fix(es)?|fixed)$/i.test(b)).length * 2 >= bits.length; +}; + +// The first item that isn't a bare "Fix #123:" prefix, as the line: "Mob pushes: one list per mob… and 3 more fixes". +function fromNotes(body) { + const s = sections(body); + const items = [...s.filter((x) => /^new|what's new/i.test(x.title)), ...s.filter((x) => /^fixed/i.test(x.title))].flatMap((x) => x.items).map(plainItem); + const clean = items.map((i) => i.replace(/^(fix|fixes)\s+#\d+:\s*/i, "").replace(/^\w+\([^)]*\):\s*/, "")).filter(Boolean); + if (!clean.length) return ""; + const first = clean[0].replace(/[.]$/, ""); + return clean.length > 1 ? `${first} and ${clean.length - 1} more` : first; +} + +// The notes' "### Heading" sections and their top-level items, in order. +export function sections(body) { + const out = []; + let current = null; + for (const raw of (body || "").replace(/\r\n?/g, "\n").split("\n")) { + const heading = raw.match(/^#{2,3}\s+(.+?)\s*$/); + if (heading) out.push((current = { title: heading[1], items: [] })); + else if (current && /^[-*]\s+/.test(raw)) current.items.push(raw.replace(/^[-*]\s+/, "").trim()); + } + return out; +} + +// An item without its pull request references: "Riptide (#123, fixes #45)" -> "Riptide". +export const plainItem = (item) => item.replace(/\s*\((?:#\d+|fixes #\d+|[^()]*#\d+[^()]*)\)\s*/g, " ").replace(/\s+/g, " ").trim(); + +// The notes' first sentence, for a release with no title line and no sections ("Rebuilt from the latest main."). +const firstLine = (body) => ((body || "").split(/\r?\n/).find((l) => l.trim() && !/^#/.test(l)) || "").trim().replace(/[.:]$/, ""); + +const count = (n, one, many) => `${n} ${n === 1 ? one : many}`; + +// What a release changes, in a line: "12 new, 30 fixed, 2 known issues". +export function overview(r) { + const s = sections(r.body); + const by = (re) => s.filter((x) => re.test(x.title)).reduce((n, x) => n + x.items.length, 0); + const added = by(/^new|what's new/i); + const fixed = by(/^fixed/i); + const known = by(/^known/i); + const bits = []; + if (added) bits.push(count(added, "new feature", "new features")); + if (fixed) bits.push(count(fixed, "fix", "fixes")); + if (known) bits.push(count(known, "known issue", "known issues")); + return { added, fixed, known, text: bits.join(", ") }; +} + +export function highlights(r, n = 3) { + const added = sections(r.body).filter((x) => /^new|what's new/i.test(x.title)).flatMap((x) => x.items); + return added.slice(0, n).map(plainItem); +} + +const byTag = (a, b) => newestFirst(a.tag_name, b.tag_name); +const badge = (r) => `${channel(r)}`; + +// The home page: the newest releases on a line each, and what the newest ones added. +export function recentHtml(list, { rows = 5, picks = 3 } = {}) { + const sorted = [...list].sort(byTag); + const game = sorted.filter((r) => !isLauncher(r.tag_name)); + if (!game.length) return ""; + const lines = game + .slice(0, rows) .map((r) => { - const o = parts(r); - return `
    - ${escape(o.version)}${escape(o.line)} -
    ${markdown(r.body || "")}

    Downloads and full notes on GitHub

    -
    `; + const p = parts(r); + return `
  • ${escape(p.version)}${escape(p.line || overview(r).text || firstLine(r.body) || "Release notes")}${badge(r)}
  • `; }) .join(""); - return `${head} -
    - ${rest ? `

    Earlier releases

    ${rest}` : ""} -

    Every release on GitHub

    -
    `; + // What landed last: the "New" items of the newest releases with the highest pull request numbers (a release's + // notes list everything since the release before it, oldest first). + const pr = (item) => Math.max(0, ...[...item.matchAll(/#(\d+)/g)].map((m) => Number(m[1]))); + const seen = new Set(); + const picked = game + .slice(0, rows) + .flatMap((r) => sections(r.body).filter((x) => /^new|what's new/i.test(x.title)).flatMap((x) => x.items).map((raw) => ({ raw, item: plainItem(raw), r }))) + .filter(({ item }) => !seen.has(item) && seen.add(item)) + .sort((a, b) => pr(b.raw) - pr(a.raw)) + .slice(0, picks); + const picks_ = picked + .map(({ item, r }) => `
  • ${inline(item)}

    ${escape(parts(r).version)}
  • `) + .join(""); + return `
      ${lines}
    + ${picks_ ? `

    New lately

      ${picks_}
    ` : ""} +

    Every release, with its full notes

    `; } + +const ASSET_LABELS = [ + [/linux-x86_64/, "Linux x86-64"], + [/macos-arm64/, "macOS, Apple Silicon"], + [/macos-x86_64/, "macOS, Intel"], + [/windows-x64/, "Windows x64"], +]; +function assetLabel(name) { + if (/^SHA256SUMS/.test(name)) return name.endsWith(".sig") ? "Checksums signature" : "Checksums"; + const os = ASSET_LABELS.find(([re]) => re.test(name)); + const what = /server/.test(name) ? "Server" : /launcher/.test(name) ? "Launcher" : /smoke-test/.test(name) ? "Smoke test" : "Game"; + return os ? `${what}, ${os[1]}` : name; +} +const size = (bytes) => (bytes >= 1e6 ? `${(bytes / 1e6).toFixed(0)} MB` : bytes >= 1e3 ? `${(bytes / 1e3).toFixed(0)} kB` : `${bytes} B`); + +function releaseHtml(r, open) { + const p = parts(r); + const o = overview(r); + const top = highlights(r, 4); + const downloads = (r.assets || []) + .map((a) => `
  • ${escape(assetLabel(a.name))}${escape(a.name)} · ${size(a.size || 0)}
  • `) + .join(""); + return `
    + ${escape(p.version)}${badge(r)}${escape(p.line)} +
    + ${o.text || top.length ? `
    + ${o.text ? `

    ${escape(o.text)}

    ` : ""} + ${top.length ? `
      ${top.map((t) => `
    • ${inline(t)}
    • `).join("")}
    ` : ""} +
    ` : ""} +
    ${markdown(r.body || "") || "

    No notes for this release.

    "}
    + ${downloads ? `

    Downloads

      ${downloads}
    ` : ""} +

    This release on GitHub

    +
    +
    `; +} + +// The Releases page: every release, newest first; the newest few open. +export function releasesPageHtml(list, { open = 3 } = {}) { + const sorted = [...list].sort(byTag); + if (!sorted.length) return ""; + return sorted.map((r, i) => releaseHtml(r, i < open)).join("\n"); +} + +export const releasesUrl = `https://github.com/${REPO}/releases`; diff --git a/website/src/style.css b/website/src/style.css index 03004464b..323cd6e83 100644 --- a/website/src/style.css +++ b/website/src/style.css @@ -1,8 +1,7 @@ /* Horizon's design language (docs/design-system.md), set as a page. The tokens come from crates/horizon-theme through src/tokens.css, which build.mjs puts before this file: the - same palette, type, spacing and motion as the launcher and the game's menus. Type is the - interface; content is numbered index lists with one-pixel rules; one violet accent for the - main action, links and focus; space instead of borders; quiet motion. */ + launcher's Blocks palettes, type, spacing and motion. The base below lays out the page; the + "Blocks" section at the end gives it the launcher's blocky, Minecraft-like look. */ @font-face { font-family: "Geist"; src: url("/fonts/Geist-Regular.woff2") format("woff2"); font-weight: 400; font-display: swap; } @font-face { font-family: "Geist"; src: url("/fonts/Geist-Medium.woff2") format("woff2"); font-weight: 500; font-display: swap; } @@ -301,12 +300,7 @@ figcaption span { font-family: var(--mono); font-size: var(--text-micro); letter .screen-caption { margin-top: 12px; font-size: var(--text-caption); color: var(--muted); } /* Patch notes. */ -.release-latest { display: grid; grid-template-columns: minmax(0, 5fr) minmax(0, 7fr); gap: 48px; padding-top: 32px; border-top: 1px solid var(--rule); } -.release-head { position: sticky; top: calc(var(--nav) + 24px); align-self: start; display: flex; flex-direction: column; gap: 12px; } .eyebrow { text-transform: uppercase; } -.release-version { font-size: var(--text-display); line-height: var(--text-display-line); letter-spacing: var(--text-display-tracking); font-weight: 500; } -.release-line { color: var(--muted); max-width: 36ch; } -.release-body { font-size: var(--text-ui); } .prose h2, .prose h3, .prose h4 { font-size: var(--text-heading); line-height: var(--text-heading-line); color: var(--ink); margin-top: 28px; } .prose ul, .prose ol { padding-left: 18px; list-style: disc; } .prose li + li { margin-top: 6px; } @@ -314,8 +308,6 @@ figcaption span { font-family: var(--mono); font-size: var(--text-micro); letter .prose strong { color: var(--ink); font-weight: 500; } .prose pre { padding: 16px; border-radius: var(--radius-plate); background: var(--plate-soft); overflow-x: auto; } .prose pre code { background: none; padding: 0; } -.release-older { margin-top: 64px; } -.release-older-title { font: var(--text-micro) / var(--text-micro-line) var(--mono); letter-spacing: var(--text-micro-tracking); color: var(--muted); text-transform: uppercase; margin-bottom: 12px; } .release { border-top: 1px solid var(--rule); } .release:last-of-type { border-bottom: 1px solid var(--rule); } .release summary { @@ -405,9 +397,9 @@ figcaption span { font-family: var(--mono); font-size: var(--text-micro); letter /* --- Narrow screens ------------------------------------------------------------------------ */ @media (max-width: 900px) { - .section-head, .parity-hero, .launcher-grid, .release-latest { grid-template-columns: minmax(0, 1fr); } + .section-head, .parity-hero, .launcher-grid { grid-template-columns: minmax(0, 1fr); } .section-head { gap: 16px; } - .screens, .release-head { position: static; } + .screens { position: static; } .fact { grid-template-columns: var(--index) minmax(0, 1fr); row-gap: 6px; } .fact p { grid-column: 2; } .mosaic { grid-template-columns: minmax(0, 1fr); } @@ -499,3 +491,253 @@ figcaption span { font-family: var(--mono); font-size: var(--text-micro); letter @media (pointer: coarse) { .docs-nav li a, .docs-toc a, .docs-bar-title, .docs-bar-link { display: flex; align-items: center; min-height: 44px; } } + +/* --- Blocks: the launcher's look on the page (docs/design-system.md, "Blocks") ------------- + Pixel type for headings and controls, square panels with a dark outline, a light bevel on top + and a darker lip below, the violet face for the main action, sunk wells, a stone texture + behind the page and Horizon's pixel landscape behind the hero. The art is drawn in code + (scripts/art.mjs, like launcher/src/art.rs); nothing in it comes from Minecraft. */ + +@font-face { font-family: "Pixelify Sans"; src: url("/fonts/PixelifySans-Medium.woff2") format("woff2"); font-weight: 500; font-display: swap; } +@font-face { font-family: "Pixelify Sans"; src: url("/fonts/PixelifySans-SemiBold.woff2") format("woff2"); font-weight: 600; font-display: swap; } +@font-face { font-family: "Pixelify Sans"; src: url("/fonts/PixelifySans-Bold.woff2") format("woff2"); font-weight: 700; font-display: swap; } + +:root { + --stone: url("/media/stone-light.png"); + --scene: url("/media/scene-light.png"); + --sky: #8d7fd8; + --panel-edges: inset 0 var(--block-bevel) 0 var(--bevel), inset 0 calc(-1 * var(--block-bevel)) 0 var(--lip); + --radius: 0px; --radius-plate: 0px; --radius-pill: 0px; +} +:root[data-theme="dark"] { --stone: url("/media/stone-dark.png"); --scene: url("/media/scene-dark.png"); --sky: #0a0f2c; } +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]) { --stone: url("/media/stone-dark.png"); --scene: url("/media/scene-dark.png"); --sky: #0a0f2c; } +} + +/* The stone: 64 texels of the page colour in close shades, each texel 4 px. */ +body { position: relative; isolation: isolate; } +body::before { + content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none; + background: var(--stone) 0 0 / 256px 256px repeat; image-rendering: pixelated; +} + +/* Pixel type for what names and what you act on; paragraphs stay in Geist. */ +.display, .title, .statement, .row-name, .card-title, .release-tag, .count, +.fact h3, .features h3, .system h3, .contributors-title, .footer-disclaimer, .footer-word, +.nav-mark, .docs-prose h2, .docs-prose h3, .prose h2, .prose h3, .prose h4, .menu nav a { + font-family: var(--pixel); font-weight: 600; letter-spacing: 0; +} +.display, .count, .footer-word { font-weight: 700; } +.nav-mark { font-size: 18px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.04em; } +code { border-radius: 0; background: var(--well); box-shadow: 0 0 0 1px var(--outline); } + +/* Buttons: blocks with an outline, a bevel and a lip; they sink a pixel when pressed. */ +.button { + border: var(--block-outline) solid var(--outline); border-radius: 0; + font: 500 var(--text-ui) / 1 var(--pixel); + box-shadow: inset 0 var(--block-bevel) 0 var(--button-bevel), inset 0 calc(-1 * var(--block-lip)) 0 var(--lip); + padding-bottom: 2px; +} +.button.large { font-size: 18px; } +.button.primary { background: var(--face); color: var(--on-face); box-shadow: inset 0 var(--block-bevel) 0 var(--face-bevel), inset 0 calc(-1 * var(--block-lip)) 0 var(--face-lip); } +.button.primary:hover { opacity: 1; filter: brightness(1.08); } +.button.secondary { background: var(--button); } +.button.secondary:hover { background: var(--button); filter: brightness(1.06); } +.button.ghost { border-color: transparent; box-shadow: none; } +.button:active { opacity: 1; transform: translateY(1px); box-shadow: inset 0 var(--block-bevel) 0 var(--lip); } +:focus-visible { border-radius: 0; } + +/* The top bar: the sidebar colour with an outline under it, tabs with an accent underline. */ +.nav.is-scrolled, .nav.is-menu { background: var(--side); -webkit-backdrop-filter: none; backdrop-filter: none; box-shadow: 0 var(--block-outline) 0 var(--outline); } +.nav-links a, .nav-github, .theme-toggle { border-radius: 0; font-family: var(--pixel); font-weight: 500; font-size: 15px; } +.nav-links a:hover, .nav-github:hover, .theme-toggle:hover { background: var(--raised); } +.nav-links a[aria-current] { background: var(--raised); box-shadow: inset 0 -3px 0 var(--accent); } +.theme-toggle { text-transform: none; letter-spacing: 0; } +.menu { background: var(--side); } +.menu nav a { border-bottom: 0; } + +/* Lists become stacks of panels. */ +.index, .systems, .contributors-list { border-top: 0; display: grid; gap: 8px; } +.row, .system, .release, .release:last-of-type, .contributor { border-bottom: 0; border-top: 0; } +.row > a, .row.card, .fact.row, .features li, .system, .release, .contributor, .docs-pager a { + background: var(--panel); border: var(--block-outline) solid var(--outline); box-shadow: var(--panel-edges); + border-radius: 0; +} +.row > a, .row.card, .fact.row, .features li, .system { padding-left: 20px; padding-right: 20px; } +.row > a::before, .row.card::before { display: none; } +.row > a:hover, .row.card:hover, .contributor:hover, .docs-pager a:hover { background: var(--raised); } +.row > a:hover .row-index { color: var(--accent); } +.row-name { font-size: clamp(20px, 2.2vw, 28px); } +.release { padding: 0 20px; } +.release + .release { margin-top: 8px; } +.release .prose { padding-left: 12rem; } +.contributor { padding: 12px 14px; } +.contributors-list { grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 8px; } +.contributor-avatar { border-radius: 0; box-shadow: 0 0 0 2px var(--outline); image-rendering: pixelated; } +.system.is-full .system-state { color: var(--success); } + +/* Screenshots and the launcher's screens: square, outlined. */ +.zoom, .screen, .lightbox, .prose pre, .docs-prose figure img { border-radius: 0; box-shadow: 0 0 0 var(--block-outline) var(--outline); } +.tabs { border-radius: 0; background: var(--well); box-shadow: 0 0 0 var(--block-outline) var(--outline); } +.tabs button { border-radius: 0; font-family: var(--pixel); font-weight: 500; font-size: 15px; } +.tabs button[aria-selected="true"] { color: var(--on-face); } +.tab-pill { border-radius: 0; background: var(--face); box-shadow: inset 0 var(--block-bevel) 0 var(--face-bevel), inset 0 calc(-1 * var(--block-bevel)) 0 var(--face-lip); } + +/* The hero: Horizon's landscape under a veil of the page colour, the words on the left. */ +.hero { + position: relative; isolation: isolate; overflow: hidden; + background: var(--scene) 70% 100% / clamp(1200px, 135vw, 2400px) auto no-repeat, var(--sky); image-rendering: pixelated; + border-bottom: var(--block-outline) solid var(--outline); +} +.hero::before { + content: ""; position: absolute; inset: 0; z-index: -1; + background: + linear-gradient(90deg, color-mix(in srgb, var(--page) 92%, transparent) 0%, color-mix(in srgb, var(--page) 78%, transparent) 45%, color-mix(in srgb, var(--page) 0%, transparent) 78%), + linear-gradient(180deg, color-mix(in srgb, var(--page) 0%, transparent) 55%, color-mix(in srgb, var(--page) 70%, transparent) 100%); +} +.hero .kicker span, .hero .kicker { color: var(--ink-soft); } +.hero .lede { color: var(--ink-soft); } +.hero { padding-bottom: clamp(160px, 18vw, 280px); } +.hero-after { padding-top: 40px; } +.hero-after .hero-index { margin-top: 0; max-width: 860px; } +.hero-after .disclaimer { margin-top: 24px; } +@media (max-width: 900px) { + .hero::before { background: color-mix(in srgb, var(--page) 84%, transparent); } +} + +/* Documentation. */ +.docs-bar { background: var(--side); -webkit-backdrop-filter: none; backdrop-filter: none; box-shadow: 0 var(--block-outline) 0 var(--outline); } +.docs-nav li a { border-radius: 0; } +.docs-nav li a[aria-current] { background: var(--raised); box-shadow: inset 4px 0 0 var(--accent); } +.docs-toc a { border-radius: 0; background: var(--button); box-shadow: 0 0 0 var(--block-outline) var(--outline); } +.docs-pager a { box-shadow: var(--panel-edges); } +.docs-prose h2 { border-top: var(--block-outline) solid var(--outline); } +.docs-prose blockquote { border-left: 4px solid var(--accent); background: var(--panel); padding: 10px 16px; box-shadow: 0 0 0 var(--block-outline) var(--outline); } + +/* The footer: the giant wordmark in pixels. */ +.footer { background: var(--side); border-top: var(--block-outline) solid var(--outline); margin-top: 48px; } +.footer-word { color: var(--raised); letter-spacing: 0.02em; } +:root[data-theme="dark"] .footer-word { color: var(--panel); } +@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) .footer-word { color: var(--panel); } } + +/* --- Releases and Benchmarks pages, and the home page's "Recently added" ------------------ */ + +/* Pixelify Sans' "fi" ligature draws as "A" ("8 Axes"): no common ligatures anywhere. */ +:root { font-variant-ligatures: no-common-ligatures; } + +.page-main { padding-top: calc(var(--nav) + clamp(40px, 6vw, 80px)); } +.page-title { max-width: 18ch; margin-bottom: 20px; } +.page-main > .container > .lede { font-size: var(--text-body); } +.page-main .disclaimer { margin-top: 48px; } + +/* Release and source badges: small square tags. */ +.badge { + display: inline-flex; align-items: center; height: 22px; padding: 0 8px; margin-right: 10px; vertical-align: 2px; + font: 500 12px / 1 var(--pixel); letter-spacing: 0.02em; text-transform: uppercase; white-space: nowrap; + border: var(--block-outline) solid var(--outline); background: var(--well); color: var(--ink-soft); +} +.badge-game { background: color-mix(in srgb, var(--success) 22%, var(--panel)); color: var(--ink); } +.badge-launcher { background: color-mix(in srgb, var(--accent) 20%, var(--panel)); color: var(--ink); } +.badge-us { background: color-mix(in srgb, var(--accent) 20%, var(--panel)); color: var(--ink); } +.badge-players { background: color-mix(in srgb, var(--success) 22%, var(--panel)); color: var(--ink); } +.badge-estimate { background: color-mix(in srgb, var(--warn) 24%, var(--panel)); color: var(--ink); } + +/* Home: the newest releases on a line each, then what they added. */ +.recent-list .row > a { grid-template-columns: 8.5rem minmax(0, 13rem) minmax(0, 1fr) auto; align-items: baseline; } +.recent-line { color: var(--muted); min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.recent-list .row-name { font-size: clamp(18px, 1.8vw, 22px); } +.recent-list .badge { margin-right: 0; } +.recent-picks { margin-top: 32px; } +.recent-picks .eyebrow { margin-bottom: 12px; } +.highlights { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; } +.highlight { + display: flex; flex-direction: column; justify-content: space-between; gap: 16px; padding: 18px 20px; + background: var(--panel); border: var(--block-outline) solid var(--outline); box-shadow: var(--panel-edges); +} +.highlight p { color: var(--ink); } +.highlight-from { font: var(--text-micro) / 1 var(--mono); letter-spacing: var(--text-micro-tracking); color: var(--muted); } +.highlight-from:hover { color: var(--accent); } + +/* Releases: a filter, then every release as a panel that opens. */ +.release-filter { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 32px; } +.release-filter .button[aria-pressed="true"] { background: var(--face); color: var(--on-face); box-shadow: inset 0 var(--block-bevel) 0 var(--face-bevel), inset 0 calc(-1 * var(--block-lip)) 0 var(--face-lip); } +.release-count { margin: 16px 0 12px; } +.release-list { display: grid; gap: 8px; } +.release-list .release + .release { margin-top: 0; } +.release-entry summary { grid-template-columns: minmax(0, 11rem) minmax(0, 1fr) auto; } +.release-entry .release-sub { display: flex; align-items: baseline; flex-wrap: wrap; row-gap: 4px; } +.release-detail { padding: 0 0 24px 11rem; margin-left: 16px; display: grid; gap: 20px; max-width: calc(11rem + 16px + var(--measure) + 120px); } +.release-detail .prose { padding: 0; margin: 0; font-size: var(--text-ui); max-width: none; } +.release-overview { padding: 16px 18px; background: var(--well); box-shadow: 0 0 0 var(--block-outline) var(--outline); } +.release-counts { font-family: var(--pixel); font-weight: 600; color: var(--ink); margin-bottom: 8px; } +.release-overview ul { list-style: square; padding-left: 18px; color: var(--ink-soft); font-size: var(--text-ui); } +.release-overview li + li { margin-top: 4px; } +.release-downloads ul { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 8px; margin-top: 8px; } +.release-downloads li { display: flex; flex-direction: column; gap: 2px; padding: 10px 12px; background: var(--button); box-shadow: 0 0 0 var(--block-outline) var(--outline); } +.release-downloads li a { font-weight: 500; } +.release-downloads li span { font: var(--text-micro) / 1.4 var(--mono); color: var(--muted); overflow-wrap: anywhere; } +.release-github { font-size: var(--text-caption); } +.release-entry:target { box-shadow: var(--panel-edges), 0 0 0 3px var(--accent); } + +/* Benchmarks. */ +.bench-section { margin-top: clamp(64px, 8vw, 112px); } +.bench-section > .title { margin-bottom: 16px; } +.bench-section > .lede { margin-bottom: 32px; } +.machines { display: grid; grid-template-columns: minmax(0, 1fr); gap: 24px; } +.machine { min-width: 0; padding: 24px; background: var(--panel); border: var(--block-outline) solid var(--outline); box-shadow: var(--panel-edges); } +.machine-head { display: grid; gap: 10px; margin-bottom: 20px; } +.machine-name { font-family: var(--pixel); font-weight: 600; font-size: var(--text-title); line-height: var(--text-title-line); } +.machine-facts { display: flex; flex-wrap: wrap; gap: 6px 28px; margin: 0; } +.machine-facts div { display: flex; gap: 8px; min-width: 0; } +.machine-facts dt { font: var(--text-micro) / 1.6 var(--mono); letter-spacing: var(--text-micro-tracking); text-transform: uppercase; color: var(--muted); } +.machine-facts dd { margin: 0; min-width: 0; overflow-wrap: anywhere; font-size: var(--text-caption); color: var(--ink-soft); } +.machine-note { font-size: var(--text-caption); color: var(--muted); max-width: 90ch; } +/* relative: the screen-reader-only labels inside are absolute and would escape the scroll box otherwise. */ +.table-wrap { position: relative; overflow-x: auto; } +.bench-table { width: 100%; border-collapse: collapse; font-size: var(--text-ui); } +.bench-table th, .bench-table td { padding: 9px 12px; text-align: left; border-bottom: 1px solid var(--rule); vertical-align: baseline; } +.bench-table thead th { font: var(--text-micro) / 1.4 var(--mono); letter-spacing: var(--text-micro-tracking); text-transform: uppercase; color: var(--muted); font-weight: 400; } +.bench-table thead tr:first-child th { color: var(--ink); } +.bench-table tbody th { font-weight: 500; color: var(--ink); } +.bench-table td.num { font-variant-numeric: tabular-nums; white-space: nowrap; } +.bench-table td.wins { color: var(--ink); font-weight: 600; } +.bench-table td.vs { font-size: var(--text-caption); white-space: nowrap; } +.vs-horizon { color: var(--success); } +.vs-java { color: var(--danger); } +.vs-tie, .vs-none { color: var(--muted); } +.capped { font: var(--text-micro) / 1 var(--mono); color: var(--warn); cursor: help; } +.metric-hint { display: block; font: var(--text-micro) / 1.4 var(--mono); color: var(--muted); font-weight: 400; } +.java-wins { margin-top: 16px; font-size: var(--text-caption); color: var(--ink-soft); } +.picker { display: flex; flex-wrap: wrap; gap: 16px 24px; align-items: end; padding: 20px; background: var(--panel); border: var(--block-outline) solid var(--outline); box-shadow: var(--panel-edges); } +.picker label { display: grid; gap: 6px; } +.picker label > span, .picker legend { font: var(--text-micro) / 1.4 var(--mono); letter-spacing: var(--text-micro-tracking); text-transform: uppercase; color: var(--muted); } +.picker select { + min-width: min(320px, 80vw); height: var(--control); padding: 0 10px; font: inherit; font-size: var(--text-ui); color: var(--ink); + background: var(--well); border: var(--block-outline) solid var(--outline); border-radius: 0; +} +.picker-rd { display: flex; gap: 16px; align-items: center; border: 0; padding: 0; margin: 0; } +.picker-rd legend { margin-bottom: 6px; } +.picker-rd label { display: inline-flex; align-items: center; gap: 6px; font-family: var(--pixel); font-weight: 500; height: var(--control); } +.picker-rd input { accent-color: var(--accent); width: 18px; height: 18px; } +.pick-result { margin-top: 16px; padding: 20px; background: var(--panel); border: var(--block-outline) solid var(--outline); box-shadow: var(--panel-edges); } +.pick-head { margin-bottom: 12px; font-size: var(--text-caption); color: var(--ink-soft); line-height: 1.8; } +.pick-result .meta { margin-top: 12px; } +.pick-notes { margin: 12px 0 0; padding-left: 20px; font-size: var(--text-caption); color: var(--ink-soft); line-height: 1.6; } +.players-hardware th[scope="rowgroup"] { vertical-align: top; } +.empty { color: var(--muted); } +.prose-section .prose { max-width: 80ch; } +.spec-table { margin-top: 24px; } +.spec-table summary { cursor: pointer; font-family: var(--pixel); font-weight: 600; } +.spec-table .bench-table { margin-top: 16px; max-width: 760px; } + +@media (max-width: 900px) { + .recent-list .row > a { grid-template-columns: minmax(0, 1fr) auto; row-gap: 4px; } + .recent-list .row-index { grid-column: 1; grid-row: 1; } + .recent-list .row-name { grid-column: 1; grid-row: 2; } + .recent-line { grid-column: 1 / -1; grid-row: 3; white-space: normal; } + .recent-list .row-meta { grid-column: 2; grid-row: 1; } + .highlights { grid-template-columns: minmax(0, 1fr); } + .release-entry summary { grid-template-columns: minmax(0, 1fr) auto; } + .release-detail { padding-left: 0; margin-left: 0; } + .machine { padding: 16px; } +} diff --git a/website/src/tokens.css b/website/src/tokens.css index d272865cc..816ad5b8e 100644 --- a/website/src/tokens.css +++ b/website/src/tokens.css @@ -2,21 +2,39 @@ docs/design-system.md describes the tokens. */ :root { - --page: #fafafc; - --plate-soft: #f3f3f8; - --plate: #ebecf4; - --surface: #ffffff; - --rule: #e2e3ea; - --ink: #16181f; - --ink-soft: #3b3e49; - --muted: #646875; - --accent: #5b3fd6; + --page: #ece7f7; + --plate-soft: #e9e3f8; + --plate: #ddd4f3; + --surface: #f8f6fd; + --rule: #e4ddf4; + --ink: #1b1530; + --ink-soft: #3b3354; + --muted: #585071; + --accent: #5333c9; --on-accent: #ffffff; - --danger: #b4372a; - --success: #1d7a48; + --danger: #a3301d; + --success: #136336; + --warn: #7a4f00; + --side: #e2dbf2; + --panel: #f8f6fd; + --raised: #e9e3f8; + --button: #ddd4f3; + --button-bevel: #f4f0fe; + --well: #f3f0fb; + --bevel: #ffffff; + --lip: #c3b8e2; + --outline: #2b2244; + --face: #5b3fd6; + --face-bevel: #8069ef; + --face-lip: #3a2694; + --on-face: #ffffff; color-scheme: light; --font: "Geist", ui-sans-serif, system-ui, sans-serif; --mono: "Geist Mono", ui-monospace, monospace; + --pixel: "Pixelify Sans", "Geist", ui-sans-serif, sans-serif; + --block-outline: 2px; + --block-bevel: 2px; + --block-lip: 4px; --text-micro: 11px; --text-micro-line: 1.5; --text-micro-tracking: 0.04em; @@ -88,34 +106,62 @@ @media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) { - --page: #0d0e13; - --plate-soft: #181a22; - --plate: #20222c; - --surface: #16181f; - --rule: #24262f; + --page: #0f0d17; + --plate-soft: #221e34; + --plate: #2b2641; + --surface: #1a1727; + --rule: #120f1c; --ink: #ecedf3; --ink-soft: #c5c7d1; - --muted: #8b8f9c; + --muted: #a29cb8; --accent: #9a86ff; - --on-accent: #0d0e13; + --on-accent: #ffffff; --danger: #f07a68; --success: #45c27a; + --warn: #f0b84f; + --side: #0b0a11; + --panel: #1a1727; + --raised: #221e34; + --button: #2b2641; + --button-bevel: #3d3560; + --well: #0c0b12; + --bevel: #342d52; + --lip: #07060b; + --outline: #05040a; + --face: #5b3fd6; + --face-bevel: #8a74ff; + --face-lip: #3a2694; + --on-face: #ffffff; color-scheme: dark; } } :root[data-theme="dark"] { - --page: #0d0e13; - --plate-soft: #181a22; - --plate: #20222c; - --surface: #16181f; - --rule: #24262f; + --page: #0f0d17; + --plate-soft: #221e34; + --plate: #2b2641; + --surface: #1a1727; + --rule: #120f1c; --ink: #ecedf3; --ink-soft: #c5c7d1; - --muted: #8b8f9c; + --muted: #a29cb8; --accent: #9a86ff; - --on-accent: #0d0e13; + --on-accent: #ffffff; --danger: #f07a68; --success: #45c27a; + --warn: #f0b84f; + --side: #0b0a11; + --panel: #1a1727; + --raised: #221e34; + --button: #2b2641; + --button-bevel: #3d3560; + --well: #0c0b12; + --bevel: #342d52; + --lip: #07060b; + --outline: #05040a; + --face: #5b3fd6; + --face-bevel: #8a74ff; + --face-lip: #3a2694; + --on-face: #ffffff; color-scheme: dark; }