diff --git a/.github/workflows/launcher.yml b/.github/workflows/launcher.yml index a05aa8810..79ea852fb 100644 --- a/.github/workflows/launcher.yml +++ b/.github/workflows/launcher.yml @@ -116,6 +116,9 @@ jobs: # Horizon's Azure app for Microsoft sign-in (docs/microsoft-account.md): a repository # variable, not a secret. Unset, the launcher says sign-in is not configured. HORIZON_MSA_CLIENT_ID: ${{ vars.HORIZON_MSA_CLIENT_ID }} + # The mod browser's CurseForge source (docs/mod-browser.md#curseforge): a repository secret. Unset, the + # launcher searches Modrinth only. + HORIZON_CURSEFORGE_API_KEY: ${{ secrets.HORIZON_CURSEFORGE_API_KEY }} # The release's version and tag, built in (launcher/src/backend.rs VERSION and own_tag: the tag says which # line it is on, docs/versioning.md); a launcher branch's build keeps Cargo.toml's. HORIZON_LAUNCHER_VERSION: ${{ (github.event_name != 'push' || github.ref == 'refs/heads/main') && needs.decide.outputs.version || '' }} diff --git a/.github/workflows/promote.yml b/.github/workflows/promote.yml index b7ef0b38b..3966f571b 100644 --- a/.github/workflows/promote.yml +++ b/.github/workflows/promote.yml @@ -1,17 +1,20 @@ name: promote -# Beta game releases become stable (docs/release-flow.md, "Channels"): every 30 minutes tools/release_channels.py -# promotes the newest beta that has been out 6 hours, passed its release smoke test and isn't covered by an issue -# labelled release-blocker. By hand, from GitHub's app too (Actions > promote > Run workflow): -# gh workflow run promote -f tag=v2026.10.19.03 # that beta now, without the wait -# gh workflow run promote -f tag=v2026.10.19.03 -f force=true # even blocked or without its smoke test -# gh workflow run promote -f dry_run=true # say what would be promoted +# 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 24 hours old, an issue "Promotion to stable has stalled" says so; it closes itself -# after the next promotion. +# 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: '13,43 * * * *' + - cron: '7,37 20-21 * * *' workflow_dispatch: inputs: tag: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 354f7d493..b19ba9ce5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,14 +1,14 @@ name: release # Automatic game releases (docs/release-flow.md). After every green `checks` run on main, every 10 minutes (so a # 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 15 minutes -# ago (the oldest an hour ago, if merges never pause), or at once for a pull request labelled release-now. +# 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. # 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 after 6 hours. macOS: with the repository variable MACOS_SIGN_IDENTITY set, the programs are signed with +# stable in its daily promotion. 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 @@ -45,6 +45,7 @@ jobs: outputs: release: ${{ steps.decide.outputs.release }} tag: ${{ steps.decide.outputs.tag }} + version: ${{ steps.decide.outputs.version }} head: ${{ steps.decide.outputs.head }} dry_run: ${{ steps.mode.outputs.dry_run }} steps: @@ -65,6 +66,9 @@ jobs: run: | python3 tools/release_train.py decide --kind game ${HEAD_SHA:+--head "$HEAD_SHA"} ${FORCE:+--force} | tee decision.json echo "### $(jq -r '.reason' decision.json)" >> "$GITHUB_STEP_SUMMARY" + # The version the programs are built with (docs/versioning.md): the tag without its v. + tag=$(jq -r '.tag' decision.json) + echo "version=${tag#v}" >> "$GITHUB_OUTPUT" # A dry run builds whatever the decision, to test the builds. if [[ "${{ steps.mode.outputs.dry_run }}" == true ]]; then echo "release=true" >> "$GITHUB_OUTPUT"; fi @@ -99,6 +103,9 @@ jobs: timeout-minutes: ${{ matrix.mac && 60 || 40 }} env: RUSTFLAGS: ${{ matrix.rustflags }} + # The release's version, built in (horizon_core::release): --version, user agents, crash reports and + # telemetry say it. No version-bump commits. + HORIZON_VERSION: ${{ needs.decide.outputs.version }} defaults: run: shell: bash @@ -162,9 +169,13 @@ jobs: bin=target/release "$bin/horizon-client${{ matrix.exe }}" --help | grep -q -- '--resources' "$bin/horizon-ctl${{ matrix.exe }}" --help > /dev/null - "$bin/horizon-prepare${{ matrix.exe }}" --version "$bin/horizon-prepare${{ matrix.exe }}" --help | grep -q -- '--minecraft-dir' - "$bin/horizon-server${{ matrix.exe }}" --version + # The version is the release's. + for binary in horizon-prepare horizon-server; do + out=$("$bin/$binary${{ matrix.exe }}" --version | tr -d '\r') + echo "$out" + [[ "$out" == "$binary $HORIZON_VERSION" ]] || { echo "::error::expected $binary $HORIZON_VERSION"; exit 1; } + done - name: Tools from the runner if: runner.environment == 'self-hosted' run: bash tools/ci/runner-env.sh @@ -245,7 +256,7 @@ jobs: folder="dist/${{ matrix.server_dir }}" python3 tools/check_imports.py --server "$folder/horizon-engine" "$folder/horizon-server" "$folder/horizon-prepare" "$folder/horizon-engine" --help | grep -q -- '--resources' - "$folder/horizon-server" --version + [[ "$("$folder/horizon-server" --version)" == "horizon-server $HORIZON_VERSION" ]] cd dist rm -f "${{ matrix.server_asset }}" tar czf "${{ matrix.server_asset }}" "${{ matrix.server_dir }}" @@ -338,7 +349,8 @@ jobs: 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): promote.yml makes it stable and latest after 6 hours (docs/release-flow.md). + # A beta (pre-release), the Alpha channel's: promote.yml makes it stable and latest in its daily promotion + # (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 \ dist/horizon-windows-x64.zip dist/horizon-macos-arm64.zip dist/horizon-server-linux-x86_64.tar.gz \ diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index 1a7a4d25c..48e2e57d4 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -42,8 +42,9 @@ log = "0.4" chrono = { version = "0.4.42", default-features = false, features = ["clock", "std"] } flate2 = { version = "1.1.10", default-features = false, features = ["zlib-rs", "runtime_detection"] } horizon-theme = { path = "../horizon-theme" } -# Opt-in data collection: the game keeps, the launcher sends (docs/telemetry.md). -horizon-telemetry = { path = "../horizon-telemetry", default-features = false } +# Opt-in data collection: the game keeps, the launcher sends (docs/telemetry.md); `live` is +# the anonymous "I'm playing" ping the game sends itself (`heartbeat.rs`). +horizon-telemetry = { path = "../horizon-telemetry", default-features = false, features = ["live"] } horizon-bench = { path = "../horizon-bench" } arboard = { version = "3.6.1", default-features = false, features = ["wayland-data-control"] } zip = { version = "2", default-features = false, features = ["deflate"] } diff --git a/crates/horizon-client/examples/breaking_fixture.rs b/crates/horizon-client/examples/breaking_fixture.rs index 2016fd613..da696b88e 100644 --- a/crates/horizon-client/examples/breaking_fixture.rs +++ b/crates/horizon-client/examples/breaking_fixture.rs @@ -14,6 +14,8 @@ use std::{ io::{BufRead, BufReader, BufWriter, Write}, path::Path, }; +/// The stage sprite origin the cracks carry (the oracle compares the geometry and UVs only). +const STAGE: [f32; 2] = [0.25, 0.5]; fn main() -> Result<(), Box> { let args: Vec<_> = std::env::args().collect(); let root = Path::new(&args[1]); @@ -47,7 +49,7 @@ fn main() -> Result<(), Box> { .iter() .any(|(_, m)| m.faces.iter().any(|f| f.translucent)); for (_, m) in models { - breaking::geometry(m, origin, translucent, &mut vertices); + breaking::geometry(m, origin, translucent, STAGE, &mut vertices); } } let quads: Vec<_> = vertices @@ -58,7 +60,7 @@ fn main() -> Result<(), Box> { q.iter() .map(|v| { assert_eq!(v.color, 0xffff_ffff); - assert_eq!(v.light, 240 | (240 << 8)); + assert_eq!(v.light, breaking::stage_light(STAGE)); assert_eq!(v.layer, if translucent { 12 } else { 11 }); [v.pos[0], v.pos[1], v.pos[2], v.uv[0], v.uv[1]] }) diff --git a/crates/horizon-client/examples/cauldron_fixture.rs b/crates/horizon-client/examples/cauldron_fixture.rs index 584425ced..6aa942d42 100644 --- a/crates/horizon-client/examples/cauldron_fixture.rs +++ b/crates/horizon-client/examples/cauldron_fixture.rs @@ -82,12 +82,19 @@ fn main() -> horizon_client::Result<()> { let brewing = horizon_client::brewing::Brewing::load(root, &items); // The inventory menu never reads banner patterns. let banners = horizon_client::banner::Banners::default(); + let station_recipes = horizon_client::stations::StationRecipes::default(); + let enchantments = horizon_client::enchant::Enchantments::default(); + let names = horizon_client::creative::Names::default(); let env = Env { items: &items, recipes: &recipes, brewing: &brewing, banners: &banners, + station_recipes: &station_recipes, + enchantments: &enchantments, + names: &names, trade: None, + maps: None, }; let mut out = String::new(); for line in input.lines() { diff --git a/crates/horizon-client/examples/lan_flat.rs b/crates/horizon-client/examples/lan_flat.rs index 53a4d62f7..f3dfea6b1 100644 --- a/crates/horizon-client/examples/lan_flat.rs +++ b/crates/horizon-client/examples/lan_flat.rs @@ -102,6 +102,7 @@ fn main() -> Result<(), Box> { equipment: Default::default(), health: 20.0, attributes: Vec::new(), + bed: None, living_flags: 0, }; loop { diff --git a/crates/horizon-client/examples/menu_fixture.rs b/crates/horizon-client/examples/menu_fixture.rs index 63a5351a3..1da4a0278 100644 --- a/crates/horizon-client/examples/menu_fixture.rs +++ b/crates/horizon-client/examples/menu_fixture.rs @@ -11,8 +11,41 @@ use horizon_client::{ items::Items, menu::{Env, Input, Kind, Menu}, }; +use horizon_protocol::registry::Ids; use serde_json::Value; -use std::{fs, path::Path}; +use std::{ + cell::{Cell, RefCell}, + collections::HashMap, + fs, + path::Path, +}; + +/// The case's maps: (locked, scale) by id, and the next free id. +#[derive(Default)] +struct CaseMaps { + maps: RefCell>, + next: Cell, +} + +impl horizon_client::menu::Maps for CaseMaps { + fn state(&self, id: i32) -> Option<(bool, u8)> { + self.maps.borrow().get(&id).copied() + } + + /// `MapItemSavedData.scaled` (unlocked, one scale up) or `locked`. + fn derive(&self, id: i32, scale: bool) -> Option { + let (_, s) = self.state(id)?; + let new = self.next.get(); + self.next.set(new + 1); + let made = if scale { + (false, (s + 1).min(4)) + } else { + (true, s) + }; + self.maps.borrow_mut().insert(new, made); + Some(new) + } +} fn state(menu: &Menu) -> String { let slots: Vec = (0..menu.slot_count()) @@ -24,13 +57,21 @@ fn state(menu: &Menu) -> String { .iter() .map(|(slot, stack)| format!("{slot}:{}", canon_stack(stack.as_ref()))) .collect(); - format!( + let line = format!( "{} | {} |{data} | {} | {}", slots.join(" "), canon_stack(menu.carried.as_ref()), menu.drops.join(";"), equipped.join(";") - ) + ); + if menu.kind() != Kind::Lectern { + return line; + } + // No inventory slots: the inventory Take Book fills. + let items: String = (0..36) + .map(|i| format!(" {}", canon_stack(menu.player_item(i)))) + .collect(); + format!("{line} | inv{items}") } fn main() -> horizon_client::Result<()> { @@ -44,13 +85,28 @@ fn main() -> horizon_client::Result<()> { let recipes = Recipes::load(root, &items)?; let brewing = horizon_client::brewing::Brewing::load(root, &items); let banners = horizon_client::banner::Banners::load(root); + let station_recipes = horizon_client::stations::StationRecipes::load(root, &items); + let enchantments = horizon_client::enchant::Enchantments::load(root); + let names = horizon_client::creative::Names::load(root); + let case_maps = CaseMaps::default(); let env = Env { items: &items, recipes: &recipes, brewing: &brewing, banners: &banners, + station_recipes: &station_recipes, + enchantments: &enchantments, + names: &names, trade: None, + maps: Some(&case_maps), }; + // The mob effects' network ids (BeaconMenu.encodeEffect). + let builtin = horizon_protocol::registry::Builtin::find(root) + .and_then(|p| horizon_protocol::registry::Builtin::load(&p).ok()); + let effects = builtin + .as_ref() + .and_then(|b| b.get("minecraft:mob_effect")) + .cloned(); let mut out = String::new(); for line in input.lines() { let case: Value = serde_json::from_str(line)?; @@ -68,15 +124,41 @@ fn main() -> horizon_client::Result<()> { .unwrap_or(name), ) .ok_or("menu kind")?; + // [id, scale, locked] each; the level's new maps from 1000. + case_maps.next.set(1000); + *case_maps.maps.borrow_mut() = case["maps"] + .as_array() + .into_iter() + .flatten() + .map(|m| { + let id = m[0].as_i64().unwrap_or(0) as i32; + ( + id, + ( + m[2].as_bool().unwrap_or(false), + m[1].as_u64().unwrap_or(0) as u8, + ), + ) + }) + .collect(); let mut menu = Menu::new(kind); menu.creative = case["creative"].as_bool().unwrap_or(false); + menu.levels = case["levels"].as_i64().unwrap_or(0) as i32; for (i, slot) in case["slots"].as_array().ok_or("slots")?.iter().enumerate() { menu.set_slot(&env, i, parse_stack(slot.as_str().unwrap_or("-"))?); } menu.carried = parse_stack(case["carried"].as_str().unwrap_or("-"))?; + for (i, item) in case["inventory"] + .as_array() + .into_iter() + .flatten() + .enumerate() + { + menu.set_player_item(i, parse_stack(item.as_str().unwrap_or("-"))?); + } menu.settle(&env); for (i, v) in case["data"].as_array().ok_or("data")?.iter().enumerate() { - menu.data[i] = v.as_i64().unwrap_or(0) as i32; + menu.set_data(i, v.as_i64().unwrap_or(0) as i32); } let mut furnace = furnace_kind.map(|kind| Furnace { kind, @@ -100,6 +182,26 @@ fn main() -> horizon_client::Result<()> { out += &format!("{}\n", state(&menu)); continue; } + // ServerboundRenameItemPacket: AnvilMenu.setItemName. + "RENAME" => { + menu.rename(&env, op[3].as_str().unwrap_or_default()); + out += &format!("{}\n", state(&menu)); + continue; + } + // ServerboundSetBeaconPacket: BeaconMenu.updateEffects. + "SET_BEACON" => { + fn power<'a>(ids: Option<&Ids>, v: &'a Value) -> Option<(i32, &'a str)> { + let name = v.as_str()?; + Some((ids?.id(name)?, name)) + } + let (primary, secondary) = ( + power(effects.as_ref(), &op[3]), + power(effects.as_ref(), &op[4]), + ); + menu.beacon_update(&env, primary, secondary); + out += &format!("{}\n", state(&menu)); + continue; + } // ServerboundContainerSlotStateChangedPacket. "SLOT_STATE" => { if (0..9).contains(&slot) { diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 974293ee5..a3abb54d9 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -1027,6 +1027,7 @@ fn main() -> horizon_client::Result<()> { nearest_player: player.as_ref().filter(|p| !p.spectator).map(|p| p.position), others: $snapshot, others_grid: $grid, + others_index: None, daylight: (world.day_time.rem_euclid(24000)) < 12000, game_time: world.game_time, day_time: world.day_time, diff --git a/crates/horizon-client/examples/particle_providers_probe.rs b/crates/horizon-client/examples/particle_providers_probe.rs index 989895c07..8b8bd1e0d 100644 --- a/crates/horizon-client/examples/particle_providers_probe.rs +++ b/crates/horizon-client/examples/particle_providers_probe.rs @@ -112,21 +112,26 @@ fn state(s: &ParticleSnapshot) -> String { } out } -fn world(assets: &Assets, facts: &BlockFacts, floor: bool) -> Result { +fn world(assets: &Assets, facts: &BlockFacts, floor: bool, water: bool) -> Result { let mut world = World::new(facts.air, 0); - let stone = assets - .registry - .default_state("minecraft:stone") - .ok_or("missing stone")?; + let state = |name: &str| assets.registry.default_state(name).ok_or("missing block"); + let (stone, still) = (state("minecraft:stone")?, state("minecraft:water")?); for cz in -3..=2 { for cx in -3..=2 { world .chunks .insert((cx, cz), Arc::new(Chunk::empty(cx, cz))); - if floor { - for z in 0..16 { - for x in 0..16 { - world.set(cx * 16 + x, 63, cz * 16 + z, stone)?; + for z in 0..16 { + for x in 0..16 { + let (x, z) = (cx * 16 + x, cz * 16 + z); + if floor { + world.set(x, 63, z, stone)?; + } + // The oracle's water: still sources from y 64 to 67. + if water { + for y in 64..=67 { + world.set(x, y, z, still)?; + } } } } @@ -142,8 +147,10 @@ fn main() -> Result<()> { let facts = BlockFacts::load(root, assets.registry)?; let collision = collisions::load(root, assets.registry)?; let worlds = [ - world(&assets, &facts, false)?, - world(&assets, &facts, true)?, + world(&assets, &facts, false, false)?, + world(&assets, &facts, true, false)?, + world(&assets, &facts, false, true)?, + world(&assets, &facts, true, true)?, ]; let mut engine = ParticleEngine::new(root, &HashMap::new()); for (ty, item) in [ @@ -174,7 +181,8 @@ fn main() -> Result<()> { engine.requested = Some(Vec::new()); engine.sounds.clear(); let level = ParticleLevel { - world: &worlds[usize::from(case["floor"].as_bool() == Some(true))], + world: &worlds[usize::from(case["floor"].as_bool() == Some(true)) + + 2 * usize::from(case["water"].as_bool() == Some(true))], facts: &facts, collision: &collision, player: None, diff --git a/crates/horizon-client/examples/place_recipe_fixture.rs b/crates/horizon-client/examples/place_recipe_fixture.rs index 45d763980..1e2b66dbf 100644 --- a/crates/horizon-client/examples/place_recipe_fixture.rs +++ b/crates/horizon-client/examples/place_recipe_fixture.rs @@ -38,12 +38,19 @@ fn main() -> horizon_client::Result<()> { let recipes = Recipes::load(root, &items)?; let brewing = horizon_client::brewing::Brewing::load(root, &items); let banners = horizon_client::banner::Banners::default(); + let station_recipes = horizon_client::stations::StationRecipes::default(); + let enchantments = horizon_client::enchant::Enchantments::default(); + let names = horizon_client::creative::Names::default(); let env = Env { items: &items, recipes: &recipes, brewing: &brewing, banners: &banners, + station_recipes: &station_recipes, + enchantments: &enchantments, + names: &names, trade: None, + maps: None, }; let mut out = String::new(); for (line, order) in cases.lines().zip(orders.lines()) { diff --git a/crates/horizon-client/examples/trading_fixture.rs b/crates/horizon-client/examples/trading_fixture.rs index a560b1c06..58824257c 100644 --- a/crates/horizon-client/examples/trading_fixture.rs +++ b/crates/horizon-client/examples/trading_fixture.rs @@ -239,10 +239,12 @@ fn main() -> horizon_client::Result<()> { let vanilla = fs::read_to_string(args.get(3).ok_or(usage)?)?; let items = Items::catalog(root)?; let enchantments = Enchantments::load(root); + let names = horizon_client::creative::Names::default(); let trades = Trades::load(root); let recipes = horizon_client::crafting::Recipes::load(root, &items)?; let brewing = horizon_client::brewing::Brewing::load(root, &items); let banners = horizon_client::banner::Banners::load(root); + let station_recipes = horizon_client::stations::StationRecipes::default(); let types: HashMap<_, _> = horizon_client::mobs::MobTypes::load(root)? .types .into_iter() @@ -378,7 +380,11 @@ fn main() -> horizon_client::Result<()> { recipes: &recipes, brewing: &brewing, banners: &banners, + station_recipes: &station_recipes, + enchantments: &enchantments, + names: &names, trade: Some(&env_trade), + maps: None, }; trade(&mut out, name, &kv, &mut world, &env, origin)?; } diff --git a/crates/horizon-client/src/advancements.rs b/crates/horizon-client/src/advancements.rs index 16028e220..6706532b7 100644 --- a/crates/horizon-client/src/advancements.rs +++ b/crates/horizon-client/src/advancements.rs @@ -53,6 +53,10 @@ pub struct Tree { pub by_id: HashMap, /// trigger id -> (advancement index, criterion index). pub by_trigger: HashMap>, + /// `recipe_unlocked` criteria by the recipe they name (`index_recipes`); + /// those naming none in `recipes_any`. + by_recipe: HashMap>, + recipes_any: Vec<(usize, usize)>, } fn frame(v: &Value) -> Frame { match v.as_str() { @@ -93,12 +97,111 @@ impl Tree { tree.list.push(a); } } + tree.index_recipes(); tree } + /// Index the `recipe_unlocked` criteria by recipe: a grant that unlocks + /// twenty recipes tested every one of the ~1,300 recipe advancements' + /// criteria for each (several ms in one tick). + pub fn index_recipes(&mut self) { + self.by_recipe.clear(); + self.recipes_any.clear(); + for &(ai, ci) in self + .by_trigger + .get("minecraft:recipe_unlocked") + .into_iter() + .flatten() + { + match self.list[ai].criteria[ci].conditions["recipes"].as_str() { + Some(r) => self + .by_recipe + .entry(r.to_owned()) + .or_default() + .push((ai, ci)), + None => self.recipes_any.push((ai, ci)), + } + } + } + /// The `recipe_unlocked` criteria that could pass for `recipe`, in tree + /// order (the others name another recipe). + pub fn recipe_criteria(&self, recipe: &str) -> Vec<(usize, usize)> { + let mut out = self.recipes_any.clone(); + out.extend(self.by_recipe.get(recipe).into_iter().flatten()); + out.sort_unstable(); + out + } pub fn get(&self, id: &str) -> Option<&Advancement> { self.by_id.get(id).map(|&i| &self.list[i]) } } + +/// The `inventory_changed` criteria by the items they need. A criterion whose +/// item predicates include one limited to some items (an id, a `#tag`, a +/// list) can only pass with one of those in the inventory, so an inventory +/// change tests only the criteria of the items it holds, plus those that +/// need no particular item. The same answers as testing them all: the ~1,300 +/// recipe advancements each have one, and testing every one of them cost a +/// player 1–4 ms on every tick its inventory changed. +#[derive(Default)] +pub struct InventoryIndex { + by_item: HashMap>, + any: Vec<(usize, usize)>, +} +impl InventoryIndex { + /// `tag` gives a `#tag`'s item ids (none for a tag that doesn't exist, + /// which matches nothing). + pub fn build<'t>(tree: &Tree, tag: impl Fn(&str) -> Vec<&'t str>) -> Self { + fn ids<'t>(v: &Value, tag: &impl Fn(&str) -> Vec<&'t str>, out: &mut Vec) { + match v { + Value::String(s) => match s.strip_prefix('#') { + Some(t) => out.extend(tag(t).into_iter().map(str::to_owned)), + None => out.push(s.clone()), + }, + Value::Array(a) => a.iter().for_each(|x| ids(x, tag, out)), + _ => {} + } + } + let mut index = Self::default(); + let Some(list) = tree.by_trigger.get("minecraft:inventory_changed") else { + return index; + }; + for &(ai, ci) in list { + let items = &tree.list[ai].criteria[ci].conditions["items"]; + // `id_matches`: only a string or a list limits the items. + let limited = items.as_array().and_then(|a| { + a.iter() + .map(|p| &p["items"]) + .find(|v| v.is_string() || v.is_array()) + }); + match limited { + Some(v) => { + let mut out = Vec::new(); + ids(v, &tag, &mut out); + out.sort(); + out.dedup(); + for id in out { + index.by_item.entry(id).or_default().push((ai, ci)); + } + } + None => index.any.push((ai, ci)), + } + } + index + } + /// The criteria an inventory holding these item ids could pass, in + /// tree order. + pub fn candidates<'a>(&self, held: impl IntoIterator) -> Vec<(usize, usize)> { + let mut out = self.any.clone(); + for id in held { + if let Some(list) = self.by_item.get(id) { + out.extend_from_slice(list); + } + } + out.sort_unstable(); + out.dedup(); + out + } +} fn collect(root: &Path, dir: &Path, ns: &str, out: &mut Vec<(String, std::path::PathBuf)>) { let Ok(entries) = std::fs::read_dir(dir) else { return; @@ -992,6 +1095,77 @@ impl Tree { #[cfg(test)] mod tests { use super::*; + + /// The criteria an inventory change and a recipe unlock test, on vanilla's tree: + /// `cargo test -p horizon-client --lib -- --ignored --nocapture index_on_vanilla_tree` + /// with HORIZON_RESOURCES set to the prepared resources. + #[test] + #[ignore = "needs the prepared resources"] + fn index_on_vanilla_tree() { + let Some(root) = std::env::var_os("HORIZON_RESOURCES").map(std::path::PathBuf::from) else { + return; + }; + let data = root.join("data"); + let t = std::time::Instant::now(); + let tree = Tree::load(&data); + let load = t.elapsed(); + let tags = data.join("minecraft/tags/item"); + let tag_items: HashMap> = std::fs::read_dir(&tags) + .into_iter() + .flatten() + .flatten() + .filter_map(|e| { + let v: Value = + serde_json::from_str(&std::fs::read_to_string(e.path()).ok()?).ok()?; + let name = format!("minecraft:{}", e.path().file_stem()?.to_string_lossy()); + let values = v["values"] + .as_array()? + .iter() + .filter_map(|x| x.as_str().map(str::to_owned)); + Some((name, values.collect())) + }) + .collect(); + let t = std::time::Instant::now(); + let index = InventoryIndex::build(&tree, |tag| { + tag_items + .get(tag) + .map(|v| v.iter().map(String::as_str).collect()) + .unwrap_or_default() + }); + let build = t.elapsed(); + let all = tree + .by_trigger + .get("minecraft:inventory_changed") + .map_or(0, Vec::len); + let held = [ + "minecraft:iron_ingot", + "minecraft:oak_log", + "minecraft:cobblestone", + "minecraft:diamond_pickaxe", + "minecraft:bread", + "minecraft:torch", + "minecraft:oak_planks", + "minecraft:stick", + "minecraft:coal", + ]; + let t = std::time::Instant::now(); + let mut candidates = 0; + for _ in 0..1000 { + candidates = index.candidates(held).len(); + } + let per_change = t.elapsed() / 1000; + let recipes = tree + .by_trigger + .get("minecraft:recipe_unlocked") + .map_or(0, Vec::len); + let per_recipe = tree.recipe_criteria("minecraft:iron_pickaxe").len(); + eprintln!( + "tree {load:?}; inventory_changed: {all} criteria, index built in {build:?}, \ + a 9-stack inventory tests {candidates} (looked up in {per_change:?}); \ + recipe_unlocked: {recipes} criteria, iron_pickaxe tests {per_recipe}" + ); + assert!(candidates < all / 10); + } struct Flat; impl World for Flat { fn dimension(&self) -> &str { @@ -1090,6 +1264,94 @@ mod tests { stack.id = "minecraft:tnt".into(); } } + /// Only the criteria the held items could pass are tested; those that + /// need no particular item always are. + #[test] + fn inventory_index_keeps_the_criteria_the_items_could_pass() { + let criteria = [ + serde_json::json!({"items": [{"items": "minecraft:diamond"}]}), + serde_json::json!({"items": [{"items": "#minecraft:planks"}]}), + serde_json::json!({"items": [{"count": {"min": 2}}]}), + serde_json::json!({"items": [{"count": 1}, {"items": ["minecraft:stick", "minecraft:apple"]}]}), + serde_json::json!({"slots": {"empty": 0}}), + serde_json::json!({"items": [{"items": "#minecraft:no_such_tag"}]}), + ]; + let mut tree = Tree::default(); + for (i, conditions) in criteria.into_iter().enumerate() { + tree.list.push(Advancement { + id: format!("test:{i}"), + parent: None, + display: None, + criteria: vec![Criterion { + name: "c".into(), + trigger: "minecraft:inventory_changed".into(), + conditions, + }], + requirements: vec![vec!["c".into()]], + rewards: Rewards::default(), + }); + tree.by_trigger + .entry("minecraft:inventory_changed".into()) + .or_default() + .push((i, 0)); + } + let index = InventoryIndex::build(&tree, |tag| match tag { + "minecraft:planks" => vec!["minecraft:oak_planks", "minecraft:birch_planks"], + _ => Vec::new(), + }); + let found = |held: &[&str]| -> Vec { + index + .candidates(held.iter().copied()) + .into_iter() + .map(|(ai, _)| ai) + .collect() + }; + assert_eq!(found(&[]), [2, 4]); + assert_eq!(found(&["minecraft:dirt"]), [2, 4]); + assert_eq!( + found(&["minecraft:oak_planks", "minecraft:diamond"]), + [0, 1, 2, 4] + ); + assert_eq!(found(&["minecraft:apple", "minecraft:apple"]), [2, 3, 4]); + } + /// A recipe unlocked tests only the criteria that name it. + #[test] + fn recipe_index_keeps_the_criteria_of_the_recipe() { + let mut tree = Tree::default(); + for (i, conditions) in [ + serde_json::json!({"recipes": "minecraft:oak_planks"}), + serde_json::json!({"recipes": "minecraft:stick"}), + serde_json::json!({}), + serde_json::json!({"recipes": "minecraft:oak_planks"}), + ] + .into_iter() + .enumerate() + { + tree.list.push(Advancement { + id: format!("test:{i}"), + parent: None, + display: None, + criteria: vec![Criterion { + name: "c".into(), + trigger: "minecraft:recipe_unlocked".into(), + conditions, + }], + requirements: vec![vec!["c".into()]], + rewards: Rewards::default(), + }); + tree.by_trigger + .entry("minecraft:recipe_unlocked".into()) + .or_default() + .push((i, 0)); + } + tree.index_recipes(); + assert_eq!( + tree.recipe_criteria("minecraft:oak_planks"), + [(0, 0), (2, 0), (3, 0)] + ); + assert_eq!(tree.recipe_criteria("minecraft:stick"), [(1, 0), (2, 0)]); + assert_eq!(tree.recipe_criteria("minecraft:torch"), [(2, 0)]); + } #[test] fn bucket_axolotl_block_advancements_require_the_placed_block() { let ctx = Entities { diff --git a/crates/horizon-client/src/animate_tick.rs b/crates/horizon-client/src/animate_tick.rs index b391c0cbf..ce34df510 100644 --- a/crates/horizon-client/src/animate_tick.rs +++ b/crates/horizon-client/src/animate_tick.rs @@ -61,6 +61,8 @@ enum Animate { Fire, /// An active sculk sensor. SculkSensor, + /// Potent sulfur that is not dry. + PotentSulfur, } fn step(facing: &str) -> [i32; 3] { match facing { @@ -128,6 +130,9 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate { } } "respawn_anchor" if prop("charges").is_some_and(|c| c != "0") => Animate::RespawnAnchor, + "potent_sulfur" if prop("potent_sulfur_state").is_some_and(|s| s != "dry") => { + Animate::PotentSulfur + } "bubble_column" => Animate::BubbleColumn { drag: prop("drag").as_deref() == Some("true"), }, @@ -819,6 +824,26 @@ fn block_animate_tick( } } } + Animate::PotentSulfur => { + // PotentSulfurBlock.animateTick: under a water source, two + // bubbles and, one time in ten, the noxious gas. + let above = ctx.facts.get(ctx.state([pos[0], pos[1] + 1, pos[2]])); + if above.fluid == Fluid::Water && above.fluid_level == 8 && !above.fluid_falling { + for _ in 0..2 { + let r = engine.random(); + let p = [ + fx + f64::from(r.next_float()), + fy + 1.0 + f64::from(r.next_float()), + fz + f64::from(r.next_float()), + ]; + add(engine, T::SulfurBubbles, p, [0.0; 3]); + } + if next_int(engine.random(), 10) == 0 { + let name = "minecraft:block.potent_sulfur.noxious_gas"; + sound(engine, name, [fx, fy, fz], 1.0, 1.0); + } + } + } Animate::Mycelium => { let r = engine.random(); if next_int(r, 10) == 0 { diff --git a/crates/horizon-client/src/audio.rs b/crates/horizon-client/src/audio.rs index 62bdc041f..f101f53cd 100644 --- a/crates/horizon-client/src/audio.rs +++ b/crates/horizon-client/src/audio.rs @@ -2,7 +2,7 @@ //! small mixer standing in for OpenAL: one channel per source with its gain, //! pitch, linear distance attenuation (`AL_LINEAR_DISTANCE`, reference 0, //! rolloff 1), looping, relative flag and source state, Ogg/Vorbis decoding -//! (streams on a worker thread) and stereo panning. +//! (streams on a worker thread) and OpenAL Soft's stereo panning. use crate::Result; use crate::sound_engine::{ Attenuation, Backend, Bound, ChannelId, InstanceId, PlayResult, SoundEngine, SoundInstance, @@ -45,6 +45,7 @@ struct Mixer { channels: HashMap, listener: [f64; 3], listener_yaw: f32, + listener_pitch: f32, limiter_peak: f32, } /// A sound the player could have heard (`SoundEventListener.onPlaySound`): @@ -157,6 +158,9 @@ pub struct Audio { /// Positional sounds played since the last drain, kept while the world /// is open to the network so guests hear them too. pub capture: Option>, + /// How many times each positional sound played (the control socket's `status`), + /// with or without an audio device. + pub heard: std::collections::BTreeMap, } fn decode(path: &Path) -> Option<(Vec, u32)> { use symphonia::core::{ @@ -331,6 +335,32 @@ impl Backend for MixerBackend { .unwrap_or(true) } } +/// OpenAL Soft's stereo gains `[left, right]` for a mono source in a +/// direction given in listener space (right, up, forward; any length). +/// Vanilla's context (`Library.createAttributes`: HRTF off) on a stereo +/// output renders pairwise: front azimuths are stretched by 1.5 +/// (`ScaleAzimuthFront`, so 60 degrees off-centre pans fully) and the +/// direction is decoded by the first-order stereo decoder, 0.5 W, 0.5 Y and +/// 0.0957 X in this scaling. A centred source gets 0.596 on each side, one +/// behind 0.404, one above or below 0.5, one at the source's own position +/// is panned to the front. Matches OpenAL Soft 1.25.2 (LWJGL 3.4.3, the +/// pinned client's) rendered through `ALC_SOFT_loopback` within 1e-5. +fn stereo_gains(right: f32, up: f32, forward: f32) -> [f32; 2] { + let length = (right * right + up * up + forward * forward).sqrt(); + if length <= f32::EPSILON { + return stereo_gains(0.0, 0.0, 1.0); + } + let elevation = (up / length).clamp(-1.0, 1.0).asin(); + let mut azimuth = right.atan2(forward); + if azimuth.abs() < std::f32::consts::FRAC_PI_2 { + azimuth = (azimuth.abs() * 1.5) + .min(std::f32::consts::FRAC_PI_2) + .copysign(azimuth); + } + let side = azimuth.sin() * elevation.cos(); + let front = azimuth.cos() * elevation.cos() * 0.095_660_8; + [0.5 - 0.5 * side + front, 0.5 + 0.5 * side + front] +} /// The gain OpenAL applies for distance (`AL_LINEAR_DISTANCE` with reference /// distance 0 and rolloff 1: the distance clamps to the max distance). fn distance_gain(linear: Option, distance: f32) -> f32 { @@ -345,9 +375,30 @@ fn distance_gain(linear: Option, distance: f32) -> f32 { fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) { data.fill(0.0); let listener = mixer.listener; - let yaw = mixer.listener_yaw.to_radians(); + // The camera's forward and up vectors (`Camera.forwardVector`/`upVector`) + // and OpenAL's right = forward x up. + let (yaw, pitch) = ( + f64::from(mixer.listener_yaw.to_radians()), + f64::from(mixer.listener_pitch.to_radians()), + ); + let forward = [ + -yaw.sin() * pitch.cos(), + -pitch.sin(), + yaw.cos() * pitch.cos(), + ]; + let up = [ + -yaw.sin() * pitch.sin(), + pitch.cos(), + yaw.cos() * pitch.sin(), + ]; + let right = [ + forward[1] * up[2] - forward[2] * up[1], + forward[2] * up[0] - forward[0] * up[2], + forward[0] * up[1] - forward[1] * up[0], + ]; + let dot = |a: [f64; 3], b: [f64; 3]| (a[0] * b[0] + a[1] * b[1] + a[2] * b[2]) as f32; // Gains and pans per source for this buffer. - let mut voices: Vec<(ChannelId, f32, f32, f64)> = Vec::new(); + let mut voices: Vec<(ChannelId, [f32; 3], f64)> = Vec::new(); for (id, c) in &mixer.channels { let Some((_, source_rate)) = &c.samples else { continue; @@ -366,19 +417,17 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) { }; let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt() as f32; let gain = c.gain.clamp(0.0, 1.0) * distance_gain(c.linear, distance); - // The listener's right vector for a Minecraft yaw. - let side = if c.relative { - (d[0] as f32) / distance.max(0.001) + // Relative sources are already in OpenAL's listener space (-Z ahead). + let [left, right] = if c.relative { + stereo_gains(d[0] as f32, d[1] as f32, -d[2] as f32) } else { - (-(yaw.cos()) as f64 * d[0] - (yaw.sin()) as f64 * d[2]) as f32 / distance.max(0.001) - }; - let pan = side.clamp(-1.0, 1.0); - let left = gain * (1.0 - pan.max(0.0) * 0.6); - let right = gain * (1.0 + pan.min(0.0) * 0.6); + stereo_gains(dot(d, right), dot(d, up), dot(d, forward)) + } + .map(|pan| gain * pan); let step = f64::from(*source_rate) / f64::from(rate) * f64::from(c.pitch.max(0.0)); - voices.push((*id, left, right, step)); + voices.push((*id, [left, right, gain], step)); } - for (id, left, right, step) in voices { + for (id, [left, right, gain], step) in voices { let Some(c) = mixer.channels.get_mut(&id) else { continue; }; @@ -402,16 +451,19 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) { frame[0] += s * left; frame[1] += s * right; } else { - frame[0] += s * (left + right) / 2.0; + // A mono output has no panning: the source's own gain. + frame[0] += s * gain; } c.position += step; } } // Limit the whole buffer together, preserving waveform and stereo balance - // instead of flattening each overloaded sample; release over 50 ms. + // instead of flattening each overloaded sample; release over 200 ms + // (OpenAL Soft's output limiter, `ALC_OUTPUT_LIMITER_SOFT`, releases + // over 0.2 s). let peak = data.iter().fold(1.0f32, |peak, s| peak.max(s.abs())); mixer.limiter_peak = mixer.limiter_peak.max(peak); - let release = (-1.0 / (0.05 * rate as f32)).exp(); + let release = (-1.0 / (0.2 * rate as f32)).exp(); for frame in data.chunks_mut(channels) { let gain = mixer.limiter_peak.recip(); for s in frame { @@ -542,6 +594,7 @@ impl Audio { random: LegacyRandom::new(crate::sound_engine::unique_seed()), source_override: None, capture: None, + heard: Default::default(), } } #[cfg(not(feature = "audio"))] @@ -591,13 +644,15 @@ impl Audio { backend: &mut self.backend, } } - /// `SoundManager.updateSource`: the camera position and yaw. - pub fn set_listener(&mut self, position: [f64; 3], yaw: f32) { + /// `SoundManager.updateSource`: the camera position and rotation + /// (`Listener.setTransform` takes its forward and up vectors). + pub fn set_listener(&mut self, position: [f64; 3], yaw: f32, pitch: f32) { self.listener = position; self.listener_yaw = yaw; if let Ok(mut m) = self.backend.mixer.lock() { m.listener = position; m.listener_yaw = yaw; + m.listener_pitch = pitch; } } /// Sync the volume options, refreshing the categories that changed @@ -682,6 +737,9 @@ impl Audio { if let (Some(capture), Some(at)) = (self.capture.as_mut(), at) { capture.push((event.to_owned(), at, volume, pitch)); } + if at.is_some() { + *self.heard.entry(event.to_owned()).or_default() += 1; + } self.sync_volumes(); let event = crate::sound_events::normalize(event); let source = self @@ -908,8 +966,9 @@ mod tests { } let mut data = [0.0; 16]; mix(&mut m, &mut data, 2, 48_000); + // West of a listener facing south: fully on the right. for (frame, sample) in data.as_chunks::<2>().0.iter().zip(wave) { - assert!((frame[0] - sample * 0.4).abs() < 1e-6, "{frame:?}"); + assert!(frame[0].abs() < 1e-6, "{frame:?}"); assert!((frame[1] - sample).abs() < 1e-6, "{frame:?}"); } assert!(data.iter().all(|s| s.abs() <= 1.0)); @@ -920,9 +979,10 @@ mod tests { let mut m = Mixer::default(); m.channels .insert(1, channel(vec![0.25; 2], None, [0.0; 3], true)); + let quiet = 0.25 * stereo_gains(0.0, 0.0, 1.0)[0]; let mut data = [0.0; 16]; mix(&mut m, &mut data, 2, 48_000); - assert_eq!(data, [0.25; 16]); + assert_eq!(data, [quiet; 16]); for id in 2..=5 { m.channels @@ -935,7 +995,7 @@ mod tests { mix(&mut m, &mut recovery, 2, 48_000); assert!(recovery[0] > 0.0 && recovery[0] < 0.1); assert!(recovery.windows(2).all(|w| w[1] >= w[0])); - assert_eq!(*recovery.last().unwrap(), 0.25); + assert_eq!(*recovery.last().unwrap(), quiet); } #[test] @@ -953,4 +1013,60 @@ mod tests { let first = data[0] + data[1]; assert!(first > 1.4 && first < 3.1, "{first}"); } + + #[test] + fn stereo_panning_matches_openal_soft() { + // OpenAL Soft 1.25.2 (LWJGL 3.4.3's macOS build), stereo loopback + // device with vanilla's attributes, 1 kHz sine 4 blocks away. + let cases = [ + ((0.0, 0.0, 1.0), [0.5957, 0.5957]), + ((-1.0, 0.0, 0.0), [1.0, 0.0]), + ((1.0, 0.0, 0.0), [0.0, 1.0]), + ((0.0, 0.0, -1.0), [0.4043, 0.4043]), + ((0.0, 1.0, 0.0), [0.5, 0.5]), + ((0.0, -1.0, 0.0), [0.5, 0.5]), + ((-1.0, 0.0, 1.0), [0.9985, 0.0747]), + ((-1.0, 0.0, -1.0), [0.7859, 0.0788]), + ((0.0, 0.0, 0.0), [0.5957, 0.5957]), + ]; + for ((right, up, forward), expected) in cases { + let gains = stereo_gains(right, up, forward); + for (g, e) in gains.into_iter().zip(expected) { + assert!((g - e).abs() < 1e-4, "{right} {up} {forward}: {gains:?}"); + } + } + } + + #[test] + fn panning_follows_the_camera_rotation() { + let gains = |yaw: f32, pitch: f32, at: [f32; 3]| { + let mut m = Mixer { + listener_yaw: yaw, + listener_pitch: pitch, + ..Mixer::default() + }; + m.channels.insert(1, channel(vec![1.0; 4], None, at, true)); + let mut data = [0.0; 2]; + mix(&mut m, &mut data, 2, 48_000); + data + }; + let close = + |a: [f32; 2], b: [f32; 2]| (a[0] - b[0]).abs() < 1e-4 && (a[1] - b[1]).abs() < 1e-4; + // Facing south (yaw 0), east is on the left; facing north, on the right. + assert!(close(gains(0.0, 0.0, [1.0, 0.0, 0.0]), [1.0, 0.0])); + assert!(close(gains(180.0, 0.0, [1.0, 0.0, 0.0]), [0.0, 1.0])); + // Looking straight down, a source below is ahead and one south is above. + assert!(close(gains(0.0, 90.0, [0.0, -1.0, 0.0]), [0.5957, 0.5957])); + assert!(close(gains(0.0, 90.0, [0.0, 0.0, 1.0]), [0.5, 0.5])); + } + + #[test] + fn a_mono_output_plays_sources_unpanned() { + let mut m = Mixer::default(); + m.channels + .insert(1, channel(vec![0.5; 4], None, [0.0, 0.0, -3.0], true)); + let mut data = [0.0; 2]; + mix(&mut m, &mut data, 1, 48_000); + assert_eq!(data, [0.5; 2]); + } } diff --git a/crates/horizon-client/src/auth.rs b/crates/horizon-client/src/auth.rs index a6dfab1ee..b899ea5d5 100644 --- a/crates/horizon-client/src/auth.rs +++ b/crates/horizon-client/src/auth.rs @@ -174,7 +174,7 @@ pub fn discovery_url() -> String { fn agent() -> ureq::Agent { ureq::AgentBuilder::new() .timeout(Duration::from_secs(15)) - .user_agent(concat!("Horizon/", env!("CARGO_PKG_VERSION"))) + .user_agent(&format!("Horizon/{}", horizon_core::release::VERSION)) .build() } diff --git a/crates/horizon-client/src/bin/horizon-ctl/mcp.rs b/crates/horizon-client/src/bin/horizon-ctl/mcp.rs index fa60b38f9..8d67953a5 100644 --- a/crates/horizon-client/src/bin/horizon-ctl/mcp.rs +++ b/crates/horizon-client/src/bin/horizon-ctl/mcp.rs @@ -130,7 +130,7 @@ impl Session { "initialize" => Ok(json!({ "protocolVersion": params.get("protocolVersion").and_then(Value::as_str).unwrap_or(PROTOCOL), "capabilities": { "tools": {} }, - "serverInfo": { "name": "horizon-ctl", "version": env!("CARGO_PKG_VERSION") }, + "serverInfo": { "name": "horizon-ctl", "version": horizon_core::release::VERSION }, "instructions": "Play Horizon, a Rust reimplementation of Minecraft Java Edition. Start with launch (it finds the game installed by the Horizon launcher and opens or creates a world), then read the world with state, inventory, screen, entities and find_block, and act with goto, look_at_block, break, place, interact, click_slot and click_button. Actions block until they finish and report what happened. Coordinates are block coordinates; yaw 0 faces south (+Z).", })), "ping" => Ok(json!({})), diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index db6bf7b79..21376d698 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -939,7 +939,14 @@ impl BlockEntityRenderer { !matches!(self.kind(state), Kind::None) } /// ChestRenderer and BannerRenderer submit their animated models for crumbling. - pub fn render_breaking(&self, scene: &Scene, pos: [i32; 3], state: u32, out: &mut Vec) { + pub fn render_breaking( + &self, + scene: &Scene, + pos: [i32; 3], + state: u32, + stage: [f32; 2], + out: &mut Vec, + ) { if !matches!(self.kind(state), Kind::Banner { .. } | Kind::Chest { .. }) { return; } @@ -958,7 +965,7 @@ impl BlockEntityRenderer { false, out, ); - crate::breaking::entity_geometry(&mut out[start..], origin); + crate::breaking::entity_geometry(&mut out[start..], origin, stage); } /// `ChestRenderer.extractRenderState`'s openness for the chest of `state` /// at `pos`: `ChestBlock.combine` (`DoubleBlockCombiner.combineWithNeigbour`) @@ -1942,7 +1949,7 @@ mod tests { let mut base = Vec::new(); renderer.render_block(&scene, [0; 3], state, Mat4::IDENTITY, 0xff, &mut base); let mut cracks = Vec::new(); - renderer.render_breaking(&scene, [0; 3], state, &mut cracks); + renderer.render_breaking(&scene, [0; 3], state, [0.0; 2], &mut cracks); assert!(!cracks.is_empty()); assert_eq!( base.iter().map(|v| v.pos).collect::>(), @@ -1956,7 +1963,7 @@ mod tests { scene.lid = &|_| 1.0; } let mut animated = Vec::new(); - renderer.render_breaking(&scene, [0; 3], state, &mut animated); + renderer.render_breaking(&scene, [0; 3], state, [0.0; 2], &mut animated); assert!(cracks.iter().zip(&animated).any(|(a, b)| a.pos != b.pos)); scene.game_time = 0; scene.lid = &|_| 0.0; diff --git a/crates/horizon-client/src/breaking.rs b/crates/horizon-client/src/breaking.rs index c7ee19206..84eedae75 100644 --- a/crates/horizon-client/src/breaking.rs +++ b/crates/horizon-client/src/breaking.rs @@ -23,7 +23,21 @@ pub fn decal_uv([x, y, z]: [f32; 3], direction: Direction) -> [f32; 2] { [-p[0], -p[1]] } -pub fn geometry(model: &BakedModel, origin: glam::Vec3, translucent: bool, out: &mut Vec) { +/// The light bytes of a crack vertex: the pass is unlit, so they carry the origin of the +/// vertex's destroy stage sprite (each crack in `LevelRenderer.destroyingBlocks` has its own +/// stage; every stage sprite has the same size, `crumbling_sprite.zw`). +pub fn stage_light([u0, v0]: [f32; 2]) -> u32 { + let q = |x: f32| (x.clamp(0.0, 1.0) * 65535.0).round() as u32; + q(u0) | (q(v0) << 16) +} + +pub fn geometry( + model: &BakedModel, + origin: glam::Vec3, + translucent: bool, + stage: [f32; 2], + out: &mut Vec, +) { // Vanilla visits all six cull groups and then the unculled faces, even beside solid neighbours. for cull in Direction::ALL.map(Some).into_iter().chain([None]) { for face in model.faces.iter().filter(|face| face.quad.cull == cull) { @@ -33,7 +47,7 @@ pub fn geometry(model: &BakedModel, origin: glam::Vec3, translucent: bool, out: uv: decal_uv(pos, face.quad.facing), layer: if translucent { 12 } else { 11 }, color: 0xffff_ffff, - light: 240 | (240 << 8), + light: stage_light(stage), normal: [0; 4], }); } @@ -42,7 +56,7 @@ pub fn geometry(model: &BakedModel, origin: glam::Vec3, translucent: bool, out: } /// Project a block entity's transformed quads onto the same destroy-stage pass. -pub fn entity_geometry(vertices: &mut [Vertex], origin: glam::Vec3) { +pub fn entity_geometry(vertices: &mut [Vertex], origin: glam::Vec3, stage: [f32; 2]) { for quad in vertices.as_chunks_mut::<4>().0 { let positions = [0, 1, 2].map(|i| glam::Vec3::from(quad[i].pos)); let normal = (positions[1] - positions[0]).cross(positions[2] - positions[0]); @@ -65,7 +79,7 @@ pub fn entity_geometry(vertices: &mut [Vertex], origin: glam::Vec3) { vertex.uv = decal_uv((glam::Vec3::from(vertex.pos) - origin).to_array(), facing); vertex.layer = 11; vertex.color = 0xffff_ffff; - vertex.light = 240 | (240 << 8); + vertex.light = stage_light(stage); } } } @@ -73,6 +87,24 @@ pub fn entity_geometry(vertices: &mut [Vertex], origin: glam::Vec3) { #[cfg(test)] mod tests { use super::*; + + #[test] + fn stage_origin_survives_the_light_bytes() { + // entity.wgsl's `wrap`: the low and high 16 bits over 65535. + for origin in [[0.0, 0.0], [0.5, 0.25], [0.123_456, 0.987_654], [1.0, 1.0]] { + let light = stage_light(origin); + let back = [ + (light & 0xffff) as f32 / 65535.0, + (light >> 16) as f32 / 65535.0, + ]; + for k in 0..2 { + assert!( + (back[k] - origin[k]).abs() <= 0.5 / 65535.0, + "{origin:?} -> {back:?}" + ); + } + } + } use crate::models::catalog::BakedFace; use horizon_assets::{bake::ModelQuad, model::Material}; fn slab_top() -> BakedModel { @@ -109,7 +141,13 @@ mod tests { fn slab_overlay_follows_baked_top_not_unit_cube() { let model = slab_top(); let mut vertices = Vec::new(); - geometry(&model, glam::Vec3::new(2.0, 3.0, 4.0), false, &mut vertices); + geometry( + &model, + glam::Vec3::new(2.0, 3.0, 4.0), + false, + [0.0; 2], + &mut vertices, + ); assert_eq!(vertices.len(), 4); for (v, p) in vertices.iter().zip(model.faces[0].quad.positions) { assert_eq!(v.pos, [p[0] + 2.0, p[1] + 3.0, p[2] + 4.0]); @@ -120,14 +158,14 @@ mod tests { fn entity_overlay_uses_block_local_projected_uvs() { let origin = glam::Vec3::new(12.0, -3.0, 8.0); let mut expected = Vec::new(); - geometry(&slab_top(), origin, false, &mut expected); + geometry(&slab_top(), origin, false, [0.0; 2], &mut expected); let mut actual = expected.clone(); for vertex in &mut actual { vertex.uv = [0.0; 2]; vertex.layer = 0; vertex.color = 0; } - entity_geometry(&mut actual, origin); + entity_geometry(&mut actual, origin, [0.0; 2]); assert_eq!( bytemuck::cast_slice::<_, u8>(&actual), bytemuck::cast_slice::<_, u8>(&expected) @@ -143,7 +181,7 @@ mod tests { #[test] fn translucent_overlay_has_its_own_pass() { let mut vertices = Vec::new(); - geometry(&slab_top(), glam::Vec3::ZERO, true, &mut vertices); + geometry(&slab_top(), glam::Vec3::ZERO, true, [0.0; 2], &mut vertices); assert!(vertices.iter().all(|v| v.layer == 12)); } #[test] @@ -151,7 +189,7 @@ mod tests { let mut model = slab_top(); model.faces.clear(); let mut vertices = Vec::new(); - geometry(&model, glam::Vec3::ZERO, false, &mut vertices); + geometry(&model, glam::Vec3::ZERO, false, [0.0; 2], &mut vertices); assert!(vertices.is_empty()); } } diff --git a/crates/horizon-client/src/collisions.rs b/crates/horizon-client/src/collisions.rs index a52f25ce7..67f5d6027 100644 --- a/crates/horizon-client/src/collisions.rs +++ b/crates/horizon-client/src/collisions.rs @@ -15,8 +15,9 @@ use horizon_world::{ entity_obstruction::EntityIdentity, fluid::{FluidKind, FluidState}, liquid_collision::LiquidCollisionWorld, + piston_shape::PistonCollisionWorld, powder_snow_collision::{PowderSnowEntity, PowderSnowWorld}, - registry::{BlockRegistry, BlockTableFile}, + registry::{BlockRegistry, BlockStateId, BlockTableFile}, world_movement::{ CollisionCheckRequest, EntityMovementWorld, MovementRequest, no_world_collision, resolve_world_movement, @@ -259,8 +260,30 @@ impl DynamicSupportWorld for SceneCollisions<'_, '_> { fn shulker_is_closed(&mut self, _: [i32; 3]) -> io::Result> { Ok(None) } - fn moving_piston_shape(&mut self, _: [i32; 3]) -> io::Result> { - Ok(None) + /// `MovingPistonBlock.getCollisionShape`: the block entity's moving shape + /// (`PistonMovingBlockEntity.getCollisionShape`), outside any push. + fn moving_piston_shape(&mut self, p: [i32; 3]) -> io::Result> { + let Some(&(_, piston)) = self.world.moving_pistons.iter().find(|(q, _)| *q == p) else { + return Ok(None); + }; + let binding = self.binding; + let Some(pistons) = binding.pistons() else { + return Ok(None); + }; + pistons + .collision_shape(self, p, piston, None) + .map(Some) + .map_err(io::Error::other) + } +} +impl PistonCollisionWorld for SceneCollisions<'_, '_> { + type Error = io::Error; + /// `BlockState.getCollisionShape(level, pos)` of the moved state. + fn collision_shape(&mut self, state: BlockStateId, p: [i32; 3]) -> io::Result { + let binding = self.binding; + binding + .collision_shape(self, state, p) + .map_err(io::Error::other) } } impl DynamicCollisionWorld for SceneCollisions<'_, '_> { diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 6a135799c..854332815 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -528,7 +528,7 @@ impl Furnace { let has_fuel = self.items[1].is_some(); if lit || has_fuel && has_ingredient { if let Some(ingredient) = self.items[0].clone() { - if let Some(recipe) = recipes.cook(self.kind.recipe_type(), &ingredient).cloned() { + if let Some(recipe) = recipes.cook(self.kind.recipe_type(), &ingredient) { if self.cooking_timer == 0 { self.cooking_total = total_time(recipe.time, self.speed); } diff --git a/crates/horizon-client/src/crafting.rs b/crates/horizon-client/src/crafting.rs index e96ca0067..d0b8906ee 100644 --- a/crates/horizon-client/src/crafting.rs +++ b/crates/horizon-client/src/crafting.rs @@ -1102,7 +1102,11 @@ pub struct Recipes { facts: HashMap, Facts>, /// The `#minecraft:curse` enchantments. curses: HashSet, + /// The first cooking recipe of each kind taking each item, built at the + /// first lookup (furnaces look theirs up every tick). + cook_index: std::sync::OnceLock, } +type CookIndex = HashMap>; /// `MinMaxBounds.Ints` as (min, max) with the given defaults. fn bounds(v: Option<&Value>, default: (i64, i64), open: (i64, i64)) -> (i64, i64) { match v { @@ -1421,6 +1425,7 @@ impl Recipes { meta, facts, curses, + cook_index: Default::default(), }) } /// Match a `size`x`size` grid (row-major) against the crafting recipes. @@ -1606,6 +1611,22 @@ impl Recipes { out } pub fn cook(&self, kind: &str, input: &ItemStack) -> Option<&Cooking> { + let index = self.cook_index.get_or_init(|| { + let mut index = CookIndex::new(); + for (i, c) in self.cooking.iter().enumerate() { + let of_kind = index.entry(c.kind.clone()).or_default(); + for item in &c.ingredient.0 { + of_kind.entry(item.clone()).or_insert(i); + } + } + index + }); + let i = *index.get(kind)?.get(&*input.item)?; + self.cooking.get(i) + } + /// `cook` by scanning every recipe, as it was before the index. + #[cfg(test)] + fn cook_scan(&self, kind: &str, input: &ItemStack) -> Option<&Cooking> { self.cooking .iter() .find(|c| c.kind == kind && c.ingredient.test(input)) @@ -1625,6 +1646,80 @@ mod tests { s.data_mut().banner_patterns = vec![BannerLayer::new("minecraft:cross", "red")]; s } + /// About vanilla's count of cooking recipes: four kinds, ingredients of + /// one to twelve items, overlapping (several recipes take some items). + fn cooking_book() -> Recipes { + let kinds = ["smelting", "blasting", "smoking", "campfire_cooking"]; + let cooking = (0..320usize) + .map(|i| Cooking { + id: format!("r{i}"), + category: "misc".into(), + group: String::new(), + kind: kinds[i % 4].into(), + ingredient: ingredient( + &(0..1 + i % 12) + .map(|k| format!("minecraft:item_{}", (i * 7 + k * 13) % 400)) + .collect::>() + .iter() + .map(String::as_str) + .collect::>(), + ), + result: ItemStack::new("minecraft:stone", 1), + experience: 0.1, + time: 200, + }) + .collect(); + Recipes { + crafting: Vec::new(), + cooking, + meta: HashMap::new(), + facts: HashMap::new(), + curses: HashSet::new(), + cook_index: Default::default(), + } + } + #[test] + fn cook_finds_the_first_recipe_the_scan_finds() { + let recipes = cooking_book(); + for kind in [ + "smelting", + "blasting", + "smoking", + "campfire_cooking", + "other", + ] { + for n in 0..420 { + let stack = ItemStack::new(&format!("minecraft:item_{n}"), 1); + let a = recipes.cook(kind, &stack).map(|c| &c.id); + let b = recipes.cook_scan(kind, &stack).map(|c| &c.id); + assert_eq!(a, b, "{kind} item_{n}"); + } + } + } + /// A furnace's recipe lookup, once per lit furnace per tick. + #[test] + #[ignore] + fn cook_cost() { + let recipes = cooking_book(); + let stacks: Vec = (0..1000) + .map(|n| ItemStack::new(&format!("minecraft:item_{}", n % 400), 1)) + .collect(); + let t = std::time::Instant::now(); + let a = stacks + .iter() + .filter(|s| recipes.cook_scan("smelting", s).cloned().is_some()) + .count(); + let before = t.elapsed().as_secs_f64() * 1e3; + recipes.cook("smelting", &stacks[0]); + let t = std::time::Instant::now(); + let b = stacks + .iter() + .filter(|s| recipes.cook("smelting", s).is_some()) + .count(); + let after = t.elapsed().as_secs_f64() * 1e3; + assert_eq!(a, b); + println!("1000 furnace lookups (scan and clone -> index): {before:.3} ms -> {after:.3} ms"); + } fn run(special: &Special, cells: &[ItemStack]) -> Option { let recipes = Recipes { crafting: Vec::new(), @@ -1632,6 +1727,7 @@ mod tests { meta: HashMap::new(), facts: HashMap::new(), curses: HashSet::new(), + cook_index: Default::default(), }; let ctx = Context { recipes: &recipes, diff --git a/crates/horizon-client/src/crash.rs b/crates/horizon-client/src/crash.rs index 8ee5803b5..e147bfb4c 100644 --- a/crates/horizon-client/src/crash.rs +++ b/crates/horizon-client/src/crash.rs @@ -105,18 +105,23 @@ impl Report { } } -/// The release tag (the launcher installs each build in a folder named after it) and the client's -/// own version, or just the latter. +/// The release this binary is (`v0.2.3`); for a release from before 0.2, its tag and the client's +/// crate version; for a build from source, that version alone. pub fn version() -> String { let version = env!("CARGO_PKG_VERSION"); - match release_tag() { - Some(tag) => format!("{tag} (client {version})"), - None => version.to_owned(), + match (horizon_core::release::RELEASE, release_tag()) { + (Some(_), Some(tag)) => tag, + (None, Some(tag)) => format!("{tag} (client {version})"), + (_, None) => version.to_owned(), } } -/// The release this binary came with: launcher installs live in a folder named after the tag. +/// The release this binary came with: the version release.yml built in (docs/versioning.md), else +/// the folder the launcher installed it in, named after the tag (releases from before 0.2). pub fn release_tag() -> Option { + if let Some(version) = horizon_core::release::RELEASE { + return Some(format!("v{version}")); + } let exe = std::env::current_exe().ok()?; let folder = exe.parent()?.file_name()?.to_str()?; (folder.starts_with('v') && folder[1..].starts_with(|c: char| c.is_ascii_digit())) @@ -517,6 +522,18 @@ pub fn debug_crash_after() -> Option { mod tests { use super::*; + #[test] + fn a_release_reports_its_built_in_version() { + // release.yml builds with HORIZON_VERSION (docs/versioning.md): `v0.2.3`, wherever it is installed. + match horizon_core::release::RELEASE { + Some(version) => { + assert_eq!(release_tag(), Some(format!("v{version}"))); + assert_eq!(super::version(), format!("v{version}")); + } + None => assert!(release_tag().is_none() || super::version().contains("(client ")), + } + } + fn report() -> Report { Report { time: chrono::TimeZone::with_ymd_and_hms(&Local, 2026, 10, 14, 9, 5, 7).unwrap(), diff --git a/crates/horizon-client/src/creative.rs b/crates/horizon-client/src/creative.rs index 80445d541..55e4eb28e 100644 --- a/crates/horizon-client/src/creative.rs +++ b/crates/horizon-client/src/creative.rs @@ -44,6 +44,7 @@ pub struct Creative { search_index: Vec, } /// Display names from the pinned en_us language file. +#[derive(Default)] pub struct Names { map: HashMap, } diff --git a/crates/horizon-client/src/dynamic_light.rs b/crates/horizon-client/src/dynamic_light.rs new file mode 100644 index 000000000..4502b3356 --- /dev/null +++ b/crates/horizon-client/src/dynamic_light.rs @@ -0,0 +1,133 @@ +//! Horizon Extras' dynamic lights (docs/extras.md): a torch, lantern or other light source held by +//! a player or mob, dropped as an item, or an entity on fire lights the blocks and entities +//! around it. Not in vanilla; off by default. +//! +//! Client-only and at render time: the light engine, chunk meshes and saves never see it. Each +//! frame the game picks the [`MAX`] sources nearest the camera; terrain.wgsl and entity.wgsl +//! raise a vertex's block light to `level - distance` (one level per block, as block light falls +//! off) when that is brighter. Off, the list is empty and the shaders skip the loop. +use crate::blocks::BlockFacts; +use glam::DVec3; +use horizon_world::registry::BlockRegistry; +use std::collections::HashMap; + +/// Lights the shaders read: `Globals.dynamic_lights` in gfx.rs, terrain.wgsl and entity.wgsl. +pub const MAX: usize = 16; +/// What an entity on fire gives off, as a lit campfire or fire block does. +pub const BURNING: u8 = 15; +/// Sources farther than this from the camera light nothing it can see well. +const REACH: f64 = 96.0; + +/// How brightly each item glows when held or dropped. +#[derive(Debug, Default)] +pub struct Luminance(HashMap); + +impl Luminance { + /// A block item glows like its block's default state (`getLightEmission`): torches 14, + /// lanterns and glowstone 15, a lit redstone torch 7; a furnace's item, unlit, not at all. + pub fn new(facts: &BlockFacts, registry: &BlockRegistry) -> Self { + let mut map = HashMap::new(); + for (id, state) in facts.states.iter().enumerate() { + if state.emission == 0 || *state.item != *state.name { + continue; + } + if registry.default_state(&state.name).map(|d| d.0 as usize) == Some(id) { + map.insert(state.item.to_string(), state.emission); + } + } + // A bucket of lava glows as lava does. + map.insert("minecraft:lava_bucket".into(), 15); + Self(map) + } + + pub fn of(&self, item: &str) -> u8 { + self.0.get(item).copied().unwrap_or(0) + } + + #[cfg(test)] + fn from_pairs(pairs: &[(&str, u8)]) -> Self { + Self(pairs.iter().map(|(k, v)| (k.to_string(), *v)).collect()) + } +} + +/// One light this frame: where it is (world space) and its level, 1 to 15. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Source { + pub at: DVec3, + pub level: u8, +} + +/// The [`MAX`] sources nearest `camera` within reach, as the shaders read them: camera-relative +/// position and level. Overwrites `out`. +pub fn select(sources: &[Source], camera: DVec3, out: &mut Vec<[f32; 4]>) { + out.clear(); + let key = |s: &Source| s.at.distance_squared(camera); + let mut near: Vec<&Source> = sources + .iter() + .filter(|s| s.level > 0 && key(s) <= REACH * REACH) + .collect(); + near.sort_by(|a, b| key(a).total_cmp(&key(b))); + out.extend(near.into_iter().take(MAX).map(|s| { + let p = (s.at - camera).as_vec3(); + [p.x, p.y, p.z, f32::from(s.level.min(15))] + })); +} + +/// The block light a vertex at `pos` (camera-relative) gets from `lights`, 0 to 15: the WGSL +/// `dynamic_block_light` in Rust, for tests. +pub fn level_at(pos: [f32; 3], lights: &[[f32; 4]]) -> f32 { + lights.iter().fold(0.0f32, |level, l| { + let d = + ((pos[0] - l[0]).powi(2) + (pos[1] - l[1]).powi(2) + (pos[2] - l[2]).powi(2)).sqrt(); + level.max(l[3] - d) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn nearest_sources_win() { + let camera = DVec3::new(100.0, 64.0, 100.0); + let mut sources: Vec = (0..40) + .map(|i| Source { + at: camera + DVec3::new(f64::from(i), 0.0, 0.0), + level: 14, + }) + .collect(); + sources.push(Source { + at: camera + DVec3::new(0.5, 0.0, 0.0), + level: 0, + }); + sources.push(Source { + at: camera + DVec3::new(0.0, 0.0, 200.0), + level: 15, + }); + let mut out = Vec::new(); + select(&sources, camera, &mut out); + assert_eq!(out.len(), MAX); + assert_eq!(out[0], [0.0, 0.0, 0.0, 14.0]); + assert_eq!(out[MAX - 1][0], (MAX - 1) as f32); + select(&[], camera, &mut out); + assert!(out.is_empty()); + } + + #[test] + fn light_falls_off_a_level_per_block() { + let torch = [[0.0, 0.0, 0.0, 14.0]]; + assert_eq!(level_at([0.0, 0.0, 0.0], &torch), 14.0); + assert_eq!(level_at([3.0, 4.0, 0.0], &torch), 9.0); + assert_eq!(level_at([20.0, 0.0, 0.0], &torch), 0.0); + let two = [[0.0, 0.0, 0.0, 14.0], [10.0, 0.0, 0.0, 15.0]]; + assert_eq!(level_at([8.0, 0.0, 0.0], &two), 13.0); + assert_eq!(level_at([0.0; 3], &[]), 0.0); + } + + #[test] + fn item_luminance() { + let l = Luminance::from_pairs(&[("minecraft:torch", 14)]); + assert_eq!(l.of("minecraft:torch"), 14); + assert_eq!(l.of("minecraft:stone"), 0); + } +} diff --git a/crates/horizon-client/src/enchant.rs b/crates/horizon-client/src/enchant.rs index a988eeb55..039ea658f 100644 --- a/crates/horizon-client/src/enchant.rs +++ b/crates/horizon-client/src/enchant.rs @@ -60,6 +60,7 @@ pub struct ItemProps { /// `minecraft:brewing_fuel` present. pub brewing_fuel: bool, } +#[derive(Default)] pub struct Enchantments { pub list: Vec, index: HashMap, usize>, diff --git a/crates/horizon-client/src/entity.wgsl b/crates/horizon-client/src/entity.wgsl index c6305c697..2c6af26f9 100644 --- a/crates/horizon-client/src/entity.wgsl +++ b/crates/horizon-client/src/entity.wgsl @@ -14,11 +14,13 @@ struct Globals { // Atlas rects (u0, v0, width, height) of end_sky.png and end_portal.png. end_portal_sprites: array, 2>, // x: vanilla's GameTime ((game time % 24000 + partial tick) / 24000) - // y: Nether cardinal lighting. + // y: Nether cardinal lighting, z: how many dynamic_lights are set. time: vec4, crumbling_sprite: vec4, // Selection outline parameters (read by terrain.wgsl). outline_params: vec4, + // Horizon Extras' dynamic lights: camera-relative position and level (dynamic_light.rs). + dynamic_lights: array, 16>, } @group(0) @binding(0) var globals: Globals; @group(0) @binding(1) var atlas: texture_2d; @@ -58,20 +60,33 @@ fn overlay_texel(overlay: u32) -> vec4 { if overlay >= 16u && overlay < 32u { return vec4(1.0, 1.0, 1.0, WHITE_OVERLAY_ALPHA[overlay - 16u]); } return vec4(1.0); } +// Horizon Extras' dynamic lights (dynamic_light.rs): the block light, in the vertex's units +// (16 per level), a vertex at camera-relative `pos` gets from the frame's light sources, one +// level less per block. time.z of them are set: none when the extra is off, so no loop runs. +fn dynamic_block_light(pos: vec3) -> f32 { + let count = min(u32(globals.time.z), 16u); + var level = 0.0; + for (var i = 0u; i < count; i++) { + let l = globals.dynamic_lights[i]; + level = max(level, l.w - distance(pos, l.xyz)); + } + return level * 16.0; +} fn entity_vertex(position: vec3, uv: vec2, overlay: u32, color: vec4, light: vec4, normal: vec4) -> Out { var out: Out; out.clip = globals.view_proj * vec4(position, 1.0); out.proj = vec4(out.clip.xy * 0.5 + out.clip.w * 0.5, out.clip.zw); out.uv = uv; - let l = vec2(f32(light.y), f32(light.x)); + let l = vec2(max(f32(light.y), dynamic_block_light(position)), f32(light.x)); let lm = textureSampleLevel(lightmap, lightmap_sampler, clamp(l / 256.0 + 0.5 / 16.0, vec2(0.5 / 16.0), vec2(15.5 / 16.0)), 0.0); // Celestial bodies, clouds, beacon beams, End portals and breaking cracks are unlit. let unlit = overlay == 2u || overlay == 4u || overlay == 6u || overlay == 9u || overlay == 10u || overlay == 11u || overlay == 12u; out.light_color = select(lm, vec4(1.0), unlit); - // Overlay 6 (beacon beams): the light bytes carry the sprite's v range. + // Overlay 6 (beacon beams): the light bytes carry the sprite's v range; 11 and 12 + // (cracks): the destroy stage sprite's origin. out.wrap = vec2(f32(light.x | (light.y << 8u)), f32(light.z | (light.w << 8u))) / 65535.0; // minecraft_mix_light: the vertex colour times the cardinal light only. var c = color; @@ -147,7 +162,8 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 { var uv = in.uv; if in.overlay == 6u { uv.y = in.wrap.x + fract(in.uv.y) * in.wrap.y; } if in.overlay == 11u || in.overlay == 12u { - uv = globals.crumbling_sprite.xy + fract(in.uv) * globals.crumbling_sprite.zw; + // Each crack's stage sprite origin comes in its light bytes (breaking::stage_light). + uv = in.wrap + fract(in.uv) * globals.crumbling_sprite.zw; } var color = textureSample(atlas, atlas_sampler, uv) * select(in.back_color, in.color, front); if in.overlay == 9u || in.overlay == 10u { @@ -188,3 +204,8 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 { let color = textureSample(atlas, atlas_sampler, in.uv) * in.color * in.light_color; return color; } + +// RenderPipelines.WATER_MASK: depth only (the pipeline masks the colour off). +@fragment fn fs_water_mask() -> @location(0) vec4 { + return vec4(0.0); +} diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index a42bc8ba6..d9cf20db5 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -918,6 +918,43 @@ pub fn item_entity_from_nbt(tag: &Tag, id: u32, bob_offset: f32) -> Option, +) -> Tag { + let base = Base { + id: "minecraft:ominous_item_spawner", + uuid, + position, + motion: Vec3::ZERO, + rotation: [0.0, 0.0], + on_ground: false, + fall_distance: 0.0, + }; + let mut tag = base.tag(raw); + put(&mut tag, "item", item_to_nbt(item)); + put( + &mut tag, + "spawn_item_after_ticks", + Tag::Long(spawn_item_after), + ); + tag +} +/// `OminousItemSpawner.readAdditionalSaveData`: the item, where it floats +/// and `spawn_item_after_ticks` (0 when absent). None without an item: +/// such a spawner would spawn nothing. +pub fn ominous_item_spawner_from_nbt(tag: &Tag) -> Option<(crate::items::ItemStack, Vec3, i64)> { + let item = tag.get("item").and_then(item_from_nbt)?; + let after = number(tag.get("spawn_item_after_ticks")).unwrap_or(0); + Some((item, position(tag)?, after)) +} + /// `ExperienceOrb`: Health, Age, Value, Count. pub fn orb_to_nbt(o: &ExperienceOrb, uuid: [i32; 4]) -> Tag { let base = Base { @@ -1505,6 +1542,38 @@ mod tests { use super::*; use crate::items::ItemStack; + /// The item, the spawn delay and the fields Horizon doesn't model come + /// back; a compound without an item is no spawner. + #[test] + fn ominous_item_spawner_round_trip() { + let item = ItemStack { + item: Arc::from("minecraft:ominous_trial_key"), + count: 1, + damage: 0, + extra: None, + }; + let raw = Tag::compound([("CustomName", string("kept"))]); + let at = Vec3::new(10.5, 64.25, -3.5); + let tag = ominous_item_spawner_to_nbt(&item, at, 97, [1, 2, 3, 4], Some(&raw)); + assert_eq!( + kind(&tag).as_deref(), + Some("minecraft:ominous_item_spawner") + ); + assert_eq!(uuid(&tag), Some([1, 2, 3, 4])); + assert!(matches!( + tag.get("spawn_item_after_ticks"), + Some(Tag::Long(97)) + )); + assert!(tag.get("CustomName").is_some()); + let (back, pos, after) = ominous_item_spawner_from_nbt(&tag).unwrap(); + assert_eq!( + (back.item.as_ref(), back.count), + ("minecraft:ominous_trial_key", 1) + ); + assert_eq!((pos, after), (at, 97)); + assert!(ominous_item_spawner_from_nbt(&raw).is_none()); + } + #[test] fn falling_block_round_trip_keeps_impact_distance_and_settings() { let state = Tag::compound([("Name", string("minecraft:damaged_anvil"))]); diff --git a/crates/horizon-client/src/extras.rs b/crates/horizon-client/src/extras.rs index adbc6e23a..c7be78019 100644 --- a/crates/horizon-client/src/extras.rs +++ b/crates/horizon-client/src/extras.rs @@ -69,6 +69,8 @@ impl Corner { #[derive(Clone, Debug, PartialEq)] pub struct Extras { pub fullbright: bool, + /// Held, dropped and burning light sources light their surroundings (`dynamic_light`). + pub dynamic_lights: bool, pub zoom: bool, /// A vanilla key name (`key.keyboard.z`). pub zoom_key: String, @@ -110,6 +112,7 @@ impl Default for Extras { fn default() -> Self { Self { fullbright: false, + dynamic_lights: false, zoom: false, zoom_key: "key.keyboard.z".into(), zoom_level: 4, @@ -158,6 +161,7 @@ impl Extras { }; match key.trim() { "fullbright" => e.fullbright = flag(e.fullbright), + "dynamicLights" => e.dynamic_lights = flag(e.dynamic_lights), "zoom" => e.zoom = flag(e.zoom), "zoomKey" if value.starts_with("key.") => e.zoom_key = value.to_owned(), "zoomLevel" => { @@ -201,8 +205,9 @@ impl Extras { } pub fn serialize(&self) -> String { format!( - "fullbright:{}\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", bool_text(self.fullbright), + bool_text(self.dynamic_lights), bool_text(self.zoom), self.zoom_key, self.zoom_level, @@ -423,6 +428,7 @@ impl Cps { #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Item { Fullbright, + DynamicLights, Zoom, ZoomKey, ZoomLevel, @@ -452,6 +458,7 @@ pub fn rows() -> Vec> { vec![ Err("Lighting"), Ok(Fullbright), + Ok(DynamicLights), Err("Zoom"), Ok(Zoom), Ok(ZoomKey), @@ -501,6 +508,7 @@ impl Item { pub fn caption(self) -> &'static str { match self { Item::Fullbright => "Fullbright", + Item::DynamicLights => "Dynamic lights", Item::Zoom => "Zoom", Item::ZoomKey => "Zoom key", Item::ZoomLevel => "Starting zoom", @@ -533,7 +541,8 @@ impl Item { KeystrokesCorner | KeystrokesCps => Keystrokes, MouseTweaksWheel => MouseTweaks, SortKey => Sort, - Fullbright | Zoom | Minimap | Fps | Keystrokes | MouseTweaks | Sort | AutoReconnect => { + Fullbright | DynamicLights | Zoom | Minimap | Fps | Keystrokes | MouseTweaks | Sort + | AutoReconnect => { return None; } }) @@ -542,6 +551,9 @@ impl Item { pub fn description(self) -> &'static str { match self { Item::Fullbright => "Show blocks and entities at full light, even in dark areas.", + Item::DynamicLights => { + "Torches and other light sources held, dropped or on fire light the blocks around them." + } Item::Zoom => "Hold the zoom key to zoom; the wheel changes it while held.", Item::ZoomKey => "Click, then press a key. Escape unbinds it.", Item::ZoomLevel => "The zoom the key starts at.", @@ -581,7 +593,7 @@ impl Item { use crate::graphics_style::Cost; match self { Item::Fullbright | Item::Zoom | Item::Fps | Item::Keystrokes => Some(Cost::None), - Item::Minimap => Some(Cost::Low), + Item::Minimap | Item::DynamicLights => Some(Cost::Low), Item::AutoReconnect | Item::MouseTweaks | Item::Sort => Some(Cost::None), _ => None, } @@ -590,6 +602,7 @@ impl Item { pub fn switch(self, e: &Extras) -> Option { Some(match self { Item::Fullbright => e.fullbright, + Item::DynamicLights => e.dynamic_lights, Item::Zoom => e.zoom, Item::ZoomSmooth => e.zoom_smooth, Item::ZoomSensitivity => e.zoom_sensitivity, @@ -632,6 +645,7 @@ impl Item { pub fn cycle(self, e: &mut Extras, back: bool) { match self { Item::Fullbright => e.fullbright = !e.fullbright, + Item::DynamicLights => e.dynamic_lights = !e.dynamic_lights, Item::Zoom => e.zoom = !e.zoom, Item::ZoomSmooth => e.zoom_smooth = !e.zoom_smooth, Item::ZoomSensitivity => e.zoom_sensitivity = !e.zoom_sensitivity, @@ -677,7 +691,7 @@ mod tests { #[test] fn everything_is_off_by_default_and_round_trips() { let d = Extras::default(); - assert!(!d.fullbright); + assert!(!d.fullbright && !d.dynamic_lights); assert!(!d.zoom && !d.fps && !d.keystrokes && !d.minimap && !d.auto_reconnect); assert!(!d.mouse_tweaks && !d.sort); assert_eq!(Extras::parse(""), d); @@ -685,6 +699,9 @@ mod tests { let mut e = d.clone(); Item::Fullbright.cycle(&mut e, false); assert_eq!(Item::Fullbright.switch(&e), Some(true)); + Item::DynamicLights.cycle(&mut e, false); + assert_eq!(Item::DynamicLights.switch(&e), Some(true)); + assert_eq!(Extras::parse(&e.serialize()), e); e.zoom = true; e.zoom_key = "key.keyboard.c".into(); e.zoom_level = 6; diff --git a/crates/horizon-client/src/first_person.rs b/crates/horizon-client/src/first_person.rs index a25d9f537..463d51437 100644 --- a/crates/horizon-client/src/first_person.rs +++ b/crates/horizon-client/src/first_person.rs @@ -21,6 +21,8 @@ pub enum ItemPose { Trident { ticks_used: f32, }, + /// Riptide's spin (`isAutoSpinAttack`): the item held up like a fork. + SpinAttack, Bow { ticks_used: f32, }, @@ -67,6 +69,12 @@ pub fn item_pose(left: bool, inverse_height: f32, attack: f32, pose: ItemPose) - if matches!(pose, ItemPose::Using) { return m; } + if matches!(pose, ItemPose::SpinAttack) { + return m + * Mat4::from_translation(Vec3::new(invert * -0.4, 0.8, 0.3)) + * Mat4::from_rotation_y((invert * 65.0f32).to_radians()) + * Mat4::from_rotation_z((invert * -85.0f32).to_radians()); + } let charging = match pose { ItemPose::Bow { ticks_used } => { let power = ticks_used / 20.0; diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 56d37a3af..18a8d2cc6 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -34,9 +34,11 @@ mod crossbow; mod debug_keys; mod decorated_pot; mod dedicated; +mod deflect; mod dispense_fixture; mod dispenser; mod dragon; +mod dynamic_lights; mod enchant_effects; mod end; mod entity_culling; @@ -72,6 +74,7 @@ mod lan_entities; mod lan_mobs; mod lan_pvp; mod lan_screen; +mod lan_stations; mod lan_trading; mod lan_waypoints; mod leads; @@ -89,6 +92,7 @@ mod mob_gear; mod mods; mod mount_menu; mod mounts; +mod moving_pistons; mod music; mod names; mod natural_spawning; @@ -116,6 +120,7 @@ mod recipe_book; mod remote; mod remote_objects; mod remote_projectiles; +mod remote_stations; mod render_control; mod render_tick; mod respawn_anchor; @@ -267,8 +272,9 @@ struct Options { benchmark: Option, /// `--dev-mod PATH` (repeatable): mods always on and reloaded when rebuilt. dev_mods: Vec, - /// `--server-thread` or `HORIZON_SERVER_THREAD=1`: single player runs on - /// an integrated server thread (game/integrated.rs). + /// Single player runs on an integrated server thread (game/integrated.rs), + /// as vanilla's does: the default. `--no-server-thread` or + /// `HORIZON_SERVER_THREAD=0` runs the world in the frame instead. server_thread: bool, /// Set on the integrated server's own options: it draws nothing, so it skips meshing. integrated: bool, @@ -323,7 +329,10 @@ impl Options { dedicated: None, benchmark: None, dev_mods: Vec::new(), - server_thread: std::env::var("HORIZON_SERVER_THREAD").is_ok_and(|v| v == "1"), + // The command harness (HORIZON_COMMAND_SCRIPT) drives the world + // itself, without the event loop: it stays in the frame. + server_thread: std::env::var("HORIZON_SERVER_THREAD").map_or(true, |v| v != "0") + && std::env::var_os("HORIZON_COMMAND_SCRIPT").is_none(), integrated: false, }; let mut session_file = std::env::var("HORIZON_SESSION_FILE").ok(); @@ -332,7 +341,7 @@ impl Options { match arg.as_str() { "--help" | "-h" => { println!( - "Horizon — Minecraft Java Edition {} in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause.", + "Horizon — Minecraft Java Edition {} in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n --no-server-thread Run single player's world in the frame, not on its server thread\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause.", horizon_core::VANILLA_VERSION ); return Ok(None); @@ -347,6 +356,7 @@ impl Options { "--offscreen" => o.offscreen = true, "--control" => o.control = Some(horizon_client::control::default_path()), "--server-thread" => o.server_thread = true, + "--no-server-thread" => o.server_thread = false, _ => { let value = args .next() @@ -894,6 +904,8 @@ struct WorldRest { behaviours: Behaviours, player_arm: Option, player_type: Option>, + /// `SpinAttackEffectModel` (Riptide's spinning boxes). + spin_attack: Option, stations: horizon_client::stations::StationData, } @@ -969,6 +981,9 @@ impl Resources { fn player_type(&self) -> &Option> { &self.rest().player_type } + fn spin_attack(&self) -> &Option { + &self.rest().spin_attack + } fn stations(&self) -> &horizon_client::stations::StationData { &self.rest().stations } @@ -1136,6 +1151,9 @@ struct Game<'a> { potions: potions::PotionState, scratch_slot: Option, mining: Option, + /// The other players' cracks (`LevelRenderer.destroyingBlocks`): breaker id to the block, + /// the stage (0..=9) and the game time it last changed. + destroying: HashMap, destroy_delay: u32, use_delay: u32, creative: bool, @@ -1174,6 +1192,10 @@ struct Game<'a> { renderer: Option, /// CPU geometry storage retained across frames, including empty/title frames. entity_vertices: Vec, + /// Horizon Extras' dynamic lights this frame (`dynamic_lights.rs`), and how brightly each + /// item glows (built the first time the extra is on). + dynamic_lights: Vec<[f32; 4]>, + luminance: Option, /// Name tags drawn over everything (`RenderPipelines.TEXT_SEE_THROUGH`). see_through_vertices: Vec, started: Instant, @@ -1233,7 +1255,9 @@ struct Game<'a> { /// swap just before an attack keeps them, with the new item's enchantments /// (attribute swapping). attack_item: Option>, - last_hurt_by_player: HashSet, + /// Mobs a player hurt (`LivingEntity.lastHurtByPlayer`), with the guest + /// it was by connection (None: the host). + last_hurt_by_player: HashMap>, /// Mobs whose death (`LivingEntity.die`) has been handled. died: HashSet, /// Client-ticked block-entity animation state (`game/block_entity_anims.rs`). @@ -1393,6 +1417,8 @@ struct Game<'a> { arrow_model: Option, tnts: Vec, hoppers: HashMap<(i32, i32, i32), machines::HopperState>, + /// Where item entities are, while the block entities tick (hoppers). + item_columns: Option, creative_screen: Creative, control: Option, frame_stats: horizon_client::control::FrameStats, @@ -2417,8 +2443,21 @@ impl Game<'_> { b.run_block_events(level, ticks); b.tick_block_entities(level, ticks); }); + self.sync_moving_pistons(); self.process_level_events() } + /// Copies the moving-piston block entities into the world, where the + /// collision queries and the renderer read them. + fn sync_moving_pistons(&mut self) { + let pistons = &mut self.world.moving_pistons; + pistons.clear(); + pistons.extend( + self.block_ticks + .moving_pistons + .iter() + .map(|(p, piston)| ([p.x, p.y, p.z], piston.shape_state())), + ); + } /// `ServerLevel.tick`'s scheduled block then fluid ticks, one at a time: /// the side effects of each (a shrieker summoning a warden, drops, game /// events) happen before the next tick runs, as they do inline in vanilla. @@ -2527,14 +2566,23 @@ impl Game<'_> { 1029 => Some(("minecraft:block.anvil.destroy", 1.0)), 1031 => Some(("minecraft:block.anvil.land", 0.3)), 1505 => Some(("minecraft:item.bone_meal.use", 1.0)), + 1042 => Some(("minecraft:block.grindstone.use", 1.0)), + 1044 => Some(("minecraft:block.smithing_table.use", 1.0)), + // LevelEvent.SOUND_PAGE_TURN (a lectern's page). + 1043 => Some(("minecraft:item.book.page_turn", 1.0)), _ => None, }; if let Some((name, volume)) = sound { - let pitch = if id == 1009 { - 2.6 + (self.world.random.next_float() - self.world.random.next_float()) - * 0.8 - } else { - 1.0 + let pitch = match id { + 1009 => { + 2.6 + (self.world.random.next_float() + - self.world.random.next_float()) + * 0.8 + } + 1029 | 1030 | 1042 | 1043 | 1044 => { + self.world.random.next_float() * 0.1 + 0.9 + } + _ => 1.0, }; self.audio.play(name, c, volume, pitch); } @@ -3763,6 +3811,9 @@ impl Game<'_> { f64::from(z) + 0.5, )); self.level.spawn = Some([f64::from(x), f64::from(y), f64::from(z)]); + // The world's spawn from the start, not only once saved: a bed set + // before the first save must not become it. + self.level.world_spawn.get_or_insert([x, y, z]); } let s = self .level @@ -3884,6 +3935,7 @@ impl Game<'_> { } let riding = self.riding.is_some(); let ghast_collisions = self.happy_ghast_player_collisions(); + let spin_targets = self.spin_targets(); let Some(player) = self.player.as_mut() else { // A dedicated server has no local player: the world still runs. if self.options.dedicated.is_some() { @@ -3961,6 +4013,7 @@ impl Game<'_> { .any(|s| immune.is_some_and(|t| t.contains(&*s.item))); // The dimension's FAST_LAVA: the Nether's lava pushes harder. player.fluids.fast_lava = self.dim == Dim::Nether; + player.spin_targets = spin_targets; let grounded = player.ground.on_ground; let before = ( grounded, @@ -3983,6 +4036,7 @@ impl Game<'_> { } } let events = std::mem::take(&mut player.events); + let spin_hit = player.spin_hit.take(); let glider_wear = std::mem::take(&mut player.glider_wear); if glider_wear > 0 && !self.creative @@ -4001,6 +4055,7 @@ impl Game<'_> { self.eye += (camera_eye.unwrap_or(eye_height) - self.eye) * 0.5; let crouching = player.pose == horizon_client::pose::Pose::Crouching; self.tick_avatar(before, riding); + self.end_spin_attack(spin_hit); self.record_combat(&events); for event in events { match event { @@ -4432,10 +4487,17 @@ impl Game<'_> { }; if capture { self.mouse.set_ignore_first_move(); + // macOS warps by re-associating the mouse with the pointer, + // which undoes a Locked grab and leaves the pointer free: warp + // first there. Wayland moves a pointer only while it is locked, + // so everywhere else warp after grabbing. + #[cfg(target_os = "macos")] + warp(window); self.captured = window .set_cursor_grab(CursorGrabMode::Locked) .or_else(|_| window.set_cursor_grab(CursorGrabMode::Confined)) .is_ok(); + #[cfg(not(target_os = "macos"))] if self.captured && self.focused { warp(window); } @@ -5400,6 +5462,17 @@ impl Game<'_> { .station .as_ref() .is_some_and(|s| s.kind == stations::Kind::Merchant); + let stonecutter_open = self + .station + .as_ref() + .is_some_and(|s| s.kind == stations::Kind::Stonecutter); + let station_kind = self.station.as_ref().map(|s| s.kind); + let grindstone_open = station_kind == Some(stations::Kind::Grindstone); + let cartography_open = station_kind == Some(stations::Kind::Cartography); + let anvil_open = station_kind == Some(stations::Kind::Anvil); + let smithing_open = station_kind == Some(stations::Kind::Smithing); + let enchanting_open = station_kind == Some(stations::Kind::Enchanting); + let beacon_open = station_kind == Some(stations::Kind::Beacon); let (kind, game_of): (Kind, Vec>) = if self.creative_tab_open() { // ItemPickerMenu: the display slots (clicked by the screen), then the hotbar. let mut v = vec![None; 45]; @@ -5426,6 +5499,51 @@ impl Game<'_> { v.push(Some(stations::RESULT)); v.extend((9..36).chain(0..9).map(Some)); (Kind::Loom, v) + } else if stonecutter_open { + // StonecutterMenu: the input, the result, then the inventory. + let mut v = vec![Some(stations::INPUT), Some(stations::RESULT)]; + v.extend((9..36).chain(0..9).map(Some)); + (Kind::Stonecutter, v) + } else if grindstone_open || cartography_open { + // GrindstoneMenu and CartographyTableMenu: the two inputs, the + // result, then the inventory. + let mut v = vec![ + Some(stations::INPUT), + Some(stations::INPUT + 1), + Some(stations::RESULT), + ]; + v.extend((9..36).chain(0..9).map(Some)); + let kind = if grindstone_open { + Kind::Grindstone + } else { + Kind::Cartography + }; + (kind, v) + } else if enchanting_open { + // EnchantmentMenu: the item, the lapis, then the inventory. + let mut v = vec![Some(stations::INPUT), Some(stations::INPUT + 1)]; + v.extend((9..36).chain(0..9).map(Some)); + (Kind::Enchanting, v) + } else if beacon_open { + // BeaconMenu: the payment, then the inventory. + let mut v = vec![Some(stations::INPUT)]; + v.extend((9..36).chain(0..9).map(Some)); + (Kind::Beacon, v) + } else if anvil_open || smithing_open { + // ItemCombinerMenu: the inputs, the result, then the inventory. + let inputs = if anvil_open { 2 } else { 3 }; + let mut v: Vec> = + (0..inputs).map(|i| Some(stations::INPUT + i)).collect(); + v.push(Some(stations::RESULT)); + v.extend((9..36).chain(0..9).map(Some)); + ( + if anvil_open { + Kind::Anvil + } else { + Kind::Smithing + }, + v, + ) } else { let (kind, map) = if self.container.is_some() { let size = self.container_size(); @@ -5508,6 +5626,10 @@ impl Game<'_> { s.loom.patterns.clone(), ) }); + let stone = self + .station + .as_ref() + .map(|s| (s.selected.map_or(-1, |i| i as i32), s.stone.clone())); let crafter_data = match self.container_kind() { Some(BlockEntity::Crafter(c)) => Some((c.disabled, c.triggered)), _ => None, @@ -5521,6 +5643,18 @@ impl Game<'_> { if let Some((s, mob)) = session.as_mut() { self.merchant_sync_in(s, *mob); } + // The cartography table reads and makes the level's maps; a + // server's (the client menu's ContainerLevelAccess.NULL) doesn't. + let level_maps = (kind == Kind::Cartography && self.remote.is_none()).then(|| { + let held: Vec = before + .iter() + .flatten() + .chain(self.inventory.iter().flatten()) + .chain(self.carried.iter()) + .cloned() + .collect(); + self.level_maps(&held) + }); let next_map = if merchant_open { self.peek_map_id() } else { 0 }; let tag = |t: &str| self.structure_tag(t); let maps = trading::GameMaps { @@ -5539,10 +5673,21 @@ impl Game<'_> { recipes: self.res.recipes(), brewing: &self.res.stations().brewing, banners: &self.res.stations().banners, + station_recipes: &self.res.stations().recipes, + enchantments: &self.res.stations().enchantments, + names: &self.pack.names, trade: Some(&trade_env), + maps: level_maps + .as_ref() + .map(|m| m as &dyn horizon_client::menu::Maps), }; menu.creative = creative; menu.selected = self.selected; + menu.levels = self.experience.level; + if anvil_open { + // The rename box as AnvilScreen.onNameChanged gives it to the menu. + menu.anvil.name = self.station.as_ref().map(|s| self.anvil_item_name(s)); + } for (i, stack) in before.iter().enumerate() { menu.set_slot(&env, i, stack.clone()); } @@ -5560,6 +5705,25 @@ impl Game<'_> { menu.loom_patterns = patterns; menu.set_slot(&env, 3, before[3].clone()); } + if kind == Kind::Stonecutter + && let Some((selected, state)) = stone + { + // The same: the list and selection between clicks, then the result. + menu.data[0] = selected; + menu.stone = state; + menu.set_slot(&env, 1, before[1].clone()); + } + if kind == Kind::Enchanting + && let Some(s) = self.station.as_ref() + { + // The offers between clicks (what copying the slots in flagged is not a change). + menu.enchant_changed = false; + for i in 0..3 { + menu.data[i] = s.offers.costs[i]; + menu.data[7 + i] = s.offers.clues[i].as_ref().map_or(-1, |(_, l)| *l as i32); + } + menu.data[3] = self.level.xp_seed; + } if let Some((disabled, triggered)) = crafter_data { for (i, d) in disabled.iter().enumerate() { menu.data[i] = i32::from(*d); @@ -5614,10 +5778,37 @@ impl Game<'_> { s.loom.selected = usize::try_from(menu.data[0]).ok(); s.loom.patterns = std::mem::take(&mut menu.loom_patterns); } - for sound in sounds { - self.loom_sound(sound); + // A server's loom plays its own sounds (the client's menu has no level). + for sound in sounds.into_iter().filter(|_| !predicting) { + self.station_sound(sound); } self.loom_screen_changed(); + } else if kind == Kind::Cartography { + for sound in sounds.into_iter().filter(|_| !predicting) { + self.station_sound(sound); + } + } else if kind == Kind::Stonecutter { + if let Some(s) = self.station.as_mut() { + s.selected = usize::try_from(menu.data[0]).ok(); + s.stone = std::mem::take(&mut menu.stone); + s.stonecutter_changed(); + } + for sound in sounds.into_iter().filter(|_| !predicting) { + self.station_sound(sound); + } + } + if let Some(amount) = menu.ground.take().filter(|_| !predicting) + && let Some(pos) = self.station.as_ref().map(|s| s.pos) + { + self.grindstone_taken(pos, amount); + } + if kind == Kind::Anvil || kind == Kind::Smithing { + self.combiner_session_end(&menu, predicting); + } + if kind == Kind::Enchanting && (menu.enchant_changed || before[0] != menu.slot(0).cloned()) + { + // EnchantmentMenu.slotsChanged: new offers for the item. + self.station_changed(); } if kind == Kind::CrafterBlock && let Some(BlockEntity::Crafter(c)) = self @@ -5645,6 +5836,9 @@ impl Game<'_> { } } self.apply_equipment(); + if let Some(maps) = level_maps { + self.register_made_maps(maps); + } true } /// Number keys, F and Q over a slot of the open menu: SWAP with a hotbar @@ -6468,19 +6662,11 @@ impl Game<'_> { .block_entity_render() .render(&scene, visible, &mut out); } - if let Some(mining) = &self.mining - && mining.progress > 0.0 - && self.gui.atlas.sprites.contains_key(&format!( - "block/destroy_stage_{}", - ((mining.progress * 10.0) as u32).min(9) - )) - { - let state = self - .world - .block(mining.pos[0], mining.pos[1], mining.pos[2]); + for (pos, stage) in self.cracks(camera) { + let state = self.world.block(pos[0], pos[1], pos[2]); self.res .block_entity_render() - .render_breaking(&scene, mining.pos, state.0, &mut out); + .render_breaking(&scene, pos, state.0, stage, &mut out); } } // Experience orbs (ExperienceOrbRenderer): pulsing billboards from a 4x4 icon sheet. @@ -6577,6 +6763,7 @@ impl Game<'_> { vertex.color = horizon_client::hud_layout::multiply(vertex.color, tint); } } + self.moving_piston_geometry(camera, alpha, &mut out); self.tnt_geometry(camera, alpha, &mut out); self.painting_geometry(camera, &mut out); self.frame_geometry(camera, &mut out); @@ -6588,6 +6775,7 @@ impl Game<'_> { self.leash_geometry(camera, alpha, &mut out); self.trident_geometry(camera, alpha, &mut out); self.rocket_geometry(camera, alpha, &mut out); + self.thrown_potion_geometry(camera, alpha, &mut out); // Particles (ParticleEngine.extract): camera-facing quads. let world = &self.world; self.particles.render( @@ -6598,50 +6786,90 @@ impl Game<'_> { &|b| world.light(b[0], b[1], b[2]), &mut out, ); - let atlas = &self.gui.atlas; - // Breaking progress overlay (destroy_stage_0..9). - if let Some(m) = &self.mining - && m.progress > 0.0 - { - let stage = ((m.progress * 10.0) as u32).min(9); - if atlas - .sprites - .contains_key(&format!("block/destroy_stage_{stage}")) + // Breaking progress overlays (destroy_stage_0..9): ours and the other players'. + for (pos, stage) in self.cracks(camera) { + let o = (glam::DVec3::new(f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])) + - camera) + .as_vec3(); + let state = self.world.block(pos[0], pos[1], pos[2]); + if self.res.facts().get(state).render_shape + == horizon_client::blocks::RenderShape::Model + && let Ok(models) = self + .pack + .render + .model_catalog + .collect(state, BlockPos::new(pos[0], pos[1], pos[2])) { - let o = (glam::DVec3::new( - f64::from(m.pos[0]), - f64::from(m.pos[1]), - f64::from(m.pos[2]), - ) - camera) - .as_vec3(); - let state = self.world.block(m.pos[0], m.pos[1], m.pos[2]); - if self.res.facts().get(state).render_shape - == horizon_client::blocks::RenderShape::Model - && let Ok(models) = self - .pack - .render - .model_catalog - .collect(state, BlockPos::new(m.pos[0], m.pos[1], m.pos[2])) - { - let offset = self - .pack - .context - .tables - .offset(state, m.pos[0], m.pos[2]) - .unwrap_or([0.0; 3]); - let origin = o + glam::DVec3::from(offset).as_vec3(); - let translucent = models - .iter() - .any(|(_, model)| model.faces.iter().any(|f| f.translucent)); - for (_, model) in models { - horizon_client::breaking::geometry(model, origin, translucent, &mut out); - } + let offset = self + .pack + .context + .tables + .offset(state, pos[0], pos[2]) + .unwrap_or([0.0; 3]); + let origin = o + glam::DVec3::from(offset).as_vec3(); + let translucent = models + .iter() + .any(|(_, model)| model.faces.iter().any(|f| f.translucent)); + for (_, model) in models { + horizon_client::breaking::geometry(model, origin, translucent, stage, &mut out); } } } out } + /// `LevelRenderer.destroyBlockProgress`: a player's crack on a block (0..=9), or none + /// (any other progress). Cracks not updated for 400 ticks are dropped. + pub(crate) fn destroy_block_progress(&mut self, breaker: i32, pos: [i32; 3], progress: i32) { + let now = self.world.game_time; + self.destroying + .retain(|_, c| now.saturating_sub(c.2) <= 400); + if (0..10).contains(&progress) { + self.destroying.insert(breaker, (pos, progress as u8, now)); + } else { + self.destroying.remove(&breaker); + } + } + + /// The cracks to draw and their stage sprite's atlas origin: our own mining and the + /// other players' (`renderBlockDestroyAnimation`: within 32 blocks of the camera, the + /// furthest progress on each block). + fn cracks(&self, camera: glam::DVec3) -> Vec<([i32; 3], [f32; 2])> { + let mut stages: Vec<([i32; 3], u32)> = Vec::new(); + let mut add = |pos: [i32; 3], stage: u32| match stages.iter_mut().find(|c| c.0 == pos) { + Some(c) => c.1 = c.1.max(stage), + None => stages.push((pos, stage)), + }; + if let Some(m) = &self.mining + && m.progress > 0.0 + { + add(m.pos, ((m.progress * 10.0) as u32).min(9)); + } + let now = self.world.game_time; + for (pos, stage, at) in self.destroying.values() { + if now.saturating_sub(*at) <= 400 { + add(*pos, u32::from(*stage)); + } + } + stages + .into_iter() + .filter(|(pos, _)| { + let d = glam::DVec3::new(f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])) + + 0.5 + - camera; + d.length_squared() <= 1024.0 + }) + .filter_map(|(pos, stage)| { + let r = self + .gui + .atlas + .sprites + .get(&format!("block/destroy_stage_{stage}"))?; + Some((pos, [r.u0, r.v0])) + }) + .collect() + } + fn sky_darken(&self) -> i32 { if self.dim == Dim::Nether { return 11; @@ -6694,7 +6922,13 @@ impl Game<'_> { /// enchantments. pub(super) fn melee_damage(&mut self, target_kind: &str) -> (f32, f32, bool) { let hand_damage = 1.0 + self.attack_item_info().map_or(0.0, |i| i.attack_damage); - let damage = hand_damage + self.effect_attack_bonus(); + // Riptide's spin replaces the attack damage attribute. + let spin = self.player.as_ref().map_or(0.0, |p| p.auto_spin_attack_dmg); + let damage = if spin > 0.0 { + spin + } else { + hand_damage + self.effect_attack_bonus() + }; let scale = self.attack_strength_scale(); let mut amount = damage * (0.2 + scale * scale * 0.8); // Item.getAttackDamageBonus (a mace's smash), before the critical hit. @@ -6791,6 +7025,10 @@ impl Game<'_> { self.break_painting(i, true); return true; } + // A ghast's fireball or a wind charge in front: turned back. + if self.attack_redirectable() { + return true; + } let hand_damage = 1.0 + self .held() @@ -6818,6 +7056,14 @@ impl Game<'_> { return false; } } + self.attack_mob(index); + // Minecraft.startAttack swings after the attack. + self.swing_arm(); + true + } + /// `Player.attack` on a mob: the damage, knockback, sweep, particles and + /// sounds. + pub(super) fn attack_mob(&mut self, index: usize) { let target_kind = self.mobs[index].kind.id.clone(); let target_kind = format!("minecraft:{}", target_kind.trim_start_matches("minecraft:")); let (amount, scale, crit) = self.melee_damage(&target_kind); @@ -6835,7 +7081,6 @@ impl Game<'_> { self.audio .play("minecraft:entity.player.attack.knockback", from, 1.0, 1.0); } - self.swing_arm(); // LivingEntity.setLastHurtMob (tamed wolves join in). self.combat.last_hurt_mob = Some((self.mobs[index].id, self.world.game_time)); let old_health = self.mobs[index].health; @@ -6843,7 +7088,24 @@ impl Game<'_> { Some(f) => self.attack_source(f), None => horizon_client::mobs::Damage::of(horizon_client::mobs::DamageKind::Generic), }; - if self.hurt_by_player(index, amount, source) { + let landed = self.hurt_by_player(index, amount, source); + if let Some(p) = self.player.as_mut() { + if p.attack_log.len() >= 64 { + p.attack_log.remove(0); + } + p.attack_log.push(horizon_client::health::AttackRecord { + game_time: p.health.game_time(), + target: target_kind.clone(), + id: self.mobs[index].id, + killed: landed && !self.mobs[index].alive(), + amount, + scale, + crit, + landed, + dealt: old_health - self.mobs[index].health, + }); + } + if landed { if knockback > 0.0 { let (xd, zd) = self.extra_knockback_direction(); self.mobs[index].knockback(f64::from(knockback), xd, zd); @@ -6882,7 +7144,8 @@ impl Game<'_> { (actual * 0.5) as u32, ); } - self.last_hurt_by_player.insert(self.mobs[index].id); + self.last_hurt_by_player + .insert(self.mobs[index].id, self.lan_acting); let sound = if crit { "minecraft:entity.player.attack.crit" } else if scale > 0.9 { @@ -6910,7 +7173,6 @@ impl Game<'_> { self.audio .play("minecraft:entity.player.attack.nodamage", from, 1.0, 1.0); } - true } /// ServerExplosion: rays from a 16^3 grid lose (resistance + 0.3) * 0.3 per step. /// A mob explosion (`Level.ExplosionInteraction.MOB`: drop decay with the @@ -8410,6 +8672,10 @@ impl Game<'_> { } let shown = self.hands_to_render(); let used_hand = self.used_hand(); + let spinning = self + .player + .as_ref() + .is_some_and(|p| p.auto_spin_attack_ticks > 0); for (i, (hand, item)) in Hand::BOTH .into_iter() .zip(self.visible_hand_items()) @@ -8529,6 +8795,7 @@ impl Game<'_> { ItemPose::Using } } + _ if spinning => ItemPose::SpinAttack, _ => ItemPose::Swing, }; let m = to_world @@ -9349,7 +9616,7 @@ impl Game<'_> { ), }; self.audio - .set_listener([camera.x, camera.y, camera.z], view_yaw); + .set_listener([camera.x, camera.y, camera.z], view_yaw, view_pitch); let block = [ camera.x.floor() as i32, camera.y.floor() as i32, @@ -9581,6 +9848,11 @@ impl Game<'_> { .then(|| self.border_draw(camera.to_array(), alpha as f32)) .flatten(); let see_through = std::mem::take(&mut self.see_through_vertices); + if title { + self.dynamic_lights.clear(); + } else { + self.gather_dynamic_lights(camera, alpha); + } let frame = Frame { shader: self.shader_inputs(camera, alpha as f32), nether_lighting: self.dim == Dim::Nether, @@ -9638,6 +9910,7 @@ impl Game<'_> { color: sky.cloud_color, }), entities: &entities, + dynamic_lights: &self.dynamic_lights, additive: &additive, see_through: &see_through, celestial: if self.settings.horizon.sky || title { @@ -9653,14 +9926,10 @@ impl Game<'_> { game_time: self.world.game_time as f32, shader_game_time: ((self.world.game_time % 24000) as f32 + alpha as f32) / 24000.0, crumbling_sprite: self - .mining - .as_ref() - .and_then(|m| { - self.gui.atlas.sprites.get(&format!( - "block/destroy_stage_{}", - ((m.progress * 10.0) as u32).min(9) - )) - }) + .gui + .atlas + .sprites + .get("block/destroy_stage_0") .map_or([0.0; 4], |r| [r.u0, r.v0, r.u1 - r.u0, r.v1 - r.v0]), end_portal_sprites: ["environment/end_sky", "entity/end_portal/end_portal"].map(|n| { self.gui @@ -10858,6 +11127,10 @@ impl ApplicationHandler for Game<'_> { WindowEvent::RedrawRequested => { self.observe_fullscreen(); let now = Instant::now(); + let frame_cpu = self + .options + .spikes + .and_then(|_| horizon_client::spans::thread_cpu()); let elapsed = now.duration_since(self.previous); self.frame_ticks = elapsed.as_secs_f32() * 20.0; self.previous = now; @@ -10887,6 +11160,8 @@ impl ApplicationHandler for Game<'_> { } let updated = Instant::now(); self.track_toggle_screens(); + // For the "I'm playing" ping: an atomic, sent on when it changes. + horizon_client::heartbeat::set_lan(self.is_published()); let steps = self.clock.advance(elapsed); for _ in 0..steps { let started = Instant::now(); @@ -10924,15 +11199,16 @@ impl ApplicationHandler for Game<'_> { let cpu = now.elapsed().saturating_sub(r.last_wait).as_secs_f32() * 1000.0; let spans = horizon_client::spans::take(); if cpu > threshold { - let list: Vec = spans - .iter() - .filter(|(_, ms)| *ms >= 0.5) - .map(|(n, ms)| format!("{n} {ms:.1}")) - .collect(); + // The render thread's own CPU time in the frame: + // far below the wall time, the frame waited. + let worked = horizon_client::spans::thread_cpu() + .zip(frame_cpu) + .map_or_else(String::new, |(end, start)| { + format!(", cpu {:.1} ms", (end - start).as_secs_f32() * 1000.0) + }); log::info!( - "Horizon: slow frame {cpu:.1} ms ({} ticks): {}", - steps, - list.join(", ") + "Horizon: slow frame {cpu:.1} ms{worked} ({steps} ticks): {}", + horizon_client::spans::describe(&spans) ); } } @@ -11202,6 +11478,7 @@ impl<'a> Game<'a> { potions: Default::default(), scratch_slot: None, mining: None, + destroying: HashMap::new(), destroy_delay: 0, use_delay: 0, creative, @@ -11231,6 +11508,8 @@ impl<'a> Game<'a> { window: None, renderer: None, entity_vertices: Vec::new(), + dynamic_lights: Vec::new(), + luminance: None, see_through_vertices: Vec::new(), health_hud: hud_layout::HealthHud::default(), started: now, @@ -11271,7 +11550,7 @@ impl<'a> Game<'a> { raiding: Default::default(), attack_ticks: 100, attack_item: None, - last_hurt_by_player: HashSet::new(), + last_hurt_by_player: HashMap::new(), died: HashSet::new(), be_anims: { let mut anims = horizon_client::block_entity_anim::BlockEntityAnims::default(); @@ -11381,6 +11660,7 @@ impl<'a> Game<'a> { arrow_model: prepared.arrow_model, tnts: Vec::new(), hoppers: HashMap::new(), + item_columns: None, creative_screen: prepared.creative_screen, control: None, frame_stats: Default::default(), @@ -11976,6 +12256,7 @@ fn load_world_rest( player_type: perspective::player_type(root), player_arm: horizon_client::mobs::load_model(root, "minecraft:player#main") .and_then(|m| m.children.into_iter().find(|c| c.name == "right_arm")), + spin_attack: horizon_client::mobs::load_model(root, "minecraft:spin_attack#main"), }) } @@ -12104,6 +12385,7 @@ fn loading_frame(hud: &HudBatch) -> Frame<'_> { hud, nether_lighting: false, entities: &[], + dynamic_lights: &[], clouds: None, additive: &[], see_through: &[], @@ -12677,9 +12959,26 @@ pub fn run() -> Result<()> { if options.dedicated.is_some() && !dedicated::preflight(&mut options)? { return Ok(()); } - if options.dedicated.is_some() { - // Before any worker starts: on Linux they go behind the server thread. - horizon_threads::put_helpers_behind(); + // Before any worker starts: on Linux they go behind the server thread + // and the render thread. + horizon_threads::put_helpers_behind(); + if options.dedicated.is_none() { + // The render thread, like the server thread, ahead of the workers on + // macOS and Windows. While terrain loads, the worker pools (two with + // single player's server thread) and other programs outnumber the + // cores, and a frame that gave its core up (in a GPU submit) waited + // 10 to 200 ms to get one back. + horizon_threads::favour_current(); + } + // Someone is playing: the anonymous ping behind the launcher's "N playing now". Not for a + // server, a benchmark or a run that quits by itself. + if options.dedicated.is_none() + && options.benchmark.is_none() + && !options.offscreen + && options.frames.is_none() + && options.world_frames.is_none() + { + horizon_client::heartbeat::start(); } let started = Instant::now(); horizon_client::spans::enable(options.spikes.is_some()); diff --git a/crates/horizon-client/src/game/advancements.rs b/crates/horizon-client/src/game/advancements.rs index d13ed6b13..b0f948c5d 100644 --- a/crates/horizon-client/src/game/advancements.rs +++ b/crates/horizon-client/src/game/advancements.rs @@ -91,6 +91,8 @@ pub(super) struct AdvState { /// The tree being read on another thread since the world opened /// (`prefetch_advancement_tree`), taken by the first `advancement_tree`. pub(super) pending_tree: Option>, + /// `inventory_changed`'s criteria by item, built for `tree`. + inventory_index: Option<(Arc, Arc)>, } /// The game's world for predicates. struct View<'a, 'g>(&'a Game<'g>); @@ -229,9 +231,31 @@ impl Game<'_> { _ => Tree::load(&self.options.resources.join("data")), }; self.adv.tree = Arc::new(tree); + // With the tree, while the world loads: built on the first + // inventory change it cost that tick ~10 ms. + self.inventory_index(); } self.adv.tree.clone() } + /// `inventory_changed`'s criteria by item, for the tree in place. + fn inventory_index(&mut self) -> Arc { + let tree = self.adv.tree.clone(); + if let Some((built, index)) = &self.adv.inventory_index + && Arc::ptr_eq(built, &tree) + { + return index.clone(); + } + let items = self.res.items(); + let index = Arc::new(adv::InventoryIndex::build(&tree, |tag| { + items + .item_tags + .get(tag) + .map(|t| t.iter().map(String::as_str).collect()) + .unwrap_or_default() + })); + self.adv.inventory_index = Some((tree, index.clone())); + index + } /// Start reading the advancement files on another thread while the world /// loads. The first tick's first criterion trigger used to read and parse /// all of them on the game thread (about 60 ms). @@ -394,6 +418,16 @@ impl Game<'_> { let Some(list) = tree.by_trigger.get(name) else { return; }; + self.trigger_criteria(&tree, list, test); + } + /// `trigger` for some of a trigger's criteria: (advancement, criterion) + /// indexes in `tree`, in tree order. + fn trigger_criteria( + &mut self, + tree: &Tree, + list: &[(usize, usize)], + test: impl Fn(&Value, &dyn adv::World) -> bool, + ) { let mut hits = Vec::new(); { let view = View(self); @@ -437,9 +471,14 @@ impl Game<'_> { } else { self.recipe_toast(unlocked); } + if unlocked.is_empty() || self.remote.is_some() || self.no_player_here() { + return; + } + self.load_advancements(); + let tree = self.adv.tree.clone(); for r in unlocked { - let r = r.clone(); - self.trigger("minecraft:recipe_unlocked", move |c, _| { + let list = tree.recipe_criteria(r); + self.trigger_criteria(&tree, &list, |c, _| { c["recipes"].as_str() == Some(r.as_str()) }); } @@ -560,7 +599,15 @@ impl Game<'_> { .is_some_and(|i| s.count >= i.max_stack) }) .count() as f64; - self.trigger("minecraft:inventory_changed", move |c, w| { + // Only the criteria the items held could pass (`InventoryIndex`). + if self.remote.is_some() || self.no_player_here() { + return; + } + self.load_advancements(); + let tree = self.adv.tree.clone(); + let index = self.inventory_index(); + let list = index.candidates(stacks.iter().map(|s| s.id.as_str())); + self.trigger_criteria(&tree, &list, move |c, w| { let slots = &c["slots"]; let range = |k: &str, v: f64| { let r = &slots[k]; @@ -965,10 +1012,8 @@ impl Game<'_> { }); positions.push((a.x, a.y)); } - let mut tree = Tree { - list, - ..Tree::default() - }; + let mut tree = Tree::default(); + tree.list = list; for (i, a) in tree.list.iter().enumerate() { tree.by_id.insert(a.id.clone(), i); } diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 5d7d294dd..9a5cd6a58 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -1840,11 +1840,21 @@ impl Game<'_> { if self.ticks < *report_tick && !timed_out { return None; } - let after = pos.map(|p| self.block_json(p)); let changed = match (*pos, *before) { (Some(p), Some(b)) => self.world.block(p[0], p[1], p[2]) != b, _ => false, }; + // A client of a server (single player's server thread, a LAN + // guest) sees the block once the server's answer comes. + if *place + && !changed + && self.remote.is_some() + && self.ticks < *report_tick + 20 + && !timed_out + { + return None; + } + let after = pos.map(|p| self.block_json(p)); let used = delta(inventory, &self.inventory_counts()); let mut v = json!({ "ok": !*place || changed, diff --git a/crates/horizon-client/src/game/allays.rs b/crates/horizon-client/src/game/allays.rs index 52dfa7e1c..bed835663 100644 --- a/crates/horizon-client/src/game/allays.rs +++ b/crates/horizon-client/src/game/allays.rs @@ -9,18 +9,28 @@ impl Game<'_> { pub(super) fn tick_allays(&mut self) { let griefing = self.ui.rules.bool("mob_griefing"); let player = self.player.as_ref().map(|p| p.position); + // The playing jukeboxes, found at the first allay: no allay starts + // or stops one, and the block entities run into the thousands. + let mut jukeboxes: Option> = None; for i in 0..self.mobs.len() { if self.mobs[i].species() != Species::Allay || !self.mobs[i].alive() { continue; } let pos = self.mobs[i].position; // Dancing: a playing jukebox within 10 blocks. - let dancing = self.world.block_entities.iter().any(|(k, e)| { - matches!(e, BlockEntity::Jukebox(j) if j.playing) - && (f64::from(k.0) + 0.5 - pos.x).powi(2) - + (f64::from(k.1) + 0.5 - pos.y).powi(2) - + (f64::from(k.2) + 0.5 - pos.z).powi(2) - <= 100.0 + let jukeboxes = jukeboxes.get_or_insert_with(|| { + self.world + .block_entities + .iter() + .filter(|(_, e)| matches!(e, BlockEntity::Jukebox(j) if j.playing)) + .map(|(k, _)| *k) + .collect() + }); + let dancing = jukeboxes.iter().any(|k| { + (f64::from(k.0) + 0.5 - pos.x).powi(2) + + (f64::from(k.1) + 0.5 - pos.y).powi(2) + + (f64::from(k.2) + 0.5 - pos.z).powi(2) + <= 100.0 }); self.mobs[i].extra.flag = dancing && !horizon_client::mobs::goals::should_panic(&self.mobs[i]); diff --git a/crates/horizon-client/src/game/beacon.rs b/crates/horizon-client/src/game/beacon.rs index 79cf14541..c8a0bcba6 100644 --- a/crates/horizon-client/src/game/beacon.rs +++ b/crates/horizon-client/src/game/beacon.rs @@ -15,6 +15,7 @@ use horizon_client::{ mesher::Vertex, mobs::render::{DYE, DYE_NAMES}, }; +use horizon_protocol::packets::play::{self, Serverbound as S}; /// The beacon screen is 54 px wider than the 176-px menus it shares an origin with. pub(super) const SHIFT: f32 = -27.0; @@ -35,9 +36,6 @@ const PAYMENT: [&str; 5] = [ "minecraft:diamond", "minecraft:netherite_ingot", ]; -pub(super) fn is_payment(item: &str) -> bool { - PAYMENT.contains(&item) -} /// `BeaconMenu.PaymentSlot` and the player inventory, relative to the 176 origin. pub(super) fn slot_position(i: usize) -> Option<(f32, f32)> { Some(match i { @@ -171,7 +169,7 @@ impl Game<'_> { } } } - fn beacon_sound(&mut self, p: [i32; 3], sound: &str) { + pub(super) fn beacon_sound(&mut self, p: [i32; 3], sound: &str) { let at = [ f64::from(p[0]) + 0.5, f64::from(p[1]) + 0.5, @@ -255,9 +253,13 @@ impl Game<'_> { } } fn beacon_levels(&self) -> i32 { - let Some(pos) = self.station.as_ref().map(|s| s.pos) else { + let Some(s) = self.station.as_ref() else { return 0; }; + if let Some(levels) = s.beacon_levels { + return levels; + } + let pos = s.pos; match self.world.block_entities.get(&(pos[0], pos[1], pos[2])) { Some(BlockEntity::Beacon(b)) => b.levels, _ => 0, @@ -346,8 +348,16 @@ impl Game<'_> { self.screen = super::Screen::Playing; self.capture(true); } - /// `BeaconMenu.updateEffects`: spend the payment and set the powers. + /// `BeaconMenu.updateEffects`: spend the payment and set the powers. On + /// a server, `BeaconScreen`'s confirm button sends them + /// (`ServerboundSetBeaconPacket`) and the server's menu does it. fn confirm_beacon(&mut self, sel: [Option; 2]) { + if self.remote.is_some() { + let id = |e: Option| e.and_then(|e| self.remote_effect_network_id(EFFECTS[e].0)); + let (primary, secondary) = (id(sel[0]), id(sel[1])); + self.send(S::SetBeacon(play::SetBeacon { primary, secondary })); + return; + } let Some(s) = self.station.as_mut() else { return; }; diff --git a/crates/horizon-client/src/game/block_entity_ticks.rs b/crates/horizon-client/src/game/block_entity_ticks.rs index bb1cadd15..094aed6ef 100644 --- a/crates/horizon-client/src/game/block_entity_ticks.rs +++ b/crates/horizon-client/src/game/block_entity_ticks.rs @@ -24,6 +24,7 @@ impl Game<'_> { let ticking = self.block_ticking_area(); let mut spawners = Vec::new(); let mut trial_spawners = Vec::new(); + self.item_columns = Some(Default::default()); for slot in self.world.block_entity_tickers() { let pos = slot.0; // Ticks before this one can remove it (`TickingBlockEntity.isRemoved`). @@ -56,6 +57,8 @@ impl Game<'_> { _ => {} } } + // Items move between passes: the columns hold for this one only. + self.item_columns = None; self.update_song_volumes(); self.scan_for_hearts(); // The client ticks (particles, sounds, the turning mob) are for a diff --git a/crates/horizon-client/src/game/boats.rs b/crates/horizon-client/src/game/boats.rs index f9740598e..433c588d0 100644 --- a/crates/horizon-client/src/game/boats.rs +++ b/crates/horizon-client/src/game/boats.rs @@ -141,6 +141,8 @@ pub(super) fn boat_wood(item: &str) -> Option<&str> { pub(super) struct BoatModels { pub models: HashMap, pub chest_models: HashMap, + /// `ModelLayers.BOAT_WATER_PATCH`, shared by every boat (not rafts). + pub water_patch: Option, } impl BoatModels { /// Whether a boat of this wood (with or without a chest) can be drawn. @@ -175,6 +177,7 @@ impl BoatModels { Self { models, chest_models, + water_patch: document.and_then(|d| d.model("minecraft:boat#water_patch")), } } } @@ -785,6 +788,23 @@ impl Game<'_> { 0, out, ); + // BoatRenderer.submitTypeAdditions: the water patch hides the water + // inside the hull unless the boat is under water (RaftRenderer has none). + if let Some(patch) = self.boat_models.water_patch.as_ref() + && &*b.wood != "bamboo" + && !matches!(b.status, Status::UnderWater | Status::UnderFlowingWater) + { + horizon_client::mobs::render::draw( + patch, + base, + &Poses::new(patch), + uv, + 0xFFFF_FFFF, + packed, + horizon_client::gfx::WATER_MASK_OVERLAY, + out, + ); + } self.cull_entity_vertices(out, entity_start); } } diff --git a/crates/horizon-client/src/game/books.rs b/crates/horizon-client/src/game/books.rs index 3dd49c005..ccc1c6e19 100644 --- a/crates/horizon-client/src/game/books.rs +++ b/crates/horizon-client/src/game/books.rs @@ -9,6 +9,7 @@ use horizon_client::{ hud::{HudBatch, rgba}, item_data::WrittenBook, items::ItemStack, + menu::{Kind, Menu}, text::Text, ui, }; @@ -89,6 +90,17 @@ impl Game<'_> { self.capture(false); } pub(super) fn close_book(&mut self) { + // A server's lectern: LecternScreen's menu closes (closeContainer). + if matches!( + self.book, + Some(BookScreen::View { + lectern: Some(_), + .. + }) + ) && self.remote.is_some() + { + self.remote_close_container(); + } self.book = None; self.capture(true); } @@ -319,38 +331,25 @@ impl Game<'_> { } } Some(BookScreen::View { - pages, - page, - lectern, - }) => { - let before = *page; + lectern: Some(key), .. + }) => lectern_page = Some(*key), + Some(BookScreen::View { pages, page, .. }) => { if forward && *page + 1 < pages.len() { *page += 1; } else if !forward && *page > 0 { *page -= 1; } - if *page != before - && let Some(pos) = *lectern - { - lectern_page = Some((pos, *page)); - } } None => return, } + // LecternScreen's page buttons click the menu's (1 back, 2 forward); + // the page turns with the server's data slot and level event 1043. + if let Some(key) = lectern_page { + self.lectern_button(key, if forward { 2 } else { 1 }); + return; + } self.audio .play("minecraft:item.book.page_turn", None, 1.0, 1.0); - if let Some((pos, page)) = lectern_page { - self.set_lectern_page(pos, page as i32); - } - } - /// `LecternBlockEntity.setPage` and `LecternBlock.signalPageChange`. - fn set_lectern_page(&mut self, key: (i32, i32, i32), page: i32) { - if let Some(BlockEntity::Lectern(l)) = self.world.block_entities.get_mut(&key) { - l.page = page; - } - self.set_lectern_powered(key, true); - self.lectern_pulses.push((key, 2)); - self.container_changed(key); } fn set_lectern_powered(&mut self, key: (i32, i32, i32), powered: bool) { self.set_lectern_property(key, "powered", powered); @@ -380,6 +379,7 @@ impl Game<'_> { } /// The 2-tick pulses of turned lecterns. pub(super) fn tick_lecterns(&mut self) { + self.follow_lectern(); let mut done = Vec::new(); for (key, left) in &mut self.lectern_pulses { *left -= 1; @@ -452,6 +452,7 @@ impl Game<'_> { .or_else(|| data.map(|d| d.writable_pages.clone())) .unwrap_or_default(); let page = (l.page.max(0) as usize).min(pages.len().saturating_sub(1)); + self.stats.custom("interact_with_lectern", 1); self.open_book(BookScreen::View { pages, page, @@ -459,24 +460,189 @@ impl Game<'_> { }); true } - /// `LecternMenu` "Take Book". - fn take_lectern_book(&mut self, key: (i32, i32, i32)) { - let book = match self.world.block_entities.get_mut(&key) { - Some(BlockEntity::Lectern(l)) => { - l.page = 0; - l.book.take() + /// A `LecternMenu` button of the open lectern screen: on a server it is + /// sent (`handleInventoryButtonClick`); here the lectern's menu takes it + /// with the player's inventory, and the screen follows the block entity. + fn lectern_button(&mut self, key: (i32, i32, i32), id: i32) { + if self.remote.is_some() { + if let Some((container, _)) = self.remote.as_ref().and_then(|r| r.menu.as_ref()) { + self.send( + horizon_protocol::packets::play::Serverbound::ContainerButtonClick( + horizon_protocol::packets::play::ContainerButtonClick { + container: *container, + button: id, + }, + ), + ); } - _ => None, - }; - if let Some(book) = book - && let Some(rest) = self.give(book) - && let Some(eye) = self.eye_position() - { - self.spawn_item(rest, [eye[0], eye[1] - 0.3, eye[2]], [0.0, 0.1, 0.0], 40); + return; + } + let Some(mut menu) = self.lectern_menu(key) else { + return; + }; + for i in 0..36 { + menu.set_player_item(i, self.inventory[i].clone()); + } + menu.set_player_item(40, self.offhand.clone()); + menu.creative = self.creative; + menu.selected = self.selected; + menu.may_build = self.may_build(); + if !menu.button(&self.menu_env(), id) { + return; + } + for i in 0..36 { + self.inventory[i] = menu.player_item(i).cloned(); + } + self.offhand = menu.player_item(40).cloned(); + for stack in std::mem::take(&mut menu.dropped) { + self.player_drop(stack); + } + self.lectern_menu_done(key, &menu); + self.follow_lectern(); + } + /// The `book` control command: a button of the open book or lectern + /// screen (the page arrows, Take Book, Done), then its page. + pub(super) fn book_control( + &mut self, + action: Option<&str>, + ) -> horizon_client::Result { + let lectern = match &self.book { + Some(BookScreen::View { lectern, .. }) => *lectern, + Some(BookScreen::Edit { .. }) => None, + None => return Err("no book is open".into()), + }; + match action { + None => {} + Some("next") => self.turn_page(true), + Some("back") => self.turn_page(false), + Some("take") => match lectern { + Some(key) => self.lectern_button(key, 3), + None => return Err("not a lectern".into()), + }, + Some("done") => self.close_book(), + Some(other) => return Err(format!("unknown book button {other}").into()), + } + Ok(match &self.book { + Some(BookScreen::View { + pages, + page, + lectern, + }) => serde_json::json!({ + "page": page, "pages": pages.len(), "lectern": lectern.map(|k| [k.0, k.1, k.2]), + }), + Some(BookScreen::Edit { pages, page, .. }) => { + serde_json::json!({ "page": page, "pages": pages.len(), "lectern": null }) + } + None => serde_json::json!({ "closed": true }), + }) + } + /// A server's `minecraft:lectern` menu: LecternScreen, its book and + /// page to come (`remote_lectern_book`, `remote_lectern_page`). + pub(super) fn remote_open_lectern(&mut self, key: (i32, i32, i32)) { + self.open_book(BookScreen::View { + pages: Vec::new(), + page: 0, + lectern: Some(key), + }); + } + /// `LecternScreen.bookChanged`: the menu's book slot. + pub(super) fn remote_lectern_book(&mut self, book: Option) { + if let Some(BookScreen::View { + lectern: Some(_), + pages, + page, + }) = self.book.as_mut() + { + let data = book.as_ref().and_then(ItemStack::data); + *pages = data + .and_then(|d| d.written.as_ref().map(|w| w.pages.clone())) + .or_else(|| data.map(|d| d.writable_pages.clone())) + .unwrap_or_default(); + *page = (*page).min(pages.len().saturating_sub(1)); + } + } + /// `LecternScreen.pageChanged`: the menu's page data slot. + pub(super) fn remote_lectern_page(&mut self, value: i32) { + if let Some(BookScreen::View { + lectern: Some(_), + pages, + page, + }) = self.book.as_mut() + { + *page = (value.max(0) as usize).min(pages.len().saturating_sub(1)); + } + } + /// The server closed its lectern menu; false when none is open. + pub(super) fn remote_lectern_closed(&mut self) -> bool { + if !matches!( + self.book, + Some(BookScreen::View { + lectern: Some(_), + .. + }) + ) { + return false; + } + if let Some(r) = self.remote.as_mut() { + r.menu = None; + r.menu_title = None; + } + self.book = None; + self.capture(true); + true + } + /// `LecternMenu` over the lectern at `key` (the menu engine, for the + /// local player and LAN guests alike): its book and page. + pub(super) fn lectern_menu(&self, key: (i32, i32, i32)) -> Option { + let Some(BlockEntity::Lectern(l)) = self.world.block_entities.get(&key) else { + return None; + }; + let mut menu = Menu::new(Kind::Lectern); + menu.set_slot(&self.menu_env(), 0, l.book.clone()); + menu.data[0] = l.page; + Some(menu) + } + /// The lectern menu's book and page back in the block entity: a new page + /// is `LecternBlock.signalPageChange` (the 2-tick pulse, level event + /// 1043), a book gone `onBookItemRemove` (`resetBookState`). + pub(super) fn lectern_menu_done(&mut self, key: (i32, i32, i32), menu: &Menu) { + let Some(BlockEntity::Lectern(l)) = self.world.block_entities.get_mut(&key) else { + return; + }; + let (had, before) = (l.book.is_some(), l.page); + l.book = menu.slot(0).cloned(); + l.page = menu.data[0]; + if had && l.book.is_none() { + self.set_lectern_powered(key, false); + self.set_lectern_property(key, "has_book", false); + self.container_changed(key); + } else if menu.data[0] != before { + self.set_lectern_powered(key, true); + self.lectern_pulses.push((key, 2)); + self.level_event_at(1043, [key.0, key.1, key.2], 0); + self.container_changed(key); + } + } + /// The open lectern screen follows its block entity (`LecternScreen`'s + /// menu listener): the page, and closing once the book is gone. + pub(super) fn follow_lectern(&mut self) { + let Some(BookScreen::View { + lectern: Some(key), + page, + pages, + }) = self.book.as_mut() + else { + return; + }; + if self.remote.is_some() { + return; + } + match self.world.block_entities.get(key) { + Some(BlockEntity::Lectern(l)) if l.book.is_some() => { + *page = (l.page.max(0) as usize).min(pages.len().saturating_sub(1)); + } + _ => self.close_book(), } - self.set_lectern_property(key, "has_book", false); - self.container_changed(key); - self.close_book(); } pub(super) fn book_click(&mut self, size: [u32; 2]) { let b = HudBatch::new(size); @@ -537,7 +703,8 @@ impl Game<'_> { self.close_book(); } else if inside(w / 2.0 + 2.0, 196.0, 98.0, 20.0) { click(self); - self.take_lectern_book(key); + // LecternScreen's Take Book: the menu's button 3. + self.lectern_button(key, 3); } } else if inside((w - 200.0) / 2.0, 196.0, 200.0, 20.0) { click(self); diff --git a/crates/horizon-client/src/game/cartography.rs b/crates/horizon-client/src/game/cartography.rs index 4a5738f6e..b8b57666a 100644 --- a/crates/horizon-client/src/game/cartography.rs +++ b/crates/horizon-client/src/game/cartography.rs @@ -1,70 +1,80 @@ -//! The cartography table (`CartographyTableMenu`, `CartographyTableScreen`): -//! zooming a map out with paper, cloning it with an empty map, locking it -//! with a glass pane, the post-processing on take (`MapItem.scaleMap`, -//! `lockMap`) and the preview with its error and lock sprites. +//! The cartography table (`CartographyTableMenu` on the menu engine, +//! `CartographyTableScreen`): zooming a map out with paper, cloning it with +//! an empty map, locking it with a glass pane. The engine reads the level's +//! maps through `LevelMaps`; the scaled and locked copies a take makes +//! (`MapItem.scaleMap`, `lockMap`) are registered after the click. The +//! screen draws the preview with its error and lock sprites. use super::{ Game, maps::{MapData, map_id}, - stations::Station, }; -use horizon_client::{hud::HudBatch, items::ItemStack}; +use horizon_client::{hud::HudBatch, items::ItemStack, menu::Maps}; +use std::{ + cell::{Cell, RefCell}, + collections::HashMap, +}; + +/// The level's maps as a menu sees them (`ContainerLevelAccess`): the +/// states of the maps the click can reach, and the copies it makes. +pub(super) struct LevelMaps { + states: RefCell>, + next_id: Cell, + /// (new id, source id, scaled) for each copy made. + made: RefCell>, +} + +impl Maps for LevelMaps { + fn state(&self, id: i32) -> Option<(bool, u8)> { + self.states.borrow().get(&id).copied() + } + + fn derive(&self, id: i32, scale: bool) -> Option { + let (_, s) = self.state(id)?; + let new = self.next_id.get(); + self.next_id.set(new + 1); + let made = if scale { + (false, (s + 1).min(4)) + } else { + (true, s) + }; + self.states.borrow_mut().insert(new, made); + self.made.borrow_mut().push((new, id, scale)); + Some(new) + } +} impl Game<'_> { - /// `setupResultSlot`. - pub(super) fn cartography_result(&self, s: &Station) -> Option { - let (map, extra) = (s.inputs[0].as_ref()?, s.inputs[1].as_ref()?); - let data = self.maps.data.get(&map_id(map)?)?; - match &*extra.item { - "minecraft:paper" if !data.locked && data.scale < 4 => Some(ItemStack { - count: 1, - ..map.clone() - }), - "minecraft:glass_pane" if !data.locked => Some(ItemStack { - count: 1, - ..map.clone() - }), - "minecraft:map" => Some(ItemStack { - count: 2, - ..map.clone() - }), - _ => None, + /// The maps of `stacks` (loaded as needed) for a menu over this level. + pub(super) fn level_maps<'s>( + &mut self, + stacks: impl IntoIterator, + ) -> LevelMaps { + let ids: Vec = stacks.into_iter().filter_map(map_id).collect(); + let mut states = HashMap::new(); + for id in ids { + if let Some(m) = self.map(id) { + states.insert(id, (m.locked, m.scale)); + } + } + LevelMaps { + states: RefCell::new(states), + next_id: Cell::new(self.peek_map_id()), + made: RefCell::new(Vec::new()), } } - /// `onCraftedPostProcess` for the taken result: a scaled or locked copy - /// under a new map id. Also spends the inputs' extra item kind check. - pub(super) fn cartography_post(&mut self, mut result: ItemStack) -> ItemStack { - let extra = self - .station - .as_ref() - .and_then(|s| s.inputs[1].as_ref()) - .map(|e| e.item.clone()); - let Some(id) = map_id(&result) else { - return result; - }; - let new = match extra.as_deref() { - Some("minecraft:paper") => self.map(id).map(|m| m.scaled()), - Some("minecraft:glass_pane") => self.map(id).map(|m| m.locked_copy()), - _ => None, - }; - if let Some(data) = new { - let new_id = self.new_map_id(data); - result.data_mut().map_id = Some(new_id); + + /// The scaled and locked copies a menu made (`level.setMapData`). + pub(super) fn register_made_maps(&mut self, maps: LevelMaps) { + for (id, source, scale) in maps.made.into_inner() { + let Some(data) = self + .map(source) + .map(|m| if scale { m.scaled() } else { m.locked_copy() }) + else { + continue; + }; + let new = self.new_map_id(data); + debug_assert_eq!(new, id, "map ids follow peek_map_id"); } - result - } - /// The take sound (once per tick). - pub(super) fn cartography_taken(&mut self, pos: [i32; 3]) { - let at = [ - f64::from(pos[0]) + 0.5, - f64::from(pos[1]) + 0.5, - f64::from(pos[2]) + 0.5, - ]; - self.audio.play( - "minecraft:ui.cartography_table.take_result", - Some(at), - 1.0, - 1.0, - ); } /// `CartographyTableScreen.extractBackground` after the background. pub(super) fn draw_cartography(&mut self, batch: &mut HudBatch, ox: f32, oy: f32) { diff --git a/crates/horizon-client/src/game/combat.rs b/crates/horizon-client/src/game/combat.rs index da3851d9a..70ae082aa 100644 --- a/crates/horizon-client/src/game/combat.rs +++ b/crates/horizon-client/src/game/combat.rs @@ -25,6 +25,9 @@ pub(super) struct CombatTracker { pub(super) last_hurt_mob: Option<(u32, i64)>, /// The mob whose projectile is hitting the player now. pub(super) projectile_owner: Option, + /// The projectile hitting the player now is another player's that + /// `ServerPlayer.canHarmPlayer` refuses (the `pvp` rule, an ally). + pub(super) refuse_player_hit: bool, /// The mob exploding now (`ServerExplosion.source`): its team's friendly /// fire decides whom the blast may hurt. pub(super) explosion_source: Option, diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index b970414a6..f174f98c1 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -1612,11 +1612,16 @@ impl Game<'_> { { return Err(err("commands.summon.failed.peaceful", &[])); } - let Some(target) = self.summon_with_nbt(&format!("minecraft:{short}"), pos, &nbt)? - else { - return Err(err("commands.summon.failed", &[])); + let before = self.spawned_mark(); + let name = match self.summon_with_nbt(&format!("minecraft:{short}"), pos, &nbt)? { + Some(target) => self.target_name(target), + // Spawned as a kind no command target stands for (primed + // TNT, falling blocks, projectiles): its type's name. + None if self.spawned_mark() != before => { + Text::translate(&format!("entity.minecraft.{short}"), &[]) + } + None => return Err(err("commands.summon.failed", &[])), }; - let name = self.target_name(target); self.feedback(Text::translate("commands.summon.success", &[name])); return Ok(1); } @@ -1669,16 +1674,31 @@ impl Game<'_> { } // SummonCommand.createEntity: any other type from an empty compound. _ => { - let Some(target) = self.summon_with_nbt(&kind, pos, "{}")? else { - return Err(err("commands.summon.failed", &[])); + let before = self.spawned_mark(); + name = match self.summon_with_nbt(&kind, pos, "{}")? { + Some(target) => self.target_name(target), + // Spawned as a kind no command target stands for + // (primed TNT, falling blocks, projectiles). + None if self.spawned_mark() != before => { + Text::translate(&format!("entity.minecraft.{short}"), &[]) + } + None => return Err(err("commands.summon.failed", &[])), }; - name = self.target_name(target); } } } self.feedback(Text::translate("commands.summon.success", &[name])); Ok(1) } + /// What changes when an entity spawns, kinds that take their id only + /// when first tracked (primed TNT, falling blocks, projectiles) + /// included: a summon compares it before and after. + fn spawned_mark(&self) -> (u32, usize) { + ( + self.next_entity, + self.tnts.len() + self.falling.len() + self.creatures.projectiles.len(), + ) + } /// BlockStateArgument -> registry state. pub(super) fn block_state(&self, b: &BlockInput) -> R { let state = horizon_world::chunk::BlockState { diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 0d172387d..6fc456f8d 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -24,6 +24,7 @@ const HELP: &[&str] = &[ "time TICKS set the time of day", "summon KIND [X Y Z] [baby] spawn a mob (in front of the player without a position)", "mobs [RADIUS] list mobs near the player with their AI state", + "hurtlog the hurts taken and melee attacks made since the last call, per player (host and guests)", "fill X1 Y1 Z1 X2 Y2 Z2 BLOCK set a box of loaded blocks", "resume leave the pause menu", "screenshot PATH write the next frame as PNG", @@ -469,6 +470,10 @@ impl Game<'_> { let radius: f64 = words.get(1).map_or(Ok(64.0), |r| r.parse())?; Ok(Some(self.control_mobs(radius))) } + "hurtlog" => { + self.require_world()?; + Ok(Some(self.control_hurt_log())) + } "resume" => { if self.screen == Screen::Paused { self.screen = Screen::Playing; @@ -518,13 +523,22 @@ impl Game<'_> { Screen::Inventory if self.recipe_search_focused() => { self.recipe_text(Some(text), false) } + // The anvil's rename box. + Screen::Inventory + if self + .station + .as_ref() + .is_some_and(|s| s.kind == super::stations::Kind::Anvil) => + { + self.station_text(Some(text), false) + } Screen::Creative if self.creative_screen.tab().search => { // As typed: replaces a selected query, keeps the length limit. self.creative_search_edit(Some(text), false) } _ => { return Err( - "type needs the chat screen (key t tap), the language search, the creative search or World Options".into(), + "type needs the chat screen (key t tap), the language search, the creative search, the anvil or World Options".into(), ); } } @@ -661,7 +675,7 @@ impl Game<'_> { "dragon-hurt" => { // Test hook: damage the dragon's head as the player would. let amount: f32 = arg(1)?.parse()?; - self.hit_special(super::dragon::SPECIAL, amount, true); + self.hit_special(super::dragon::SPECIAL, amount, true, false); ok() } "quit" => { @@ -726,6 +740,54 @@ impl Game<'_> { } } + /// The hurts and melee attacks each player logged since the last call + /// (`PlayerMotion::hurt_log`, `attack_log`), taken out. + fn control_hurt_log(&mut self) -> Value { + fn drain( + name: &str, + hurt_log: &mut Vec, + attack_log: &mut Vec, + ) -> Value { + let hurts: Vec = hurt_log + .drain(..) + .map(|r| { + json!({ + "t": r.game_time, "source": r.source, "amount": r.amount, + "blocked": r.blocked, "taken": r.taken, "hurt": r.hurt, + "armor": r.armor, "toughness": r.toughness, "health": r.health, + "fire_ticks": r.fire_ticks, "knockback": r.knockback, + }) + }) + .collect(); + let attacks: Vec = attack_log + .drain(..) + .map(|r| { + json!({ + "t": r.game_time, "target": r.target, "id": r.id, "killed": r.killed, "amount": r.amount, + "scale": r.scale, "crit": r.crit, "landed": r.landed, "dealt": r.dealt, + }) + }) + .collect(); + json!({ "name": name, "hurts": hurts, "attacks": attacks }) + } + let mut players = Vec::new(); + if let Some(p) = self.player.as_mut() { + players.push(drain("host", &mut p.hurt_log, &mut p.attack_log)); + } + if let Some(host) = self.lan.as_mut() { + for g in &mut host.hub.guests { + let name = g.name.clone(); + if let Some(m) = g.motion.as_mut() { + players.push(drain(&name, &mut m.hurt_log, &mut m.attack_log)); + } else if let Some((mut hurts, mut attacks)) = g.logs_kept.take() { + // Dead, not yet respawned: what its last body logged. + players.push(drain(&name, &mut hurts, &mut attacks)); + } + } + } + json!({ "ok": true, "players": players }) + } + fn control_status(&self) -> Value { let player = self.player.as_ref().map(|p| { json!({ @@ -788,6 +850,12 @@ impl Game<'_> { "pending_observations": self.lod_observe.len(), "refined_samples": self.lod.as_ref().map_or(0, |lod| lod.refined_samples()), }); + // The other players' cracks this client draws (LevelRenderer.destroyingBlocks). + let destroying: Vec<_> = self + .destroying + .iter() + .map(|(id, (pos, stage, _))| json!({ "id": id, "pos": pos, "stage": stage })) + .collect(); let mut status = json!({ "screen": self.screen_name(), "debug": { @@ -820,14 +888,16 @@ impl Game<'_> { "tridents": self.tridents.len(), "rockets": self.rockets.len(), "fight": self.dragon_status(), - "carts": self.carts.iter().map(|c| serde_json::json!({"kind": c.kind.id(), "position": [c.position.x, c.position.y, c.position.z], "velocity": [c.velocity.x, c.velocity.y, c.velocity.z]})).collect::>(), + // A client of a server (single player's server thread) knows the + // carts it was sent. + "carts": self.remote_carts().unwrap_or_else(|| self.carts.iter().map(|c| serde_json::json!({"kind": c.kind.id(), "position": [c.position.x, c.position.y, c.position.z], "velocity": [c.velocity.x, c.velocity.y, c.velocity.z]})).collect::>()), "riding": self.riding, "using": self.using, "render_distance": self.streaming.radius, "chunks": self.world.chunks.len(), "mobs": self.mobs.len(), "block_entities": self.world.block_entities.len(), - "pending_chunks": self.streaming.pending() + self.pending_uploads.len(), + "pending_chunks": self.streaming.pending() + self.pending_uploads.len() + self.remote_backlog(), "generated_chunks": self.streaming.generated_total, "meshed_sections": self.streaming.meshed_total, "streaming": self.streaming.stages().into_iter().map(|(k, v)| (k.to_string(), v.into())).collect::>(), @@ -851,7 +921,9 @@ impl Game<'_> { status["lod"]["target_tiles"] = target.into(); status["lod"]["sampled_target_tiles"] = sampled.into(); status["pending_uploads"] = self.pending_uploads.len().into(); + status["destroying"] = json!(destroying); status["physical_keys"] = json!(physical_keys); + status["heard"] = json!(self.audio.heard); // Boats, minecarts, armor stands, item frames and paintings. status["objects"] = json!(self.objects_status()); // Primed TNT, falling blocks, projectiles, tridents and end crystals. diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index baf968729..08bcb0acb 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -3,6 +3,7 @@ //! breeding, conversions, drops), projectiles, player interactions //! (feeding, shearing, milking, spawn eggs, throwing) and rendering. use super::{Dim, Game, view_vector}; +use horizon_assets::item_model::DisplayContext; use horizon_client::{ Result, arrows::EntityHit, @@ -389,6 +390,7 @@ impl Game<'_> { player, others, others_grid: None, + others_index: None, daylight: self.dim != Dim::Nether && self.sky_darken() < 4, game_time: self.world.game_time, day_time: self.world.day_time, @@ -401,7 +403,7 @@ impl Game<'_> { end: self.dim == Dim::End, world_seed: self.level.seed, sea_level: if self.dim == Dim::Nether { 32 } else { 63 }, - teams: self.mob_teams(), + teams: std::sync::Arc::new(self.mob_teams()), items: Some(self.res.items()), difficulty: self.local_difficulty( self.player @@ -502,9 +504,22 @@ impl Game<'_> { let mut keep = Vec::with_capacity(mobs.len()); let mut grid = horizon_client::mobs::seen_grid::SeenGrid::new(snapshot.iter().map(|s| s.bounds)); + // All but the snapshot is the same for every mob of the tick, so + // build it once: the player view and the teams scan every UUID. + let base = self.mob_world_base(&[]); + // Each mob keeps its snapshot slot all tick; the first slot of an + // id answers, as a scan would. + let mut index = horizon_client::fast_hash::FxHashMap::::default(); + for (i, s) in snapshot.iter().enumerate() { + index.entry(s.id).or_insert(i as u32); + } for i in 0..mobs.len() { - let mut w = self.mob_world_base(&snapshot); - w.others_grid = Some(&grid); + let mut w = MobWorld { + others: &snapshot, + others_grid: Some(&grid), + others_index: Some(&index), + ..base.clone() + }; let m = &mut mobs[i]; w.nearest_player = super::natural_spawning::nearest_player( &players, @@ -588,7 +603,11 @@ impl Game<'_> { if let Some(host) = self.lan.as_mut() && !guests.is_empty() { - bindings.retain(|id, _| mobs.iter().any(|m| m.id == *id)); + // A set: a scan of every mob for each binding is quadratic, and a + // server's loaded mobs run into the thousands. + let live: horizon_client::fast_hash::FxHashSet = + mobs.iter().map(|m| m.id).collect(); + bindings.retain(|id, _| live.contains(id)); host.mob_players = bindings; } self.mobs.append(&mut mobs); @@ -622,7 +641,8 @@ impl Game<'_> { } /// LivingEntity.die / dropAllDeathLoot. fn mob_died(&mut self, m: &Mob) { - let by_player = self.last_hurt_by_player.remove(&m.id) || m.ai.last_hurt_by_player > 0; + let killer = self.last_hurt_by_player.remove(&m.id); + let by_player = killer.is_some() || m.ai.last_hurt_by_player > 0; let mut dying = m.clone(); // LivingEntity.die: the death is heard, and a sculk catalyst nearby // takes the experience (before the loot is dropped). @@ -636,11 +656,22 @@ impl Game<'_> { } }); if by_player { - self.stats.add("killed", &m.kind.id, 1); - self.stats.custom("mob_kills", 1); - self.score_player_killed(super::commands::Target::Mob(m.id)); - let view = self.mob_entity(m); - self.trigger_entity("minecraft:player_killed_entity", "entity", &view); + // A guest's kill is theirs: their statistics, scores and + // advancements (LivingEntity.die credits lastHurtByPlayer). + let guest = killer.flatten().filter(|_| self.lan_acting.is_none()); + let credited = guest.is_some_and(|conn| { + let Some(mut host) = self.lan.take() else { + return false; + }; + let done = self + .as_guest(&mut host, conn, |g| g.credit_kill(m)) + .is_some(); + self.lan = Some(host); + done + }); + if !credited { + self.credit_kill(m); + } } self.score_entity_removed(m.id); self.raider_died(m, by_player); @@ -675,6 +706,15 @@ impl Game<'_> { } } } + /// The killer's side of a mob's death: `ServerPlayer.awardKillScore`'s + /// statistics and scores, and the `player_killed_entity` trigger. + fn credit_kill(&mut self, m: &Mob) { + self.stats.add("killed", &m.kind.id, 1); + self.stats.custom("mob_kills", 1); + self.score_player_killed(super::commands::Target::Mob(m.id)); + let view = self.mob_entity(m); + self.trigger_entity("minecraft:player_killed_entity", "entity", &view); + } /// `dropAllDeathLoot` through `mobs::drops`: the entity loot table from the /// world's random sequence, equipment by drop chance, species extras and /// the experience orbs, spawned in order. @@ -1393,7 +1433,8 @@ impl Game<'_> { from: [f64; 3], damage_type: &str, ) -> bool { - if self.creative { + // ServerPlayer.canHarmPlayer refused another player's projectile. + if self.creative || self.combat.refuse_player_hit { return false; } let projectile = self @@ -1442,6 +1483,11 @@ impl Game<'_> { { let (xd, zd) = (from[0] - player.position.x, from[2] - player.position.z); self.knock_back_player(f64::from(0.4_f32), xd, zd); + if let Some(p) = self.player.as_mut() + && let Some(r) = p.hurt_log.last_mut() + { + r.knockback = Some([p.velocity.x, p.velocity.y, p.velocity.z]); + } self.hurt_armor(amount); self.thorns(from); } @@ -1626,14 +1672,30 @@ impl Game<'_> { w: &w, targets: targets_guests, }; + let guest_entities = self.lan_guest_entities(); projectiles.retain_mut(|p| { let mob_shot = !matches!(p.owner, Some(Who::Player)); - let (keep, hit) = match (p.arrow.is_some(), mob_shot) { + // A player's arrows, snowballs and eggs meet every player; a + // guest's flies from that guest (Projectile.getOwner), not + // from the host, until it has left them. + let pvp = !mob_shot && super::lan_pvp::meets_players(&p.kind); + let shooter = p + .guest + .filter(|_| pvp) + .and_then(|c| guest_entities.iter().find(|(g, _)| *g == c)) + .map(|&(_, id)| Who::Mob(id)); + if shooter.is_some() { + p.owner = shooter; + } + let (keep, hit) = match (p.arrow.is_some(), mob_shot || pvp) { (true, false) => horizon_client::arrows::tick(p, &scene, &arrow_targets), (true, true) => horizon_client::arrows::tick(p, &scene, &arrow_targets_guests), (false, false) => p.tick(&pw), (false, true) => p.tick(&pw_guests), }; + if shooter.is_some() { + p.owner = Some(Who::Player); + } if let Some(a) = p.arrow.as_mut() { arrow_events.extend(a.events.drain(..).map(|e| (p.position, e))); } @@ -1685,6 +1747,11 @@ impl Game<'_> { } self.creatures.projectiles.append(&mut projectiles); for (p, hit) in hits { + // A player's arrow on another player lands as the victim's hurt. + if let Some(victim) = self.projectile_pvp_victim(&p, hit) { + self.projectile_hits_player(&p, hit, victim)?; + continue; + } // A guest's projectile lands as theirs: a pearl takes them, what // it hurts answers to them. One hitting the host (`Who::Player` // here) stays the host's hit. @@ -1879,12 +1946,30 @@ impl Game<'_> { } = hit && id >= super::dragon::SPECIAL { + let by_player = p.owner == Some(Who::Player); + if let ProjectileKind::Arrow { .. } = p.kind { + // AbstractArrow.onHitEntity: spent if the part or crystal took + // it, else turned back (a perched dragon sets it alight first). + let mut arrow = p.clone(); + let amount = arrow_damage(&mut arrow, &mut self.world.random) + p.bonus.damage; + let outcome = match self.hit_special(id, amount, by_player, true) { + super::dragon::Hurt::Landed { .. } => EntityHit::Hurt, + super::dragon::Hurt::Refused => EntityHit::Refused, + super::dragon::Hurt::Shrugged => { + if let Some(a) = arrow.arrow.as_mut() { + a.ignite_for_seconds(1.0); + } + EntityHit::Refused + } + }; + self.finish_arrow_hit(arrow, outcome); + return Ok(()); + } let amount = match p.kind { - ProjectileKind::Arrow { .. } => p.arrow_damage(&mut self.world.random), ProjectileKind::SmallFireball | ProjectileKind::LargeFireball { .. } => 6.0, _ => 0.0, }; - self.hit_special(id, amount, p.owner == Some(Who::Player)); + self.hit_special(id, amount, by_player, false); return Ok(()); } if let ( @@ -1950,7 +2035,7 @@ impl Game<'_> { .find(|m| m.id == id) .is_some_and(|m| m.damage(amount, source)); if p.owner == Some(Who::Player) { - self.last_hurt_by_player.insert(id); + self.last_hurt_by_player.insert(id, self.lan_acting); } hurt } @@ -2040,15 +2125,22 @@ impl Game<'_> { let from = pl.position; self.spawn_mob("minecraft:endermite", [from.x, from.y, from.z], false); } + // To where the pearl started its last tick (oldPosition). + let to = p.previous; if let Some(pl) = self.player.as_mut() { - pl.position = at; + pl.position = to; pl.velocity = Vec3::ZERO; pl.fall_distance = 0.0; + pl.teleported = true; } - self.previous_position = at; + self.previous_position = to; self.hurt_player_by("minecraft:ender_pearl", 5.0); - self.audio - .play("minecraft:entity.player.teleport", Some(atp), 1.0, 1.0); + self.audio.play( + "minecraft:entity.player.teleport", + Some([to.x, to.y, to.z]), + 1.0, + 1.0, + ); } } (ProjectileKind::SmallFireball, hit) => match hit { @@ -2075,15 +2167,21 @@ impl Game<'_> { } }, Hit::Block { pos, face, .. } => { + // SmallFireball.onHitBlock: a mob's only with mobGriefing; + // BaseFireBlock.getState placed with updates (the fire + // ticks, ages and goes out where it can't stay). let fire = [pos[0] + face[0], pos[1] + face[1], pos[2] + face[2]]; - if self - .res - .facts() - .is_air(self.world.block(fire[0], fire[1], fire[2])) - && let Some(state) = - self.pack.assets.registry.default_state("minecraft:fire") + let mob = matches!(p.owner, Some(Who::Mob(_))); + if (!mob || self.ui.rules.bool("mob_griefing")) + && self + .res + .facts() + .is_air(self.world.block(fire[0], fire[1], fire[2])) { - self.world.set(fire[0], fire[1], fire[2], state)?; + let at = BlockPos::new(fire[0], fire[1], fire[2]); + let state = + self.with_level(|b, level, ticks| b.fire_state_for(level, ticks, at)); + self.level_set(fire, state)?; } } Hit::None => {} @@ -3035,6 +3133,14 @@ impl Game<'_> { } continue; } + if let Some(stack) = a.potion_item() { + let owner = super::item_draw::owner_at(at, 0.0, "minecraft:splash_potion"); + let state = self.resolve_item(&stack, DisplayContext::Ground, Some(&owner), 0); + let pose = glam::Mat4::from_translation(c) + * glam::Mat4::from_quat(self.camera_orientation()); + self.submit_item_world(&state, pose, packed, out); + continue; + } let Some(name) = a.item_sprite() else { continue; }; diff --git a/crates/horizon-client/src/game/deflect.rs b/crates/horizon-client/src/game/deflect.rs new file mode 100644 index 000000000..a08de87b3 --- /dev/null +++ b/crates/horizon-client/src/game/deflect.rs @@ -0,0 +1,155 @@ +//! A player's blow at a ghast's fireball or a wind charge +//! (`#minecraft:redirectable_projectile`): `Player.attack` turns it with +//! `ProjectileDeflection.AIM_DEFLECT` instead of hurting anything. It flies on +//! along the player's view and is the player's now (`Projectile.deflect` +//! sets the owner), so a ghast it meets dies of it (`Ghast.isReflectedFireball`). +use super::{Game, ray_box, view_vector}; +use horizon_client::{ + mobs::Who, + projectiles::{Projectile, ProjectileKind}, +}; +use horizon_core::geometry::{Aabb, Vec3}; + +/// `AbstractHurtingProjectile.getPickRadius`: the crosshair finds it a block +/// round its box. +const PICK_RADIUS: f64 = 1.0; + +/// `#minecraft:redirectable_projectile`: a ghast's fireball and both wind charges. +pub(super) fn redirectable(p: &Projectile) -> bool { + !p.stuck + && matches!( + p.kind, + ProjectileKind::LargeFireball { .. } + | ProjectileKind::WindCharge + | ProjectileKind::BreezeWindCharge + ) +} + +/// Its box for the crosshair: the entity's (a fireball 1 x 1, a wind charge +/// 0.3125, from its feet up) grown by the pick radius. +fn pick_box(p: &Projectile) -> Aabb { + let size = match p.kind { + ProjectileKind::LargeFireball { .. } => 1.0, + _ => 0.3125, + }; + let half = size / 2.0 + PICK_RADIUS; + Aabb::new( + Vec3::new( + p.position.x - half, + p.position.y - PICK_RADIUS, + p.position.z - half, + ), + Vec3::new( + p.position.x + half, + p.position.y + size + PICK_RADIUS, + p.position.z + half, + ), + ) +} + +impl Game<'_> { + /// The redirectable projectile under the crosshair within the attack + /// reach, and how far along the view it is. + pub(super) fn redirectable_hit(&self) -> Option<(usize, f64)> { + let eye = self.eye_position()?; + let dir = view_vector(self.yaw, self.pitch); + let reach: f64 = if self.creative { 5.0 } else { 3.0 }; + self.creatures + .projectiles + .iter() + .enumerate() + .filter(|(_, p)| redirectable(p)) + .filter_map(|(i, p)| ray_box(eye, dir, reach, pick_box(p)).map(|t| (i, t))) + .min_by(|a, b| a.1.total_cmp(&b.1)) + } + + /// `Player.attack` on a redirectable projectile nearer than any mob or + /// block in view: `AIM_DEFLECT` (its movement the unit view vector), the + /// player its owner, its acceleration power back to 0.1 + /// (`onDeflection` by an attack), and the no-damage sound. True when a + /// projectile was turned. + pub(super) fn attack_redirectable(&mut self) -> bool { + let Some((i, t)) = self.redirectable_hit() else { + return false; + }; + if self.mob_hit().is_some_and(|(_, d)| d < t) { + return false; + } + if let (Some(hit), Some(eye)) = (self.pick(), self.eye_position()) { + let d = (0..3) + .map(|a| (hit.point[a] - eye[a]).powi(2)) + .sum::() + .sqrt(); + if d < t { + return false; + } + } + self.deflect(i); + true + } + + /// `Player.canInteractWithEntity(box, 3.0)` as the server checks an + /// attack packet: the projectile's box within the reach plus 3 of the eyes. + pub(super) fn within_interaction_range(&self, i: usize) -> bool { + let (Some(eye), Some(p)) = (self.eye_position(), self.creatures.projectiles.get(i)) else { + return false; + }; + let b = pick_box(p); + let (lo, hi) = (b.min_position(), b.max_position()); + let (lo, hi) = ( + [lo.x + PICK_RADIUS, lo.y + PICK_RADIUS, lo.z + PICK_RADIUS], + [hi.x - PICK_RADIUS, hi.y - PICK_RADIUS, hi.z - PICK_RADIUS], + ); + let d2: f64 = (0..3) + .map(|a| (eye[a] - eye[a].clamp(lo[a], hi[a])).powi(2)) + .sum(); + let range = if self.creative { 5.0 } else { 3.0 } + 3.0; + d2 < range * range + } + + /// `Projectile.deflect(AIM_DEFLECT, player, player, true)`. + pub(super) fn deflect(&mut self, i: usize) { + let dir = view_vector(self.yaw, self.pitch); + let guest = self.lan_acting; + let p = &mut self.creatures.projectiles[i]; + p.velocity = Vec3::new(dir[0], dir[1], dir[2]); + p.yaw = dir[0].atan2(dir[2]).to_degrees() as f32; + p.pitch = dir[1].atan2(dir[0].hypot(dir[2])).to_degrees() as f32; + p.owner = Some(Who::Player); + // On a server, the guest who struck it (their projectile now). + p.guest = guest; + // Not into the one who turned it on its way out. + p.left_owner = false; + self.reset_attack_strength(); + self.swing_arm(); + let from = self + .player + .as_ref() + .map(|p| [p.position.x, p.position.y, p.position.z]); + self.audio + .play("minecraft:entity.player.attack.nodamage", from, 1.0, 1.0); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_ghast_fireballs_and_wind_charges_are_redirectable() { + let at = Vec3::new(0.0, 64.0, 0.0); + let large = Projectile::fireball( + ProjectileKind::LargeFireball { power: 1 }, + at, + None, + [1.0, 0.0, 0.0], + ); + let small = Projectile::fireball(ProjectileKind::SmallFireball, at, None, [1.0, 0.0, 0.0]); + assert!(redirectable(&large)); + assert!(!redirectable(&small)); + // The pick box: a block round the fireball's 1 x 1 box. + let b = pick_box(&large); + assert_eq!(b.min_position().x, -1.5); + assert_eq!(b.max_position().y, 66.0); + } +} diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs index db3f523bc..b4e358d50 100644 --- a/crates/horizon-client/src/game/dispenser.rs +++ b/crates/horizon-client/src/game/dispenser.rs @@ -317,7 +317,11 @@ impl Game<'_> { .cloned() } /// The same block with other properties (`withProperty`). - fn with_props(&self, state: BlockStateId, props: &[(&str, &str)]) -> Option { + pub(super) fn with_props( + &self, + state: BlockStateId, + props: &[(&str, &str)], + ) -> Option { let mut s = self.pack.assets.registry.state(state)?.clone(); for (k, v) in props { s.properties.insert((*k).to_owned(), (*v).to_owned()); diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index d2413e45b..222e59229 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -37,6 +37,10 @@ pub(super) struct Fight { exit_portal: Option<[i32; 3]>, alive_crystals: i32, crystal_scan: i32, + /// `ticksSinceLastPlayerScan`, and whether the last scan found a player + /// for the fight (`dragonEvent.getPlayers()` is not empty). + player_scan: i32, + players: bool, /// The spikes' crystals have been placed (worldgen does not place entities here). crystals_placed: bool, /// The respawn sequence (`DragonRespawnStage`) and its tick count. @@ -112,6 +116,8 @@ enum Phase { path: Option, target: Option, clockwise: bool, + /// `attackTarget`: the player it strafes. + player: Option, }, LandingApproach { path: Option, @@ -178,6 +184,7 @@ impl Phase { path: None, target: None, clockwise: false, + player: None, }, 2 => Self::LandingApproach { path: None, @@ -239,6 +246,9 @@ impl Phase { } } pub(super) struct Dragon { + /// `Entity.id` once tracked to guests (0 before); its parts take the + /// eight ids after it (`EnderDragon`'s constructor reserves them). + pub id: u32, pub position: Vec3, pub previous: Vec3, velocity: Vec3, @@ -247,7 +257,10 @@ pub(super) struct Dragon { yaw_accel: f32, pub health: f32, pub hurt_time: i32, + /// `LivingEntity.damageCooldownTime` and `lastHurt`: within the window + /// only damage above the last hit lands, and only the excess. invulnerable: i32, + last_hurt: f32, pub death_time: i32, pub flap: f32, pub old_flap: f32, @@ -264,8 +277,78 @@ pub(super) struct Dragon { pub parts: [(Vec3, Vec3); 8], nodes: Option<[[i32; 3]; 24]>, nearest_crystal: Option, + /// A crystal destroyed while it held its pattern (taken on its next tick). + strafe_request: Option, random: LegacyRandom, } +/// A player in the fight: the window's own player, or a guest by +/// connection (a LAN or server player). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum FightWho { + Host, + Guest(u32), +} +/// A player in the End as the dragon sees it. +#[derive(Clone, Copy, Debug)] +struct FightPlayer { + who: FightWho, + position: Vec3, + bounds: Aabb, + alive: bool, + creative: bool, + spectator: bool, +} +impl FightPlayer { + /// `Player.canBeSeenAsEnemy`: alive, neither creative nor spectator. + fn enemy(&self) -> bool { + self.alive && !self.creative && !self.spectator + } +} +/// `TargetingConditions.forCombat` (visibility aside) in +/// `Level.getNearestPlayer`: the enemy nearest `at` among `players`, within +/// `range` of the dragon at `from` and passing `selector`; none on Peaceful. +fn nearest_enemy( + players: &[FightPlayer], + peaceful: bool, + at: Vec3, + range: Option<(Vec3, f64)>, + selector: impl Fn(&FightPlayer) -> bool, +) -> Option { + if peaceful { + return None; + } + players + .iter() + .filter(|p| p.enemy() && selector(p)) + .filter(|p| range.is_none_or(|(from, r)| p.position.distance_squared(from) <= r * r)) + .min_by(|a, b| { + a.position + .distance_squared(at) + .total_cmp(&b.position.distance_squared(at)) + }) + .copied() +} +/// Whom a destroyed crystal sends a holding dragon after +/// (`DragonHoldingPatternPhase.onCrystalDestroyed`). +#[derive(Clone, Copy, Debug)] +enum StrafeRequest { + /// The player who destroyed it. + Player(FightWho), + /// Anything else: the player nearest the crystal. + Nearest(Vec3), +} +/// What `EnderDragon.hurt` made of a hit. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum Hurt { + /// It returned true; `full` when it was a new hit, not just the excess + /// over the last one (the hurt sound and animation). + Landed { full: bool }, + /// It returned false (dying, too little damage). + Refused, + /// A perched dragon's `onHurt` took an arrow's damage away (and set the + /// arrow alight for a second). + Shrugged, +} const PART_SIZES: [(f64, f64); 8] = [ (1.0, 1.0), (3.0, 3.0), @@ -284,6 +367,7 @@ const ADJACENCY: [u32; 24] = [ impl Dragon { fn new(position: Vec3, yaw: f32, seed: i64) -> Self { Self { + id: 0, position, previous: position, velocity: Vec3::ZERO, @@ -293,6 +377,7 @@ impl Dragon { health: MAX_HEALTH, hurt_time: 0, invulnerable: 0, + last_hurt: 0.0, death_time: 0, flap: 0.0, old_flap: 0.0, @@ -311,6 +396,7 @@ impl Dragon { parts: [(position, position); 8], nodes: None, nearest_crystal: None, + strafe_request: None, random: LegacyRandom::new(seed), } } @@ -341,6 +427,103 @@ impl Dragon { Vec3::new(p.x + w / 2.0, p.y + h, p.z + w / 2.0), ) } + /// `EnderDragon.hurt(part, source, damage)`: whether the hit landed + /// (an arrow is spent, else it turns back). `counts` is + /// `source.getEntity() instanceof Player` or a damage type that always + /// hurts dragons (explosions); `arrow` a direct arrow or wind charge, + /// which a perched dragon shrugs off (`AbstractDragonSittingPhase.onHurt`). + fn hurt(&mut self, part: usize, damage: f32, counts: bool, arrow: bool) -> Hurt { + if matches!(self.phase, Phase::Dying { .. }) || !self.alive() { + return Hurt::Refused; + } + if arrow && self.phase.sitting() { + return Hurt::Shrugged; + } + let mut damage = damage; + if part != 0 && part != 1 { + damage = damage / 4.0 + damage.min(1.0); + } + if damage < 0.01 { + return Hurt::Refused; + } + if !counts { + return Hurt::Landed { full: false }; + } + let before = self.health; + // LivingEntity.hurtServer: within the cooldown only what exceeds the last hit. + let full = if self.invulnerable > 10 { + if damage <= self.last_hurt { + return Hurt::Landed { full: false }; + } + self.health -= damage - self.last_hurt; + self.last_hurt = damage; + false + } else { + self.last_hurt = damage; + self.invulnerable = 20; + self.health -= damage; + self.hurt_time = 10; + true + }; + if self.health <= 0.0 { + if self.phase.sitting() { + self.health = 0.0; + } else { + // handleKillingBlow: dying flight first. + self.health = 1.0; + self.set_phase(Phase::Dying { + target: None, + time: 0, + }); + } + } + if self.phase.sitting() { + self.sitting_damage += before - self.health.max(0.0); + if self.sitting_damage > 0.25 * MAX_HEALTH { + self.sitting_damage = 0.0; + self.set_phase(Phase::Takeoff { + first: true, + path: None, + target: None, + }); + } + } + Hurt::Landed { full } + } + /// `ServerExplosion.hurtEntities` on the dragon: the dragon itself (its + /// body takes it), then each part, in `Level.getEntities` order, each by + /// its distance and how much of its box the blast sees (`exposure`). + fn explosion_hits( + &self, + center: [f64; 3], + radius: f32, + exposure: impl Fn(Aabb) -> f32, + ) -> Vec<(usize, f32)> { + let diameter = f64::from(radius * 2.0); + let dist = |p: Vec3| { + ((p.x - center[0]).powi(2) + (p.y - center[1]).powi(2) + (p.z - center[2]).powi(2)) + .sqrt() + / diameter + }; + let p = self.position; + let whole = Aabb::new( + Vec3::new(p.x - 8.0, p.y, p.z - 8.0), + Vec3::new(p.x + 8.0, p.y + 8.0, p.z + 8.0), + ); + std::iter::once((2, p, whole)) + .chain((0..8).map(|i| (i, self.parts[i].0, self.part_box(i)))) + .filter_map(|(part, at, b)| { + let d = dist(at); + (d <= 1.0).then(|| { + let pow = (1.0 - d) * f64::from(exposure(b)); + ( + part, + ((pow * pow + pow) / 2.0 * 7.0 * diameter + 1.0) as f32, + ) + }) + }) + .collect() + } fn set_phase(&mut self, phase: Phase) { if self.phase.id() == phase.id() && phase.id() != 1 { return; @@ -422,6 +605,8 @@ impl Game<'_> { Some(Tag::IntArray(v)) if v.len() == 3 => Some([v[0], v[1], v[2]]), _ => None, }, + // The first tick scans for players. + player_scan: 21, ..Default::default() }; if fight.gateways.is_empty() { @@ -495,47 +680,129 @@ impl Game<'_> { fn arena_loaded(&self) -> bool { (-2..=1).all(|cz| (-2..=1).all(|cx| self.streaming.is_lit(cx, cz))) } - /// `EnderDragonFight.tick` while the player is in the End. + /// The player acting now: the guest whose turn it is, else the host. + fn acting_player(&self) -> FightWho { + self.lan_acting.map_or(FightWho::Host, FightWho::Guest) + } + /// The players in the level the dragon sees (`level.players()`): the + /// window's own, then every guest in the level. + fn fight_players(&self) -> Vec { + let mut out = Vec::new(); + if let Some(p) = self.player.as_ref() { + out.push(FightPlayer { + who: FightWho::Host, + position: p.position, + bounds: p.bounds(), + alive: !p.health.dead_or_dying(), + creative: self.creative, + spectator: self.spectator(), + }); + } + if let Some(h) = self.lan.as_ref() { + for g in h.hub.guests.iter().filter(|g| h.hub.here(g) && g.loaded) { + let [x, y, z] = g.position; + out.push(FightPlayer { + who: FightWho::Guest(g.conn), + position: Vec3::new(x, y, z), + bounds: super::lan_mobs::guest_bounds(g), + alive: !g.dead, + creative: g.creative(), + spectator: g.spectator(), + }); + } + } + out + } + /// Run `f` as the fight's player `who` (a guest's turn, its knockback + /// sent to its client). + fn as_fight_player(&mut self, who: FightWho, f: impl FnOnce(&mut Self)) { + match who { + FightWho::Host => f(self), + FightWho::Guest(conn) => { + let Some(mut host) = self.lan.take() else { + return; + }; + self.guest_hit_by(&mut host, conn, f); + self.lan = Some(host); + } + } + } + /// `EnderDragonFight.validPlayer`: the players alive within 192 blocks of + /// (0, 128, 0), the host and the guests in the level alike. + fn fight_has_players(&self) -> bool { + let near = + |p: [f64; 3]| p[0].powi(2) + (p[1] - 128.0).powi(2) + p[2].powi(2) <= 192.0 * 192.0; + let host = self.player.as_ref().is_some_and(|p| { + !p.health.dead_or_dying() && near([p.position.x, p.position.y, p.position.z]) + }); + host || self.lan.as_ref().is_some_and(|h| { + h.hub + .guests + .iter() + .any(|g| h.hub.here(g) && g.loaded && !g.dead && near(g.position)) + }) + } + /// `EnderDragonFight.tick` and the fight's entities, while the End is + /// ticked (in place for its player, or on a server with players in it). pub(super) fn tick_fight(&mut self) { if self.dim != Dim::End || self.travelling.is_some() { return; } self.load_fight(); + // updatePlayers, every 20 ticks. + self.fight.player_scan += 1; + if self.fight.player_scan >= 20 { + self.fight.player_scan = 0; + self.fight.players = self.fight_has_players(); + } if !self.arena_loaded() { return; } - if self.fight.needs_scan { - // scanState: a missing exit portal means a fight in progress. - self.fight.previously_killed = self.end_portal_active(); - if !self.fight.previously_killed { - self.fight.killed = false; - } - self.fight.needs_scan = false; - self.fight.dirty = true; - } if !self.fight.crystals_placed { self.place_spike_crystals(); self.fight.crystals_placed = true; self.fight.dirty = true; } - let Some(p) = self.player.as_ref().map(|p| p.position) else { - return; - }; - let near = p.x.powi(2) + (p.y - 128.0).powi(2) + p.z.powi(2) <= 192.0 * 192.0; - if !self.fight.killed && near && self.dragon.is_none() { - // createNewDragon: over the podium, holding pattern, a random yaw. - let yaw = self.world.random.next_float() * 360.0; - let seed = self.world.random.next_long(); - self.dragon = Some(Dragon::new(Vec3::new(0.0, 128.0, 0.0), yaw, seed)); + if self.fight.players { + if self.fight.needs_scan { + // scanState: a missing exit portal means a fight in progress. + self.fight.previously_killed = self.end_portal_active(); + if !self.fight.previously_killed { + self.fight.killed = false; + } + self.fight.needs_scan = false; + self.fight.dirty = true; + } + if self.fight.respawn.is_some() { + self.tick_respawn(); + } + if !self.fight.killed { + if self.dragon.is_none() { + // createNewDragon: over the podium, holding pattern, a random yaw. + let yaw = self.world.random.next_float() * 360.0; + let seed = self.world.random.next_long(); + self.dragon = Some(Dragon::new(Vec3::new(0.0, 128.0, 0.0), yaw, seed)); + } + self.fight.crystal_scan += 1; + if self.fight.crystal_scan >= 100 { + self.count_crystals(); + } + } } - if self.fight.respawn.is_some() { - self.tick_respawn(); + // EnderDragon's constructor takes its id and its parts' from the + // entity counter (a dragon loaded from the save gets them here too). + if let Some(d) = self.dragon.as_mut() + && d.id == 0 + { + d.id = self.next_entity + 1; + self.next_entity += 9; } - self.fight.crystal_scan += 1; - if self.fight.crystal_scan >= 100 { - self.count_crystals(); + // The spikes' crystals too (EndCrystal's constructor): an id whether + // or not a client has tracked them yet, to be aimed at by it. + for c in self.crystals.iter_mut().filter(|c| c.id == 0) { + self.next_entity += 1; + c.id = self.next_entity; } - self.tick_crystals(); self.tick_dragon(); } /// EndSpikeFeature's crystals (with fire under them on the bedrock). @@ -583,9 +850,12 @@ impl Game<'_> { }) .count() as i32; } - /// `EndCrystal.tick`: the time and the fire below it in the End. - fn tick_crystals(&mut self) { - let fire = self.pack.assets.registry.default_state("minecraft:fire"); + /// `EndCrystal.tick` in every dimension: the time (the spin and bob), + /// and fire at its block where there is a dragon fight (the End). + pub(super) fn tick_crystals(&mut self) { + let fire = (self.dim == Dim::End) + .then(|| self.pack.assets.registry.default_state("minecraft:fire")) + .flatten(); for i in 0..self.crystals.len() { self.crystals[i].time += 1; let p = self.crystals[i].position; @@ -599,7 +869,7 @@ impl Game<'_> { } } /// A crystal took damage: `EndCrystal.hurtServer` blows it up (power 6). - fn destroy_crystal(&mut self, index: usize, by_player: bool) { + fn destroy_crystal(&mut self, index: usize, by: Option) { if index >= self.crystals.len() || self.crystals[index].invulnerable { return; } @@ -624,24 +894,21 @@ impl Game<'_> { if let Some(d) = self.dragon.as_mut() { if d.nearest_crystal == Some(index) { d.nearest_crystal = None; - self.hurt_dragon(0, 10.0, true); + self.hurt_dragon(0, 10.0, true, false); } else if let Some(n) = d.nearest_crystal.as_mut() && *n > index { *n -= 1; } - if by_player - && let Some(d) = self.dragon.as_mut() + // EnderDragon.onCrystalDestroyed: the player who did it, else the + // nearest; DragonHoldingPatternPhase strafes them. + if let Some(d) = self.dragon.as_mut() && matches!(d.phase, Phase::Holding { .. }) { - // DragonHoldingPatternPhase.onCrystalDestroyed: strafe the player. - d.set_phase(Phase::Strafe { - charge: 0, - path: None, - target: None, - clockwise: false, + d.strafe_request = Some(match by { + Some(who) => StrafeRequest::Player(who), + None => StrafeRequest::Nearest(c.position), }); - self.strafe_begin(); } } } @@ -665,64 +932,58 @@ impl Game<'_> { } out } - /// Damage to a special id (from projectiles and melee). - pub(super) fn hit_special(&mut self, id: u32, amount: f32, by_player: bool) { + /// The box of the dragon part or end crystal guests know as entity `id` + /// (`EnderDragonPart`s follow the dragon's id). + pub(super) fn tracked_special_box(&self, id: i32) -> Option { + let id = u32::try_from(id).ok().filter(|&id| id != 0)?; + if let Some(d) = self.dragon.as_ref().filter(|d| d.alive() && d.id != 0) + && (d.id + 1..=d.id + 8).contains(&id) + { + return Some(d.part_box((id - d.id - 1) as usize)); + } + let i = self.crystals.iter().position(|c| c.id == id)?; + self.special_targets() + .into_iter() + .find(|(s, _)| *s == CRYSTAL_IDS + i as u32) + .map(|(_, b)| b) + } + /// Damage to a special id (from projectiles and melee): what the + /// dragon part or crystal made of it. `arrow` for a direct arrow. + pub(super) fn hit_special( + &mut self, + id: u32, + amount: f32, + by_player: bool, + arrow: bool, + ) -> Hurt { if id >= CRYSTAL_IDS { - self.destroy_crystal((id - CRYSTAL_IDS) as usize, by_player); + // EndCrystal.hurtServer: false while invulnerable, else it blows up. + let index = (id - CRYSTAL_IDS) as usize; + if self.crystals.get(index).is_none_or(|c| c.invulnerable) { + return Hurt::Refused; + } + let by = by_player.then(|| self.acting_player()); + self.destroy_crystal(index, by); + Hurt::Landed { full: true } } else if id >= SPECIAL { - self.hurt_dragon((id - SPECIAL) as usize, amount, by_player); + self.hurt_dragon((id - SPECIAL) as usize, amount, by_player, arrow) + } else { + Hurt::Refused } } - /// `EnderDragon.hurt(part, source, damage)`. - fn hurt_dragon(&mut self, part: usize, damage: f32, counts: bool) { + /// `EnderDragon.hurt(part, source, damage)` on the dragon in the level. + fn hurt_dragon(&mut self, part: usize, damage: f32, counts: bool, arrow: bool) -> Hurt { let Some(d) = self.dragon.as_mut() else { - return; + return Hurt::Refused; }; - if matches!(d.phase, Phase::Dying { .. }) || !d.alive() { - return; + let hurt = d.hurt(part, damage, counts, arrow); + if hurt == (Hurt::Landed { full: true }) { + let at = [d.position.x, d.position.y, d.position.z]; + let pitch = 0.8 + self.world.random.next_float() * 0.3; + self.audio + .play("minecraft:entity.ender_dragon.hurt", Some(at), 5.0, pitch); } - let mut damage = damage; - if part != 0 && part != 1 { - damage = damage / 4.0 + damage.min(1.0); - } - if damage < 0.01 || !counts { - return; - } - // LivingEntity.hurt invulnerability: only damage above the last one in the window. - if d.invulnerable > 10 { - return; - } - let before = d.health; - d.health -= damage; - d.invulnerable = 20; - d.hurt_time = 10; - let at = [d.position.x, d.position.y, d.position.z]; - if d.health <= 0.0 { - if d.phase.sitting() { - d.health = 0.0; - } else { - // handleKillingBlow: dying flight first. - d.health = 1.0; - d.set_phase(Phase::Dying { - target: None, - time: 0, - }); - } - } - if d.phase.sitting() { - d.sitting_damage += before - d.health.max(0.0); - if d.sitting_damage > 0.25 * MAX_HEALTH { - d.sitting_damage = 0.0; - d.set_phase(Phase::Takeoff { - first: true, - path: None, - target: None, - }); - } - } - let pitch = 0.8 + self.world.random.next_float() * 0.3; - self.audio - .play("minecraft:entity.ender_dragon.hurt", Some(at), 5.0, pitch); + hurt } /// Player melee on the dragon's parts or a crystal under the crosshair. /// The dragon part under the crosshair within reach: its id and distance. @@ -779,7 +1040,7 @@ impl Game<'_> { amount += self.enchant_damage_bonus("minecraft:ender_dragon") * scale; self.attack_ticks = 0; self.swing_arm(); - self.hit_special(id, amount, true); + self.hit_special(id, amount, true, false); true } /// The 24 nodes (`findClosestNode` builds them on first use). @@ -943,10 +1204,8 @@ impl Game<'_> { path.advance(); Some(path) } - fn strafe_begin(&mut self) { - let Some(p) = self.player.as_ref().map(|p| p.position) else { - return; - }; + /// `DragonStrafePlayerPhase.setTarget`: a path to the player at `p`. + fn strafe_begin(&mut self, p: Vec3) { let Some(d) = self.dragon.as_ref() else { return; }; @@ -976,6 +1235,32 @@ impl Game<'_> { } /// One phase server tick (`doServerTick`). fn tick_phase(&mut self) { + let players = self.fight_players(); + let peaceful = self.ui.difficulty == 0; + // A crystal destroyed since: strafe whoever it names, if the dragon + // can attack them (`canAttack`). + if let Some(d) = self.dragon.as_mut() + && let Some(request) = d.strafe_request.take() + && matches!(d.phase, Phase::Holding { .. }) + { + let target = match request { + StrafeRequest::Player(who) => players + .iter() + .find(|p| p.who == who && p.enemy() && !peaceful) + .copied(), + StrafeRequest::Nearest(at) => nearest_enemy(&players, peaceful, at, None, |_| true), + }; + if let Some(t) = target { + d.set_phase(Phase::Strafe { + charge: 0, + path: None, + target: None, + clockwise: false, + player: Some(t.who), + }); + self.strafe_begin(t.position); + } + } let Some(d) = self.dragon.as_ref() else { return; }; @@ -987,14 +1272,13 @@ impl Game<'_> { (t.x - pos.x).powi(2) + (t.y - pos.y).powi(2) + (t.z - pos.z).powi(2) }) }; - let player = self - .player - .as_ref() - .filter(|p| !p.health.dead_or_dying()) - .map(|p| p.position); - let survival_player = player.filter(|_| !self.creative); let podium = self.podium_top(); + // The egg's place (`getHeightmapPos` at the podium) and its centre. + let egg = Vec3::new(0.0, podium.y, 0.0); + let egg_centre = Vec3::new(0.5, podium.y + 0.5, 0.5); let mut next: Option = None; + // Where the player a new strafe goes after stands. + let mut strafe_at: Option = None; match &mut phase { Phase::Holding { path, @@ -1014,11 +1298,10 @@ impl Game<'_> { target: None, }); chosen = true; - } else if let Some(pp) = survival_player { - let dist = ((pp.x - podium.x).powi(2) - + (pp.y - podium.y).powi(2) - + (pp.z - podium.z).powi(2)) - / 512.0; + } else if let Some(nearest) = + nearest_enemy(&players, peaceful, egg, None, |_| true) + { + let dist = nearest.position.distance_squared(egg_centre) / 512.0; let r = &mut self.dragon.as_mut().expect("dragon").random; if r.next_int_bound((dist + 2.0) as i32).unwrap_or(1) == 0 || r.next_int_bound(crystals + 2).unwrap_or(1) == 0 @@ -1028,7 +1311,9 @@ impl Game<'_> { path: None, target: None, clockwise: false, + player: Some(nearest.who), }); + strafe_at = Some(nearest.position); chosen = true; } } @@ -1048,8 +1333,12 @@ impl Game<'_> { path, target, clockwise, + player, } => { - let Some(pp) = survival_player else { + // Its target as it is now, whatever became of it; gone from + // the level, or never found: back to the holding pattern. + let tracked = player.and_then(|who| players.iter().find(|p| p.who == who)); + let Some(pp) = tracked.map(|p| p.position) else { next = Some(Phase::Holding { path: None, target: None, @@ -1107,7 +1396,9 @@ impl Game<'_> { if dt < 100.0 || dt > 22500.0 || collided { if path.as_ref().is_none_or(|p| p.0.done()) { let current = self.closest_node(pos.x, pos.y, pos.z); - let target_node = match player { + // NEAR_EGG_TARGETING: the enemy nearest the egg. + let near_egg = nearest_enemy(&players, peaceful, egg, None, |_| true); + let target_node = match near_egg.map(|p| p.position) { Some(pp) => { let aim = glam::DVec2::new(pp.x, pp.z).normalize_or_zero(); self.closest_node(-aim.x * 40.0, 105.0, -aim.y * 40.0) @@ -1179,12 +1470,12 @@ impl Game<'_> { } Phase::Scanning { time } => { *time += 1; - let near = player.filter(|pp| { - (pp.x - pos.x).powi(2) + (pp.y - pos.y).powi(2) + (pp.z - pos.z).powi(2) - <= 400.0 - && (pp.y - pos.y).abs() <= 10.0 - }); - if let Some(pp) = near.filter(|_| !self.creative) { + // scanTargeting: within 20 blocks, at most 10 above or below. + let near = nearest_enemy(&players, peaceful, pos, Some((pos, 20.0)), |p| { + (p.position.y - pos.y).abs() <= 10.0 + }) + .map(|p| p.position); + if let Some(pp) = near { if *time > 25 { next = Some(Phase::Attacking { ticks: 0 }); } else { @@ -1200,19 +1491,15 @@ impl Game<'_> { d.yaw += d.yaw_accel; } } else if *time >= 100 { - next = Some(match survival_player { - Some(pp) - if (pp.x - pos.x).powi(2) - + (pp.y - pos.y).powi(2) - + (pp.z - pos.z).powi(2) - <= 150.0 * 150.0 => - { - Phase::Charging { - target: Some(pp), - since: 0, - } - } - _ => Phase::Takeoff { + // CHARGE_TARGETING: within 150 blocks. + let charge = + nearest_enemy(&players, peaceful, pos, Some((pos, 150.0)), |_| true); + next = Some(match charge { + Some(p) => Phase::Charging { + target: Some(p.position), + since: 0, + }, + None => Phase::Takeoff { first: true, path: None, target: None, @@ -1317,10 +1604,9 @@ impl Game<'_> { let d = self.dragon.as_mut().expect("dragon"); d.phase = phase; if let Some(n) = next { - let strafe = matches!(n, Phase::Strafe { .. }); d.set_phase(n); - if strafe { - self.strafe_begin(); + if let Some(at) = strafe_at { + self.strafe_begin(at); } } } @@ -1554,34 +1840,41 @@ impl Game<'_> { ); let wings = [d.part_box(6), d.part_box(7)]; let heads = [d.part_box(0), d.part_box(1)]; - let player_box = self.player.as_ref().map(|p| p.bounds()); - let creative = self.creative; - if !recently_hurt && let Some(pb) = player_box.filter(|_| !creative) { - for w in wings { - let zone = w - .inflate(Vec3::new(4.0, 2.0, 4.0)) - .move_by(Vec3::new(0.0, -2.0, 0.0)); - if zone.intersects(pb) { - let pp = self - .player - .as_ref() - .map(|p| p.position) - .unwrap_or(Vec3::ZERO); - let (xd, zd) = (pp.x - bc, pp.z - bz); - let dd = (xd * xd + zd * zd).max(0.1); - if let Some(p) = self.player.as_mut() { - p.velocity.x += xd / dd * 4.0; - p.velocity.y += 0.2; - p.velocity.z += zd / dd * 4.0; - } - if !sitting { - self.hurt_player_by("minecraft:mob_attack", 5.0); + if !recently_hurt { + // EntitySelector.NO_CREATIVE_OR_SPECTATOR, every player alike. + let players: Vec = self + .fight_players() + .into_iter() + .filter(|p| p.alive && !p.creative && !p.spectator) + .collect(); + for p in players { + // knockBack, once for each wing whose zone holds them. + for w in wings { + let zone = w + .inflate(Vec3::new(4.0, 2.0, 4.0)) + .move_by(Vec3::new(0.0, -2.0, 0.0)); + if zone.intersects(p.bounds) { + let (xd, zd) = (p.position.x - bc, p.position.z - bz); + let dd = (xd * xd + zd * zd).max(0.1); + self.as_fight_player(p.who, |g| { + if let Some(pl) = g.player.as_mut() { + pl.velocity.x += xd / dd * 4.0; + pl.velocity.y += 0.2; + pl.velocity.z += zd / dd * 4.0; + } + if !sitting { + g.hurt_player_by("minecraft:mob_attack", 5.0); + } + }); } } - } - for h in heads { - if h.inflate(Vec3::new(1.0, 1.0, 1.0)).intersects(pb) { - self.hurt_player_by("minecraft:mob_attack", 10.0); + // hurt: the head and the neck. + for h in heads { + if h.inflate(Vec3::new(1.0, 1.0, 1.0)).intersects(p.bounds) { + self.as_fight_player(p.who, |g| { + g.hurt_player_by("minecraft:mob_attack", 10.0); + }); + } } } } @@ -1746,7 +2039,13 @@ impl Game<'_> { /// power, bursting into dragon's breath on impact. pub(super) fn tick_dragon_fireballs(&mut self) { let mut balls = std::mem::take(&mut self.dragon_fireballs); - let player = self.player.as_ref().map(|p| p.bounds()); + // Projectile.canHitEntity: any player but spectators. + let players: Vec = self + .fight_players() + .iter() + .filter(|p| p.alive && !p.spectator) + .map(|p| p.bounds) + .collect(); balls.retain_mut(|b| { b.previous = b.position; b.age += 1; @@ -1768,7 +2067,7 @@ impl Game<'_> { let f = self.res.facts().get(self.world.block(p[0], p[1], p[2])); f.full_collision || f.legacy_solid }; - let hit_player = player.is_some_and(|pb| { + let hit_player = players.iter().any(|pb| { pb.intersects(Aabb::new( Vec3::new(next.x - 0.5, next.y - 0.5, next.z - 0.5), Vec3::new(next.x + 0.5, next.y + 0.5, next.z + 0.5), @@ -1804,7 +2103,13 @@ impl Game<'_> { /// The dragon's breath clouds (`AreaEffectCloud` with instant damage at /// a quarter duration scale): shrinking, puffing particles, harming the player. fn tick_breath(&mut self) { - let player = self.player.as_ref().map(|p| p.position); + // What instant damage reaches: neither creative nor spectator players. + let players: Vec = self + .fight_players() + .into_iter() + .filter(|p| p.alive && !p.creative && !p.spectator) + .collect(); + let mut harmed: Vec<(FightWho, f32)> = Vec::new(); let mut clouds = std::mem::take(&mut self.breath_clouds); clouds.retain_mut(|c| { c.age += 1; @@ -1831,20 +2136,26 @@ impl Game<'_> { ); } // AreaEffectCloud: after its 20-tick wait, every 20 ticks per entity. - if c.age >= 20 - && c.age % 20 == 0 - && let Some(pp) = player - && (pp.x - c.at[0]).hypot(pp.z - c.at[2]) <= f64::from(r) - && (pp.y - c.at[1]).abs() < 1.0 - && !self.creative - { + if c.age >= 20 && c.age % 20 == 0 { // Instant damage: I (6) from the breath, II (12) from a fireball. let amount = if c.from_dragon { 6.0 } else { 12.0 }; - self.hurt_player_by("minecraft:indirect_magic", amount); + for p in &players { + let pp = p.position; + if (pp.x - c.at[0]).hypot(pp.z - c.at[2]) <= f64::from(r) + && (pp.y - c.at[1]).abs() < 1.0 + { + harmed.push((p.who, amount)); + } + } } true }); self.breath_clouds.append(&mut clouds); + for (who, amount) in harmed { + self.as_fight_player(who, |g| { + g.hurt_player_by("minecraft:indirect_magic", amount); + }); + } } /// `BossHealthOverlay`: the dragon's pink bar, then the withers', the /// raids' and the custom bars, in that order. @@ -2323,36 +2634,73 @@ impl Crystal { } } impl Game<'_> { - /// `Explosion.explode` for crystals (they blow up in turn) and the - /// dragon's parts (explosions always hurt dragons). + /// `ServerExplosion.hurtEntities` on the end crystals (each in reach + /// blows up in turn) and the dragon (explosions always hurt dragons). pub(super) fn explosion_hits_special(&mut self, center: [f64; 3], radius: f32) { let diameter = f64::from(radius * 2.0); - let dist = |p: Vec3| { + let in_reach = |p: Vec3| { ((p.x - center[0]).powi(2) + (p.y - center[1]).powi(2) + (p.z - center[2]).powi(2)) .sqrt() + / diameter + <= 1.0 }; - if let Some(i) = self + let crystals: Vec = self .crystals .iter() - .position(|c| !c.invulnerable && dist(c.position) / diameter <= 1.0) - { - self.destroy_crystal(i, false); - } - if let Some(d) = self.dragon.as_ref() { - let hits: Vec<(usize, f32)> = (0..8) - .filter_map(|i| { - let p = d.parts[i].0; - let r = dist(p) / diameter; - (r <= 1.0).then(|| { - let pow = 1.0 - r; - (i, ((pow * pow + pow) / 2.0 * 7.0 * diameter + 1.0) as f32) - }) - }) - .collect(); - if let Some(&(part, amount)) = hits.iter().max_by(|a, b| a.1.total_cmp(&b.1)) { - self.hurt_dragon(part, amount, true); + .filter(|c| !c.invulnerable && in_reach(c.position)) + .map(|c| c.position) + .collect(); + for at in crystals { + // One blowing up may already have taken the next. + if let Some(i) = self.crystals.iter().position(|c| c.position == at) { + self.destroy_crystal(i, None); } } + let Some(d) = self.dragon.as_ref() else { + return; + }; + let hits = d.explosion_hits(center, radius, |b| { + let (lo, hi) = (b.min_position(), b.max_position()); + self.seen_percent(center, [lo.x, lo.y, lo.z], [hi.x, hi.y, hi.z]) + }); + for (part, amount) in hits { + self.hurt_dragon(part, amount, true, false); + } + } +} +impl Game<'_> { + /// The dragon as guests track it (`EnderDragon.getAddEntityPacket` and + /// the synched data that differs from the defaults: its health, defined + /// as 1, and `DATA_PHASE`, defined as hovering). Vanilla pairs it with no + /// attribute instances. + pub(super) fn lan_dragon_state(&self) -> Option { + use horizon_protocol::entity_data::{Value, serializer}; + let d = self.dragon.as_ref().filter(|d| d.id != 0)?; + let mut meta = Vec::new(); + let health = d.health.max(0.0); + if health != 1.0 { + meta.push((9, serializer::FLOAT, Value::Float(health))); + } + let phase = d.phase.id(); + if phase != 10 { + meta.push((16, serializer::INT, Value::Int(phase))); + } + Some(horizon_client::lan::entity::EntityState { + id: d.id as i32, + uuid: super::lan::entity_uuid(d.id), + kind: "minecraft:ender_dragon".to_owned(), + position: [d.position.x, d.position.y, d.position.z], + yaw: d.yaw, + pitch: 0.0, + head_yaw: d.yaw, + on_ground: false, + velocity: [d.velocity.x, d.velocity.y, d.velocity.z], + data: 0, + meta, + equipment: Vec::new(), + attributes: Vec::new(), + precise: false, + }) } } impl Game<'_> { @@ -2360,12 +2708,27 @@ impl Game<'_> { pub(super) fn dragon_status(&self) -> serde_json::Value { serde_json::json!({ "dragon": self.dragon.as_ref().map(|d| serde_json::json!({ + "id": d.id, "position": [d.position.x, d.position.y, d.position.z], "health": d.health, "phase": d.phase.id(), "death_time": d.death_time, + // The player it strafes: "host", or the guest's entity id. + "strafing": match &d.phase { + Phase::Strafe { player: Some(FightWho::Host), .. } => serde_json::json!("host"), + Phase::Strafe { player: Some(FightWho::Guest(conn)), .. } => serde_json::json!( + self.lan.as_ref().and_then(|h| h.hub.guest(*conn)).map(|g| g.entity_id) + ), + _ => serde_json::Value::Null, + }, })), + "players": self.fight.players, "crystals": self.crystals.len(), + // The tracked id (0 until tracked) and position of each crystal. + "crystal_list": self.crystals.iter().map(|c| serde_json::json!({ + "id": c.id, + "position": [c.position.x, c.position.y, c.position.z], + })).collect::>(), "alive_crystals": self.fight.alive_crystals, "killed": self.fight.killed, "exit_portal": self.fight.exit_portal, @@ -2758,3 +3121,143 @@ impl Game<'_> { self.fight.dirty = true; } } + +#[cfg(test)] +mod tests { + use super::*; + + fn dragon(phase: Phase) -> Dragon { + let mut d = Dragon::new(Vec3::new(0.0, 70.0, 0.0), 0.0, 1); + d.phase = phase; + d + } + fn flying() -> Phase { + Phase::Holding { + path: None, + target: None, + clockwise: false, + } + } + + #[test] + fn a_perched_dragon_shrugs_arrows_off() { + // AbstractDragonSittingPhase.onHurt: an arrow does nothing, melee does. + let mut d = dragon(Phase::Scanning { time: 0 }); + assert_eq!(d.hurt(0, 9.0, true, true), Hurt::Shrugged); + assert_eq!(d.health, MAX_HEALTH); + assert_eq!(d.hurt(0, 9.0, true, false), Hurt::Landed { full: true }); + assert_eq!(d.health, MAX_HEALTH - 9.0); + // In flight an arrow lands. + let mut d = dragon(flying()); + assert_eq!(d.hurt(0, 9.0, true, true), Hurt::Landed { full: true }); + assert_eq!(d.health, MAX_HEALTH - 9.0); + } + + #[test] + fn the_cooldown_lets_only_the_excess_through() { + // LivingEntity.hurtServer: damageCooldownTime > 10 keeps lastHurt. + let mut d = dragon(flying()); + assert_eq!(d.hurt(0, 6.0, true, false), Hurt::Landed { full: true }); + assert_eq!(d.hurt(0, 4.0, true, false), Hurt::Landed { full: false }); + assert_eq!(d.health, MAX_HEALTH - 6.0); + assert_eq!(d.hurt(0, 10.0, true, false), Hurt::Landed { full: false }); + assert_eq!(d.health, MAX_HEALTH - 10.0); + // Ten ticks on, the window is over: a full hit again. + d.invulnerable = 10; + assert_eq!(d.hurt(0, 3.0, true, false), Hurt::Landed { full: true }); + assert_eq!(d.health, MAX_HEALTH - 13.0); + } + + #[test] + fn parts_and_sources() { + // Neither head nor neck: a quarter plus one. + let mut d = dragon(flying()); + assert_eq!(d.hurt(2, 20.0, true, false), Hurt::Landed { full: true }); + assert_eq!(d.health, MAX_HEALTH - 6.0); + // Not a player's and not an explosion: true, but no damage. + let mut d = dragon(flying()); + assert_eq!(d.hurt(0, 20.0, false, false), Hurt::Landed { full: false }); + assert_eq!(d.health, MAX_HEALTH); + // Too little after the part's cut, and nothing while dying. + assert_eq!(d.hurt(3, 0.001, true, false), Hurt::Refused); + d.phase = Phase::Dying { + target: None, + time: 0, + }; + assert_eq!(d.hurt(0, 20.0, true, false), Hurt::Refused); + } + + #[test] + fn a_quarter_of_its_health_while_perched_makes_it_take_off() { + let mut d = dragon(Phase::Flaming { ticks: 0 }); + d.hurt(0, 30.0, true, false); + assert!(d.phase.sitting()); + d.invulnerable = 0; + d.hurt(0, 21.0, true, false); + assert!(matches!(d.phase, Phase::Takeoff { .. })); + assert_eq!(d.sitting_damage, 0.0); + } + + #[test] + fn explosions_hit_each_part_by_its_exposure() { + let mut d = dragon(flying()); + for (i, part) in d.parts.iter_mut().enumerate() { + part.0 = Vec3::new(i as f64 * 4.0, 70.0, 0.0); + } + // A power-6 blast at the dragon's feet: diameter 12. + let center = [0.0, 70.0, 0.0]; + let open = d.explosion_hits(center, 6.0, |_| 1.0); + // The dragon itself (its body), then the parts within 12 blocks. + let parts: Vec = open.iter().map(|h| h.0).collect(); + assert_eq!(parts, vec![2, 0, 1, 2, 3]); + // At the centre: (1 + 1) / 2 * 7 * 12 + 1. + assert_eq!(open[0].1, 85.0); + // Behind cover (no ray reaches the box) only the 1 is left. + let covered = d.explosion_hits(center, 6.0, |_| 0.0); + assert!(covered.iter().all(|h| h.1 == 1.0)); + // Through the cooldown the strongest hit after the part's cut wins. + for (part, amount) in open { + d.hurt(part, amount, true, false); + } + assert_eq!(d.health, MAX_HEALTH - 85.0); + } + + fn player(who: FightWho, x: f64, creative: bool, spectator: bool) -> FightPlayer { + let position = Vec3::new(x, 64.0, 0.0); + FightPlayer { + who, + position, + bounds: Aabb::new(position, Vec3::new(x + 0.6, 65.8, 0.6)), + alive: true, + creative, + spectator, + } + } + + #[test] + fn the_dragon_targets_any_player_it_can_attack() { + let at = Vec3::new(0.0, 64.0, 0.0); + // A spectating host and a creative guest are never targets: the + // survival guest further away is. + let players = [ + player(FightWho::Host, 1.0, false, true), + player(FightWho::Guest(7), 2.0, true, false), + player(FightWho::Guest(8), 30.0, false, false), + ]; + let t = nearest_enemy(&players, false, at, None, |_| true); + assert_eq!(t.map(|p| p.who), Some(FightWho::Guest(8))); + // Out of a 20-block range, or filtered out, or on Peaceful: none. + assert!(nearest_enemy(&players, false, at, Some((at, 20.0)), |_| true).is_none()); + assert!(nearest_enemy(&players, false, at, None, |p| p.position.x < 10.0).is_none()); + assert!(nearest_enemy(&players, true, at, None, |_| true).is_none()); + // The nearest of several, measured from where it looks (the egg). + let players = [ + player(FightWho::Host, 5.0, false, false), + player(FightWho::Guest(8), -3.0, false, false), + ]; + let t = nearest_enemy(&players, false, at, None, |_| true); + assert_eq!(t.map(|p| p.who), Some(FightWho::Guest(8))); + let t = nearest_enemy(&players, false, Vec3::new(9.0, 64.0, 0.0), None, |_| true); + assert_eq!(t.map(|p| p.who), Some(FightWho::Host)); + } +} diff --git a/crates/horizon-client/src/game/dynamic_lights.rs b/crates/horizon-client/src/game/dynamic_lights.rs new file mode 100644 index 000000000..cd4223d82 --- /dev/null +++ b/crates/horizon-client/src/game/dynamic_lights.rs @@ -0,0 +1,67 @@ +//! Horizon Extras' dynamic lights (`horizon_client::dynamic_light`): the light sources near the +//! camera this frame. Nothing is gathered while the extra is off. +use super::{Game, shield}; +use glam::DVec3; +use horizon_client::dynamic_light::{self, BURNING, Luminance, Source}; + +impl Game<'_> { + /// Fills `dynamic_lights` for the frame: the player's and mobs' held items and fire, and + /// glowing dropped items, the nearest [`dynamic_light::MAX`] of them. + pub(super) fn gather_dynamic_lights(&mut self, camera: DVec3, alpha: f64) { + let mut out = std::mem::take(&mut self.dynamic_lights); + out.clear(); + if !self.settings.extras.dynamic_lights { + self.dynamic_lights = out; + return; + } + if self.luminance.is_none() { + self.luminance = Some(Luminance::new(self.res.facts(), self.pack.assets.registry)); + } + let lum = self.luminance.as_ref().expect("built above"); + let held = |item: Option<&str>| item.map_or(0, |i| lum.of(i)); + let mut sources = Vec::new(); + if let Some(p) = &self.player + && !p.spectator + { + let feet = self + .previous_position + .lerp(p.position, self.clock.camera_fraction()); + let level = held(self.stack_in(self.selected).map(|s| &*s.item)) + .max(held(self.stack_in(shield::OFFHAND_SLOT).map(|s| &*s.item))) + .max(if p.fire_ticks > 0 { BURNING } else { 0 }); + // About where the hands are. + sources.push(Source { + at: DVec3::new(feet.x, feet.y + 1.2, feet.z), + level, + }); + } + for m in self.mobs.iter().filter(|m| !m.removed) { + let level = held(m.extra.main_hand.as_deref()) + .max(held(m.extra.off_hand.as_deref())) + .max(if m.fire_ticks > 0 { BURNING } else { 0 }); + if level == 0 { + continue; + } + let at = m.previous.lerp(m.position, alpha); + sources.push(Source { + at: DVec3::new(at.x, at.y + f64::from(m.height()) * 0.6, at.z), + level, + }); + } + for item in &self.dropped { + let level = lum + .of(&item.stack.item) + .max(if item.fire_ticks > 0 { BURNING } else { 0 }); + if level == 0 { + continue; + } + let at = item.previous.lerp(item.position, alpha); + sources.push(Source { + at: DVec3::new(at.x, at.y + 0.25, at.z), + level, + }); + } + dynamic_light::select(&sources, camera, &mut out); + self.dynamic_lights = out; + } +} diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index a6d91d563..a7813c767 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -350,6 +350,7 @@ impl Game<'_> { self.tick_fight(); self.tick_dragon_fireballs(); } + self.tick_crystals(); self.tick_eyes(); if self.dim == Dim::End { self.end.flash.tick(self.world.game_time); diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 55babd9af..5cf67f586 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -226,6 +226,102 @@ impl Game<'_> { } /// `ServerExplosion.hurtEntities` (player, mobs, items, primed TNT); /// the player takes `damage_type`. + /// `ServerExplosion.hurtEntities` for the player: damage scaled by + /// distance and exposure, through a raised shield (`hurtServer` blocks + /// explosions like any attack from where the blast is), then the push + /// (less with explosion knockback resistance; none for spectators or a + /// creative player flying). + pub(super) fn explosion_hurt_player( + &mut self, + center: [f64; 3], + radius: f32, + damage_type: &str, + exploding: Option, + ) { + let diameter = f64::from(radius * 2.0); + // Blast protection: `EXPLOSION_KNOCKBACK_RESISTANCE` (0.15 per level and + // piece, so two Blast Protection IV pieces cancel it). + let resistance = self + .player + .as_mut() + .and_then(|p| p.attribute("minecraft:explosion_knockback_resistance").ok()) + .unwrap_or(0.0); + let Some(p) = self.player.as_ref() else { + return; + }; + let feet = [p.position.x, p.position.y, p.position.z]; + let dist = ((feet[0] - center[0]).powi(2) + + (feet[1] - center[1]).powi(2) + + (feet[2] - center[2]).powi(2)) + .sqrt() + / diameter; + if dist > 1.0 || p.health.dead_or_dying() { + return; + } + let w = f64::from(p.dimensions.width) / 2.0; + let h = f64::from(p.dimensions.height); + let eye = [ + feet[0], + feet[1] + f64::from(p.dimensions.eye_height), + feet[2], + ]; + let exposure = self.seen_percent( + center, + [feet[0] - w, feet[1], feet[2] - w], + [feet[0] + w, feet[1] + h, feet[2] + w], + ); + let pow = (1.0 - dist) * f64::from(exposure); + let amount = ((pow * pow + pow) / 2.0 * 7.0 * diameter + 1.0) as f32; + let d = [eye[0] - center[0], eye[1] - center[1], eye[2] - center[2]]; + let l = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(); + let dir = if l < 1.0e-4 { + [0.0; 3] + } else { + [d[0] / l, d[1] / l, d[2] / l] + }; + let power = pow * (1.0 - resistance); + // `source.doTeamsAllowDamage(entity)`. + let hurtable = exploding.is_none_or(|id| { + horizon_client::scoreboard::teams_allow_damage(self.mob_team(id), self.player_team()) + }); + let blocking = self.player_blocking(Some(center), damage_type, false); + let raised = blocking.is_some(); + let (creative, spectator) = (self.creative, self.spectator()); + let flying = self.player.as_ref().is_some_and(|p| p.flying); + let mut outcome = horizon_client::health::BlockOutcome::default(); + if let Some(p) = self.player.as_mut() + && let Some(id) = self.motion.health.damage.id(damage_type) + { + // Creative players are invulnerable to explosions. + if !creative + && !spectator + && hurtable + && let Ok(o) = p.hurt_blocking( + &self.motion.health, + self.world.health_rules, + id, + amount, + blocking, + ) + { + outcome = o; + } + if !spectator && !(creative && flying) { + p.velocity = Vec3::new( + p.velocity.x + dir[0] * power, + p.velocity.y + dir[1] * power, + p.velocity.z + dir[2] * power, + ); + } + } + if outcome.hurt && !creative { + self.hurt_armor(amount); + } + if raised { + self.after_block(outcome, amount, None, false); + } + } + fn explosion_hurt_entities(&mut self, center: [f64; 3], radius: f32, damage_type: &str) { if radius < 1.0e-5 { return; @@ -261,57 +357,23 @@ impl Game<'_> { horizon_client::scoreboard::teams_allow_damage(g.mob_team(id), victim) }) }; - let player_hurtable = teams_allow(self, self.player_team()); - // Player. - if let Some(p) = self.player.as_ref() { - let feet = [p.position.x, p.position.y, p.position.z]; - let dist = distance(feet) / diameter; - if dist <= 1.0 && !p.health.dead_or_dying() { - let w = f64::from(p.dimensions.width) / 2.0; - let h = f64::from(p.dimensions.height); - let eye = [ - feet[0], - feet[1] + f64::from(p.dimensions.eye_height), - feet[2], - ]; - let exposure = self.seen_percent( - center, - [feet[0] - w, feet[1], feet[2] - w], - [feet[0] + w, feet[1] + h, feet[2] + w], - ); - let amount = damage(dist, exposure); - let dir = direction(eye); - let mut hurt = false; - let creative = self.creative; - if let Some(p) = self.player.as_mut() - && let Some(id) = self.motion.health.damage.id(damage_type) - { - // Creative players are invulnerable to explosions. - if !creative && player_hurtable { - hurt = p - .hurt(&self.motion.health, self.world.health_rules, id, amount) - .unwrap_or(false); - } - // Blast protection: `EXPLOSION_KNOCKBACK_RESISTANCE` (0.15 per - // level and piece, so two Blast Protection IV pieces cancel it). - let resistance = p - .attribute("minecraft:explosion_knockback_resistance") - .unwrap_or(0.0); - let power = (1.0 - dist) * f64::from(exposure) * (1.0 - resistance); - // `hitPlayers` skips creative players who are flying: the - // client gets no knockback in the explode packet. - if !(creative && p.flying) { - p.velocity = Vec3::new( - p.velocity.x + dir[0] * power, - p.velocity.y + dir[1] * power, - p.velocity.z + dir[2] * power, - ); - } - } - if hurt && !self.creative { - self.hurt_armor(amount); - } + // The player, then every other player in the level (LAN guests), + // each swapped in as the player. + self.explosion_hurt_player(center, radius, damage_type, exploding); + if let Some(mut host) = self.lan.take() { + let guests: Vec = host + .hub + .guests + .iter() + .filter(|g| host.hub.here(g) && g.loaded && !g.dead) + .map(|g| g.conn) + .collect(); + for conn in guests { + self.guest_hit_by(&mut host, conn, |g| { + g.explosion_hurt_player(center, radius, damage_type, exploding); + }); } + self.lan = Some(host); } // Mobs. let mut mobs = std::mem::take(&mut self.mobs); diff --git a/crates/horizon-client/src/game/hand.rs b/crates/horizon-client/src/game/hand.rs index 84cea5a5c..a7218ff3c 100644 --- a/crates/horizon-client/src/game/hand.rs +++ b/crates/horizon-client/src/game/hand.rs @@ -156,6 +156,7 @@ impl Game<'_> { || before(self.dragon_hit().map(|h| h.1)) || before(self.mob_hit().map(|h| h.1)) || before(self.guest_hit().map(|h| h.1)) + || before(self.redirectable_hit().map(|h| h.1)) } /// `LocalPlayer.isHandsBusy`: paddling a boat. fn hands_busy(&self) -> bool { diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs index 6e1fdf589..ef5775174 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -6,9 +6,9 @@ //! the world's options) with [`Integrated::call`], as vanilla's client calls //! into its `IntegratedServer`. //! -//! Opt-in for now (`--server-thread` or `HORIZON_SERVER_THREAD=1`): the -//! player joins as a network player, and the server side of a network player -//! does not do everything single player does yet. +//! On by default. `--no-server-thread` or `HORIZON_SERVER_THREAD=0` runs +//! the world in the frame instead (the escape hatch while the network +//! player's side catches up with the in-frame one). use super::{ Game, Options, PackResources, Resources, UiResources, lan::{LanSettings, Owner}, diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 18325828d..548a69e3f 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -10,7 +10,7 @@ use horizon_client::{ self, Lan, MAX_PLAYERS, NetConfig, chunks::ChunkEncoder, data::SyncData, - entity::EntityState, + entity::{EntityState, States}, hub::{HostEvent, HostState, Hub, HubConfig, TickCtx}, playerdata, }, @@ -44,6 +44,8 @@ pub(super) struct LanHost { pub host_entity: i32, /// The host's swings the guests were told of (`Game::swings_started`). pub host_swings: u32, + /// The host's crack the guests were told of: the block and its stage. + pub host_crack: Option<([i32; 3], i32)>, pub host_uuid: u128, /// The host's profile name (the account's, or the offline name). pub host_name: String, @@ -59,13 +61,17 @@ pub(super) struct LanHost { pub mob_players: HashMap, /// An integrated server's owner (game/integrated.rs). pub owner: Option, - /// The players' locator bars (game/lan_waypoints.rs), and the guests who - /// are dead, whose respawn replaces their waypoint. - pub waypoints: lan::waypoints::Waypoints, + /// The players' locator bars, one waypoint manager per level by + /// dimension id (game/lan_waypoints.rs), and the guests who are dead, + /// whose respawn replaces their waypoint. + pub waypoints: std::collections::HashMap, pub waypoint_dead: std::collections::HashSet, /// Guests' commands waiting for the hub to be back in `self.lan`, where /// a command can reach every player (game/lan_actions.rs). pub commands: Vec, + /// The entities the guests track, described again every tick + /// (`lan_entities`) over last tick's states. + states: lan::entity::States, } /// The player who owns an integrated server's world: a guest whose state is @@ -133,8 +139,7 @@ fn baby_index(kind: &str) -> Option { /// A mob's synched data as ServerEntity sends it (only the values that differ /// from the defaults the client constructs), with vanilla's entry indices: /// Entity 0..=7, LivingEntity 8..=14, Mob 15, then the subclasses. -fn mob_meta(m: &Mob, hub: &Hub) -> Vec<(u8, i32, Value)> { - let mut meta = Vec::new(); +fn mob_meta(m: &Mob, hub: &Hub, meta: &mut Vec<(u8, i32, Value)>) { let kind = m.kind.id.as_str(); if m.fire_ticks > 0 { meta.push((0, serializer::BYTE, Value::Byte(1))); @@ -277,14 +282,16 @@ fn mob_meta(m: &Mob, hub: &Hub) -> Vec<(u8, i32, Value)> { } _ => {} } - meta } /// The equipment a mob shows (ClientboundSetEquipmentPacket slots: main hand, /// off hand, feet, legs, chest, head, body, saddle). -fn mob_equipment(m: &Mob, hub: &mut Hub) -> Vec<(u8, Option)> { +fn mob_equipment( + m: &Mob, + hub: &mut Hub, + out: &mut Vec<(u8, Option)>, +) { let e = &m.extra; - let mut out = Vec::new(); let slots = [ (0u8, &e.main_hand), (1, &e.off_hand), @@ -313,7 +320,6 @@ fn mob_equipment(m: &Mob, hub: &mut Hub) -> Vec<(u8, Option { ], "chunks": g.sent_chunks.len(), "tracked": g.tracker.len(), + // Whether the host draws this guest lying in a bed. + "model_lying": h.models.get(&g.conn).map(|m| m.extra.ints[1] != 0), // The armour the host draws on this guest, head to feet. "model_armor": h.models.get(&g.conn).map(|m| { [&m.extra.head, &m.extra.chest, &m.extra.legs, &m.extra.feet] @@ -519,6 +527,7 @@ impl Game<'_> { settings: LanSettings { port, ..settings }, host_entity, host_swings: self.swings_started, + host_crack: None, host_uuid, host_name: self.options.player_name(), models: HashMap::new(), @@ -531,6 +540,7 @@ impl Game<'_> { waypoints: Default::default(), waypoint_dead: Default::default(), commands: Vec::new(), + states: Default::default(), }); self.audio.capture = Some(Vec::new()); Ok(()) @@ -734,76 +744,44 @@ impl Game<'_> { equipment, health: p.health.health(), attributes: horizon_client::lan::attributes::syncable(&p.attributes), - living_flags: living_flags(self.using), + // Bit 4: Riptide's spin (LivingEntity.isAutoSpinAttack). + living_flags: living_flags(self.using) + | if p.auto_spin_attack_ticks > 0 { 4 } else { 0 }, + bed: self.sleeping, }) } /// The entities guests track: mobs, items and the rest (game/lan_entities.rs). - fn lan_entities(&self, host_entity: Option, hub: &mut Hub) -> Vec { - let mut out = Vec::with_capacity(self.mobs.len() + self.dropped.len() + self.orbs.len()); + fn lan_entities(&self, host_entity: Option, hub: &mut Hub, out: &mut States) { + out.clear(); for m in self.mobs.iter().filter(|m| !m.removed) { - let kind = m.kind.id.as_str(); - let meta = mob_meta(m, hub); - let equipment = mob_equipment(m, hub); - let attributes = self.mob_attributes(m); - let (yaw, pitch) = (m.yaw, m.head_pitch); - out.push(EntityState { - id: m.id as i32, - uuid: entity_uuid(m.id), - kind: kind.to_owned(), - position: [m.position.x, m.position.y, m.position.z], - yaw, - pitch, - head_yaw: m.head_yaw, - on_ground: m.on_ground, - velocity: [m.velocity.x, m.velocity.y, m.velocity.z], - data: 0, - meta, - equipment, - attributes, - precise: false, - }); + let e = out.add(m.id as i32, entity_uuid(m.id), m.kind.id.as_str()); + e.position = [m.position.x, m.position.y, m.position.z]; + (e.yaw, e.pitch, e.head_yaw) = (m.yaw, m.head_pitch, m.head_yaw); + e.on_ground = m.on_ground; + e.velocity = [m.velocity.x, m.velocity.y, m.velocity.z]; + mob_meta(m, hub, &mut e.meta); + mob_equipment(m, hub, &mut e.equipment); + self.mob_attributes(m, &mut e.attributes); } for d in &self.dropped { let stack = hub.stack(&Some(d.stack.clone())); - out.push(EntityState { - id: d.id as i32, - uuid: entity_uuid(d.id), - kind: "minecraft:item".to_owned(), - position: [d.position.x, d.position.y, d.position.z], - yaw: 0.0, - pitch: 0.0, - head_yaw: 0.0, - on_ground: d.on_ground, - velocity: [d.velocity.x, d.velocity.y, d.velocity.z], - data: 0, - meta: vec![(8, serializer::ITEM_STACK, Value::Item(stack))], - equipment: Vec::new(), - attributes: Vec::new(), - precise: false, - }); + let e = out.add(d.id as i32, entity_uuid(d.id), "minecraft:item"); + e.position = [d.position.x, d.position.y, d.position.z]; + e.on_ground = d.on_ground; + e.velocity = [d.velocity.x, d.velocity.y, d.velocity.z]; + e.meta.push((8, serializer::ITEM_STACK, Value::Item(stack))); } for o in &self.orbs { - out.push(EntityState { - id: o.id as i32, - uuid: entity_uuid(o.id), - kind: "minecraft:experience_orb".to_owned(), - position: [o.position.x, o.position.y, o.position.z], - yaw: 0.0, - pitch: 0.0, - head_yaw: 0.0, - on_ground: o.on_ground, - velocity: [o.velocity.x, o.velocity.y, o.velocity.z], - data: 0, - // ExperienceOrb.DATA_VALUE. - meta: vec![(8, serializer::INT, Value::Int(o.value as i32))], - equipment: Vec::new(), - attributes: Vec::new(), - precise: false, - }); + let e = out.add(o.id as i32, entity_uuid(o.id), "minecraft:experience_orb"); + e.position = [o.position.x, o.position.y, o.position.z]; + e.on_ground = o.on_ground; + e.velocity = [o.velocity.x, o.velocity.y, o.velocity.z]; + // ExperienceOrb.DATA_VALUE. + e.meta + .push((8, serializer::INT, Value::Int(o.value as i32))); } - self.lan_object_states(host_entity, hub, &mut out); - out + self.lan_object_states(host_entity, hub, out); } /// Run the hub for this tick and apply what the guests did. @@ -825,21 +803,23 @@ impl Game<'_> { // A dedicated server runs the hub without a host player. if state.is_some() || host.hub.config.dedicated { let has_guests = !host.hub.guests.is_empty(); - let entities = if has_guests { + let mut states = std::mem::take(&mut host.states); + if has_guests { let host_entity = state.as_ref().map(|s| s.entity_id); self.lan_assign_ids(); self.lan_riding(host_entity, &mut host.hub.riding); - self.lan_entities(host_entity, &mut host.hub) + self.lan_entities(host_entity, &mut host.hub, &mut states); } else { - Vec::new() - }; + states.clear(); + } + let entities = states.as_slice(); let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]); let events = { let clock_rate = self.network_clock_rate(); let mut ctx = TickCtx { world: &mut self.world, host: state.as_ref(), - entities: &entities, + entities, next_entity: &mut self.next_entity, spawn, difficulty: i32::from(self.ui.difficulty), @@ -880,7 +860,7 @@ impl Game<'_> { self.lan_log_event(event); } HostEvent::Joined(conn) => { - self.lan_guest_joined(&mut host, conn, state.as_ref(), &entities, spawn); + self.lan_guest_joined(&mut host, conn, state.as_ref(), entities, spawn); if self.options.dedicated.is_some() && let Some(g) = host.hub.guest(conn) { @@ -945,6 +925,7 @@ impl Game<'_> { } } } + host.states = states; } self.lan_flush_effects(&mut host); self.tick_guests(&mut host); @@ -1004,15 +985,15 @@ impl Game<'_> { g.dimension = in_place; } self.load_guest_records(host, conn); - let theirs; + let mut theirs = States::default(); let entities = if elsewhere { if let Err(e) = self.enter_level(Some(host), level) { log::error!("could not open {}: {e}", level.id()); return; } // A dedicated server has no host player. - theirs = self.lan_entities(None, &mut host.hub); - &theirs[..] + self.lan_entities(None, &mut host.hub, &mut theirs); + theirs.as_slice() } else { entities }; @@ -1207,6 +1188,8 @@ impl Game<'_> { .each_ref() .map(|s| s.as_ref().map(|s| s.item.clone())); m.extra.crouching = g.sneaking; + // Lying in its bed (LivingEntity.getBedOrientation). + m.extra.ints[1] = g.bed.map_or(0, |b| self.bed_facing(b)); // LivingEntity.updateSwingTime: the arm swing lan_swings started. m.anim.attack_anim_o = m.anim.attack_anim; horizon_client::mobs::ai::tick_swing(m); @@ -1218,6 +1201,20 @@ impl Game<'_> { } } + /// The bed at `head` as a sleeping model lies in it (`ints[1]`, + /// `villager::sleep_pose`): its `facing`. + pub(super) fn bed_facing(&self, head: [i32; 3]) -> i32 { + let state = self.world.block(head[0], head[1], head[2]); + let facing = self + .pack + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("facing")) + .map(String::as_str); + horizon_client::mobs::villager::bed_facing_code(facing) + } + /// The guests' models for the entity pass. pub(super) fn guest_model_geometry( &self, diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index af127f42a..bc224da9e 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -53,6 +53,10 @@ pub(super) struct GuestPlay { pub(super) merchant: Option, /// The inventory menu and the crafting table the guest crafts in. pub(super) crafting: super::lan_crafting::GuestCrafting, + /// The workstation menu the guest has open (game/lan_stations.rs). + pub(super) station: Option, + /// The lectern the guest reads (game/lan_stations.rs). + pub(super) lectern: Option, /// What the guest's body was given for its effects and enchantments. potions: super::potions::BodyPotions, /// `ServerPlayer.getStats` and the inventory `inventory_changed` last saw. @@ -64,6 +68,12 @@ pub(super) struct GuestPlay { xp_delay: u32, /// What last killed the guest outright (`/kill`): the death message's key. death_cause: Option, + /// The equipment modifiers on the guest's attributes (`apply_equipment`) + /// and the armour and main hand they were put on for: the hub's player + /// is a `ServerPlayer` too, whose worn armour counts + /// (`LivingEntity.collectEquipmentChanges`). + modifiers: Vec<(String, String)>, + equipped: Option>>, } /// A guest's command waiting for the hub (`LanHost::commands`). @@ -130,6 +140,8 @@ pub(super) struct GuestSwap { swings: u32, /// How many projectiles there were: those added since are the guest's. projectiles: usize, + /// The host's equipment modifiers. + modifiers: Vec<(String, String)>, } impl GuestPlay { @@ -193,15 +205,25 @@ impl Game<'_> { return None; } let i = host.hub.guests.iter().position(|g| g.conn == conn)?; - if host.hub.guests[i].motion.is_none() { + let fresh = host.hub.guests[i].motion.is_none(); + if fresh { let p = Vec3::new( host.hub.guests[i].position[0], host.hub.guests[i].position[1], host.hub.guests[i].position[2], ); host.hub.guests[i].motion = PlayerMotion::new(self.motion, p).ok().map(Box::new); + let kept = host.hub.guests[i].logs_kept.take(); + if let (Some(m), Some((hurts, attacks))) = (host.hub.guests[i].motion.as_mut(), kept) { + m.hurt_log = hurts; + m.attack_log = attacks; + } } let mut play = host.play.remove(&conn).unwrap_or_default(); + if fresh { + // A new body (joined, respawned, changed level): nothing on it yet. + play.equipped = None; + } let g = &mut host.hub.guests[i]; // The guest's body. let Some(mut motion) = g.motion.take() else { @@ -305,6 +327,17 @@ impl Game<'_> { let packets = std::mem::take(&mut self.guest_packets); let swings = self.swings_started; let projectiles = self.creatures.projectiles.len(); + let modifiers = std::mem::replace( + &mut self.applied_modifiers, + std::mem::take(&mut play.modifiers), + ); + // Its worn armour on its attributes, when it changed. + let mut equipped: Vec> = self.armor.to_vec(); + equipped.push(self.inventory.get(self.selected).cloned().flatten()); + if play.equipped.as_ref() != Some(&equipped) { + self.apply_equipment(); + play.equipped = Some(equipped); + } Some(GuestSwap { conn, i, @@ -350,6 +383,7 @@ impl Game<'_> { packets, swings, projectiles, + modifiers, }) } @@ -401,7 +435,9 @@ impl Game<'_> { packets, swings, projectiles, + modifiers, } = swap; + play.modifiers = std::mem::replace(&mut self.applied_modifiers, modifiers); // What the guest shot is theirs (Projectile.setOwner). for p in self.creatures.projectiles.iter_mut().skip(projectiles) { if p.owner == Some(horizon_client::mobs::Who::Player) && p.guest.is_none() { @@ -444,7 +480,13 @@ impl Game<'_> { self.container = container; self.screen = screen; self.sign_edit = host_sign; - self.book = host_book; + // A lectern the guest's use opened (LecternBlock.openScreen). + let guest_lectern = match std::mem::replace(&mut self.book, host_book) { + Some(super::books::BookScreen::View { + lectern: Some(key), .. + }) => Some(key), + _ => None, + }; self.command_block_screen = host_command_block; self.mount_menu = host_mount_menu; self.keys = host_keys; @@ -500,12 +542,14 @@ impl Game<'_> { g.health = m.health.health(); g.food = m.health.food.food; g.saturation = m.health.food.saturation; - // A teleport (commands) moves the guest. + // A teleport (commands, a pearl) moves the guest; a pearl's is + // sent even to where they stand (ServerPlayer.teleport). let at = [m.position.x, m.position.y, m.position.z]; m.sprinting = false; + let teleported = std::mem::take(&mut m.teleported); let moved: f64 = (0..3).map(|k| (at[k] - g.position[k]).powi(2)).sum(); g.motion = Some(Box::new(m)); - if moved > 0.0001 || turned { + if moved > 0.0001 || turned || teleported { host.hub.teleport(i, Some(at)); } } @@ -539,6 +583,9 @@ impl Game<'_> { if let Some(station) = opened_station { self.lan_station_opened(host, conn, station); } + if let Some(key) = guest_lectern { + self.lan_open_lectern(host, conn, key); + } if opened_table { self.lan_open_crafting(host, conn); } @@ -605,6 +652,13 @@ impl Game<'_> { _ => ("minecraft:furnace", "container.furnace"), }; (menu, title, Slots::Block(pos)) + } else if let Some(BlockEntity::Crafter(_)) = self.world.block_entities.get(&pos) { + // CrafterBlock.useWithoutItem: CrafterMenu over the block entity. + ( + "minecraft:crafter_3x3", + "container.crafter", + Slots::Block(pos), + ) } else if let Some(BlockEntity::Brewing(_)) = self.world.block_entities.get(&pos) { // BrewingStandBlock.useWithoutItem: BrewingStandMenu. ( @@ -647,6 +701,7 @@ impl Game<'_> { }; // ServerPlayer.openMenu closes the menu that was open. self.guest_container_closed(host, conn); + self.lan_station_closed(host, conn, None); host.hub.open_container( conn, menu, @@ -717,6 +772,7 @@ impl Game<'_> { conn, &C::BlockUpdate(play::BlockUpdate { pos: a.pos, state }), ); + self.destroy_block_progress(host.hub.guests[gi].entity_id, a.pos, -1); host.hub.broadcast_near( [ f64::from(a.pos[0]), @@ -799,6 +855,8 @@ impl Game<'_> { ], }; let hand = if p.hand == 1 { Hand::Off } else { Hand::Main }; + let logged = self.world.block_log.as_ref().map_or(0, Vec::len); + let heard = self.audio.capture.as_ref().map_or(0, Vec::len); let swung = self.as_guest(host, conn, |g| { g.forced_hit = Some(hit); g.guest_use = Some(GuestUse::OnBlock(hand)); @@ -809,6 +867,7 @@ impl Game<'_> { g.swings_started != swings }); self.lan_swing_back(host, conn, swung); + self.guest_use_sounds(host, conn, logged, heard); // The client predicted a result: correct it with what really is. for pos in [ p.pos, @@ -877,6 +936,16 @@ impl Game<'_> { S::ContainerClick(p) if self.lan_inventory_click(host, conn, &p) => {} S::ContainerClick(p) if self.lan_crafting_click(host, conn, &p) => {} S::ContainerClick(p) if self.lan_machine_click(host, conn, &p) => {} + S::ContainerClick(p) if self.lan_station_click(host, conn, &p) => {} + S::ContainerClick(p) if self.lan_lectern_click(host, conn, &p) => {} + S::ContainerButtonClick(p) => { + self.lan_station_button(host, conn, p.container, p.button); + } + S::RenameItem(p) => self.lan_station_rename(host, conn, &p.name), + S::ContainerSlotStateChanged(p) => { + self.lan_crafter_slot_state(host, conn, p.container, p.slot, p.enabled); + } + S::SetBeacon(p) => self.lan_station_beacon(host, conn, p.primary, p.secondary), S::SelectTrade(p) => self.lan_select_trade(host, conn, p.item), S::ContainerClose(p) if self.lan_merchant_closed(host, conn, Some(p.container)) => { let g = &mut host.hub.guests[gi]; @@ -884,7 +953,10 @@ impl Game<'_> { self.drop_guest_items(host, gi, vec![c]); } } - S::ContainerClose(p) if self.lan_crafting_closed(host, conn, Some(p.container)) => { + S::ContainerClose(p) + if self.lan_crafting_closed(host, conn, Some(p.container)) + || self.lan_station_closed(host, conn, Some(p.container)) => + { let g = &mut host.hub.guests[gi]; if let Some(c) = g.carried.take() { self.drop_guest_items(host, gi, vec![c]); @@ -1082,12 +1154,23 @@ impl Game<'_> { gi: usize, id: i32, ) -> Option<([f64; 3], [f64; 3])> { - let m = self.mobs.iter().find(|m| m.id as i32 == id)?; - let centre = [ - m.position.x, - m.position.y + m.kind.height * 0.5, - m.position.z, - ]; + let centre = match self.mobs.iter().find(|m| m.id as i32 == id) { + Some(m) => [ + m.position.x, + m.position.y + m.kind.height * 0.5, + m.position.z, + ], + // A dragon part or an end crystal (game/dragon.rs). + None => { + let b = self.tracked_special_box(id)?; + let (lo, hi) = (b.min_position(), b.max_position()); + [ + (lo.x + hi.x) / 2.0, + (lo.y + hi.y) / 2.0, + (lo.z + hi.z) / 2.0, + ] + } + }; let g = &mut host.hub.guests[gi]; let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]]; let d = [centre[0] - eye[0], centre[1] - eye[1], centre[2] - eye[2]]; @@ -1110,6 +1193,22 @@ impl Game<'_> { } return; } + // A ghast's fireball or a wind charge: turned along the guest's own + // view (ServerGamePacketListenerImpl.handleInteract, then + // Player.attack's AIM_DEFLECT). + if let Some(i) = self + .creatures + .projectiles + .iter() + .position(|p| p.id != 0 && p.id as i32 == id && super::deflect::redirectable(p)) + { + self.as_guest(host, conn, |g| { + if g.within_interaction_range(i) { + g.deflect(i); + } + }); + return; + } let (old_yaw, old_pitch) = (host.hub.guests[gi].yaw, host.hub.guests[gi].pitch); if self.look_at_entity(host, gi, id).is_none() { return; @@ -1336,7 +1435,10 @@ impl Game<'_> { g.food = 20; g.saturation = 5.0; g.sent_health = None; - g.motion = None; + if let Some(m) = g.motion.take() { + let m = *m; + g.logs_kept = Some((m.hurt_log, m.attack_log)); + } let mut xp = Experience { level: g.xp_level, progress: g.xp_progress, @@ -1372,6 +1474,7 @@ impl Game<'_> { /// Per tick, for every guest: dig, use items, pick up drops, die. pub(super) fn tick_guests(&mut self, host: &mut LanHost) { self.lan_merchant_tick(host); + self.lan_stations_tick(host); self.announce_guest_advancements(host); let conns: Vec = host .hub @@ -1684,7 +1787,12 @@ impl Game<'_> { play.mining = None; let start = play.dig_start; let state = self.world.block(pos[0], pos[1], pos[2]); - if !dug || self.res.facts().is_air(state) { + if !dug { + return; + } + if self.res.facts().is_air(state) { + // Already broken (the guest's own tick dug it out): only the crack goes. + self.guest_crack_gone(host, conn, pos); return; } let progress = self @@ -1733,18 +1841,7 @@ impl Game<'_> { self.as_guest(host, conn, |g| { let _ = g.break_block(pos); }); - if let Some(g) = host.hub.guest(conn) { - host.hub.broadcast_near( - [f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])], - 64.0, - &C::BlockDestruction(play::BlockDestruction { - id: g.entity_id, - pos, - progress: 255, - }), - Some(conn), - ); - } + self.guest_crack_gone(host, conn, pos); } /// The crack animation other players see. @@ -1756,6 +1853,18 @@ impl Game<'_> { let Some((pos, _)) = play.digging else { return; }; + // ServerPlayerGameMode.tick: a block gone while it is dug (the guest's own tick broke + // it, or something else did) clears the crack. + if play.last_progress >= 0 + && self + .res + .facts() + .is_air(self.world.block(pos[0], pos[1], pos[2])) + { + play.last_progress = -1; + self.guest_crack_gone(host, conn, pos); + return; + } let progress = play .mining .as_ref() @@ -1763,6 +1872,8 @@ impl Game<'_> { let swinging = play.swing.swinging(); if progress != play.last_progress && progress >= 0 { play.last_progress = progress; + // The host player sees it too (on the server thread its window is a guest). + self.destroy_block_progress(host.hub.guests[gi].entity_id, pos, progress); host.hub.broadcast_near( [f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])], 64.0, @@ -1777,6 +1888,25 @@ impl Game<'_> { let _ = swinging; } + /// `level.destroyBlockProgress(id, pos, -1)` for a guest: its crack on `pos` is gone, for the + /// host and the other guests. + fn guest_crack_gone(&mut self, host: &mut LanHost, conn: u32, pos: [i32; 3]) { + let Some(id) = host.hub.guest(conn).map(|g| g.entity_id) else { + return; + }; + self.destroy_block_progress(id, pos, -1); + host.hub.broadcast_near( + [f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])], + 64.0, + &C::BlockDestruction(play::BlockDestruction { + id, + pos, + progress: 255, + }), + Some(conn), + ); + } + /// Dropped items touching a guest go into their inventory. fn guest_pickups(&mut self, host: &mut LanHost, gi: usize) { let (conn, mode, position, id) = { @@ -1915,6 +2045,33 @@ impl Game<'_> { } } + /// `level.playSound(player, ...)` of a guest's use it predicted (`remote::hand_operated` + /// blocks only, as the guest decides): the others hear it now, the guest already did. + fn guest_use_sounds(&mut self, host: &mut LanHost, conn: u32, logged: usize, heard: usize) { + let changed: Vec<(i32, i32, i32)> = self + .world + .block_log + .as_ref() + .map_or(&[][..], |log| log.get(logged..).unwrap_or(&[])) + .to_vec(); + let facts = self.res.facts(); + if changed.is_empty() + || !changed.iter().all(|&(x, y, z)| { + super::remote::hand_operated(&facts.get(self.world.block(x, y, z)).name) + }) + { + return; + } + let Some(capture) = self.audio.capture.as_mut() else { + return; + }; + let sounds: Vec<_> = capture.drain(heard.min(capture.len())..).collect(); + for (name, at, volume, pitch) in sounds { + let source = horizon_client::settings::sound_source(&name) as i32; + host.hub.sound(&name, at, volume, pitch, source, Some(conn)); + } + } + /// Positional sounds and level events of the tick, for the guests. pub(super) fn lan_broadcast_effects(&mut self, host: &mut LanHost) { let sounds = self.audio.capture.take().unwrap_or_default(); @@ -1981,6 +2138,7 @@ impl Game<'_> { } play.swing.tick(); } + self.lan_host_crack(host); if self.swings_started != host.host_swings { host.host_swings = self.swings_started; if let (Some(p), Some(c)) = (self.player.as_ref(), self.swing.current) { @@ -1992,6 +2150,39 @@ impl Game<'_> { } } +impl Game<'_> { + /// The host player's crack, for the guests (`ServerLevel.destroyBlockProgress` from the + /// host's mining): each new stage, and -1 once it stops or breaks the block. + fn lan_host_crack(&mut self, host: &mut LanHost) { + let now = self + .mining + .as_ref() + .and_then(|m| (m.progress > 0.0).then(|| (m.pos, ((m.progress * 10.0) as i32).min(9)))); + if now == host.host_crack { + return; + } + let packet = |pos: [i32; 3], progress: u8| { + C::BlockDestruction(play::BlockDestruction { + id: host.host_entity, + pos, + progress, + }) + }; + let near = |pos: [i32; 3]| [f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])]; + if let Some((pos, _)) = host.host_crack + && now.is_none_or(|(p, _)| p != pos) + { + host.hub + .broadcast_near(near(pos), 64.0, &packet(pos, 255), None); + } + if let Some((pos, stage)) = now { + host.hub + .broadcast_near(near(pos), 64.0, &packet(pos, stage as u8), None); + } + host.host_crack = now; + } +} + /// ClientboundSwingAnimationPacket: the hand and the animation (its type and /// base duration; each client applies the swinger's haste and fatigue). fn swing_packet(id: i32, hand: Hand, animation: SwingAnimation) -> C { diff --git a/crates/horizon-client/src/game/lan_attributes.rs b/crates/horizon-client/src/game/lan_attributes.rs index 72d06c2ef..73942e770 100644 --- a/crates/horizon-client/src/game/lan_attributes.rs +++ b/crates/horizon-client/src/game/lan_attributes.rs @@ -83,17 +83,16 @@ impl Game<'_> { /// `LivingEntity.removeFrost`), what finalizeSpawn set, the baby speed /// modifier, its effects' modifiers, its equipment's, and what /// `/attribute` changed. - pub(super) fn mob_attributes(&self, m: &Mob) -> Vec { + pub(super) fn mob_attributes(&self, m: &Mob, out: &mut Vec) { let kind = m.kind.id.as_str(); - let mut out = Vec::new(); if let Some(a) = self.synced_attribute(kind, "minecraft:movement_speed") { - instance(&mut out, a, finalize::base_value(m, Attr::MovementSpeed)); + instance(out, a, finalize::base_value(m, Attr::MovementSpeed)); } if let Some(s) = m.extra.attributes.as_deref() { for (attr, v) in &s.bases { if let Some(a) = self.synced_attribute(kind, &format!("minecraft:{}", attr.name())) { - instance(&mut out, a, *v).base = *v; + instance(out, a, *v).base = *v; } } for x in &s.modifiers { @@ -101,7 +100,7 @@ impl Game<'_> { self.synced_attribute(kind, &format!("minecraft:{}", x.attr.name())) { add_modifier( - &mut out, + out, a, finalize::base_value(m, x.attr), AttributeModifier { @@ -122,7 +121,7 @@ impl Game<'_> { finalize::transient(m, Attr::MovementSpeed), ) { add_modifier( - &mut out, + out, a, finalize::base_value(m, Attr::MovementSpeed), AttributeModifier { @@ -150,7 +149,7 @@ impl Game<'_> { }; let start = base(attribute).unwrap_or_else(|| self.attribute_default(kind, attribute)); add_modifier( - &mut out, + out, a, start, AttributeModifier { @@ -172,10 +171,9 @@ impl Game<'_> { ("chest", e.chest.as_ref()), ("head", e.head.as_ref()), ], - &mut out, + out, ); - self.generic_attributes_of(Target::Mob(m.id), &mut out); - out + self.generic_attributes_of(Target::Mob(m.id), out); } /// An armor stand's synced instances: movement speed (its first diff --git a/crates/horizon-client/src/game/lan_crafting.rs b/crates/horizon-client/src/game/lan_crafting.rs index 6101ce99e..cb3b0a2c9 100644 --- a/crates/horizon-client/src/game/lan_crafting.rs +++ b/crates/horizon-client/src/game/lan_crafting.rs @@ -55,6 +55,7 @@ fn load_player(menu: &mut Menu, g: &Guest) { menu.set_player_item(OFFHAND, g.offhand.clone()); menu.selected = g.selected; menu.creative = g.creative(); + menu.levels = g.xp_level; menu.carried = g.carried.clone(); } @@ -83,27 +84,47 @@ fn place_back(menu: &mut Menu, env: &Env, stacks: Vec) { } impl Game<'_> { - fn menu_env(&self) -> Env<'_> { + pub(super) fn menu_env(&self) -> Env<'_> { Env { items: self.res.items(), recipes: self.res.recipes(), brewing: &self.res.stations().brewing, banners: &self.res.stations().banners, + station_recipes: &self.res.stations().recipes, + enchantments: &self.res.stations().enchantments, + names: &self.pack.names, trade: None, + maps: None, } } /// Runs `op` on the guest's menu with their inventory copied in and back. - fn guest_menu_op( + pub(super) fn guest_menu_op( &mut self, host: &mut LanHost, gi: usize, menu: &mut Menu, op: impl FnOnce(&mut Menu, &Env) -> R, ) -> R { - let env = self.menu_env(); + // The cartography table reads and makes the host level's maps. + let maps = (menu.kind() == Kind::Cartography).then(|| { + let g = &host.hub.guests[gi]; + let held: Vec = (0..menu.slot_count()) + .filter_map(|s| menu.slot(s).cloned()) + .chain(g.inventory.iter().flatten().cloned()) + .chain(g.carried.clone()) + .collect(); + self.level_maps(&held) + }); + let env = Env { + maps: maps.as_ref().map(|m| m as &dyn horizon_client::menu::Maps), + ..self.menu_env() + }; load_player(menu, &host.hub.guests[gi]); let result = op(menu, &env); + if let Some(maps) = maps { + self.register_made_maps(maps); + } let dropped = std::mem::take(&mut menu.dropped); let equipped = std::mem::take(&mut menu.equipped); menu.drops.clear(); @@ -201,8 +222,14 @@ impl Game<'_> { (Kind::Furnace(recipe), f.items.to_vec()) } Some(BlockEntity::Brewing(b)) => (Kind::Brewing, b.items.to_vec()), + Some(BlockEntity::Crafter(c)) => (Kind::CrafterBlock, c.items.to_vec()), _ => return false, }; + // CrafterBlockEntity.containerData: the disabled slots, then triggered. + let crafter_data = match self.world.block_entities.get(&pos) { + Some(BlockEntity::Crafter(c)) => Some((c.disabled, c.triggered)), + _ => None, + }; if host.hub.guests[gi].spectator() { return true; } @@ -219,6 +246,13 @@ impl Game<'_> { for (k, s) in items.iter().enumerate() { menu.set_slot(env, k, s.clone()); } + // After the slots: setting a disabled slot (CrafterBlockEntity.setItem) enables it. + if let Some((disabled, triggered)) = crafter_data { + for (k, d) in disabled.iter().enumerate() { + menu.data[k] = i32::from(*d); + } + menu.data[9] = i32::from(triggered); + } let before: Vec<_> = (0..menu.slot_count()) .map(|s| menu.slot(s).cloned()) .collect(); @@ -241,6 +275,13 @@ impl Game<'_> { b.items[k] = menu.slot(k).cloned(); } } + // CrafterBlockEntity.setItem: filling a disabled slot enables it. + Some(BlockEntity::Crafter(c)) => { + for k in 0..9 { + c.items[k] = menu.slot(k).cloned(); + c.disabled[k] = menu.data[k] == 1; + } + } _ => {} } host.play.entry(conn).or_default().crafting.machine = Some((p.container, menu)); @@ -248,6 +289,39 @@ impl Game<'_> { true } + /// `ServerGamePacketListenerImpl.handleContainerSlotStateChanged`: a + /// guest's crafter slot toggle (`CrafterBlockEntity.setSlotState`) in + /// their open crafter window. + pub(super) fn lan_crafter_slot_state( + &mut self, + host: &mut LanHost, + conn: u32, + window: i32, + slot: i32, + enabled: bool, + ) { + let Some(pos) = host + .hub + .guest(conn) + .filter(|g| !g.spectator()) + .and_then(|g| g.menu.as_ref()) + .filter(|m| window != 0 && m.window == window) + .and_then(|m| match m.slots { + Slots::Block(pos) => Some(pos), + _ => None, + }) + else { + return; + }; + if let (Some(BlockEntity::Crafter(c)), Ok(slot)) = ( + self.world.block_entities.get_mut(&pos), + usize::try_from(slot), + ) { + c.set_slot_state(slot, enabled); + self.world.modified.insert((pos.0 >> 4, pos.2 >> 4)); + } + } + /// ServerGamePacketListenerImpl.handlePlaceRecipe: the guest's recipe /// book places a known recipe in their inventory grid or crafting table /// (`ServerPlaceRecipe`), and answers with a ghost recipe when the items @@ -331,6 +405,7 @@ impl Game<'_> { /// The guest opened a crafting table (`CraftingTableBlock.getMenuProvider`). pub(super) fn lan_open_crafting(&mut self, host: &mut LanHost, conn: u32) { self.lan_crafting_closed(host, conn, None); + self.lan_station_closed(host, conn, None); // The container it replaces loses its opener. self.guest_container_closed(host, conn); let title = horizon_protocol::text::translatable("container.crafting", &[]); @@ -430,22 +505,35 @@ impl Game<'_> { None => return false, } }; - if grid.is_empty() { - return true; + if !grid.is_empty() { + self.lan_place_back(host, gi, grid); } - let mut menu = Menu::new(Kind::Inventory); - self.guest_menu_op(host, gi, &mut menu, |menu, env| place_back(menu, env, grid)); true } - /// A guest left: what their crafting grids held goes back into their + /// `Inventory.placeItemBackInInventory` of `stacks` for guest `gi`, what + /// doesn't fit dropped (`clearContainer`). + pub(super) fn lan_place_back(&mut self, host: &mut LanHost, gi: usize, stacks: Vec) { + let mut menu = Menu::new(Kind::Inventory); + self.guest_menu_op(host, gi, &mut menu, |menu, env| { + place_back(menu, env, stacks) + }); + } + + /// A guest left: what their crafting grids and workstation held goes back into their /// inventory before it is saved (dropped where they stood if full). pub(super) fn lan_crafting_left(&mut self, host: &mut LanHost, g: &mut Guest) { - let table = host.play.remove(&g.conn).and_then(|p| p.crafting.table); + let play = host.play.remove(&g.conn); let mut grid: Vec = g.craft_grid.iter_mut().filter_map(Option::take).collect(); g.craft_result = None; - if let Some((_, _, menu)) = table { - grid.extend((1..10).filter_map(|s| menu.slot(s).cloned())); + if let Some(play) = play { + if let Some((_, _, menu)) = play.crafting.table { + grid.extend((1..10).filter_map(|s| menu.slot(s).cloned())); + } + // A workstation's inputs too. + if let Some(station) = &play.station { + grid.extend(super::lan_stations::station_inputs(station)); + } } if grid.is_empty() { return; diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index 020ec6adc..404d00c46 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -5,7 +5,7 @@ //! synched data that differs from the defaults), and who rides what. use super::Game; use horizon_client::lan::{ - entity::{EntityState, Riding}, + entity::{EntityState, Riding, States}, hub::Hub, }; use horizon_protocol::entity_data::{Value, serializer}; @@ -107,7 +107,7 @@ impl Game<'_> { &self, host_entity: Option, hub: &mut Hub, - out: &mut Vec, + out: &mut States, ) { for b in &self.boats { let p = b.position; @@ -268,12 +268,7 @@ impl Game<'_> { /// Primed TNT, falling blocks, projectiles, tridents, firework rockets and /// end crystals, as guests track them. - fn lan_projectile_states( - &self, - host_entity: Option, - hub: &mut Hub, - out: &mut Vec, - ) { + fn lan_projectile_states(&self, host_entity: Option, hub: &mut Hub, out: &mut States) { let owner = |who: Option| match who { Some(horizon_client::mobs::Who::Mob(id)) => id as i32, Some(horizon_client::mobs::Who::Player) => host_entity.unwrap_or(0), @@ -406,6 +401,7 @@ impl Game<'_> { } out.push(e); } + out.extend(self.lan_dragon_state()); } } diff --git a/crates/horizon-client/src/game/lan_pvp.rs b/crates/horizon-client/src/game/lan_pvp.rs index a7347ab2a..d2c643088 100644 --- a/crates/horizon-client/src/game/lan_pvp.rs +++ b/crates/horizon-client/src/game/lan_pvp.rs @@ -3,9 +3,26 @@ //! is worked out as the attacker (weapon, attack strength, critical hit, //! enchantments, a mace's smash) and lands on the victim like any player //! attack (blocking, armour, knockback), when the `pvp` game rule allows it -//! (`ServerPlayer.canHarmPlayer`, `isPvpAllowed`). +//! (`ServerPlayer.canHarmPlayer`, `isPvpAllowed`). A player's arrow on +//! another player lands the same way. use super::{Game, lan::LanHost, lan_mobs::guest_bounds, ray_box, view_vector}; +use horizon_client::{ + Result, + mobs::Who, + projectiles::{Hit, Projectile, ProjectileKind}, +}; + +/// The player projectiles that meet other players: arrows (their hurt), and +/// snowballs and eggs, which break on them (`Player.hurtServer` takes no 0 +/// damage). Pearls, potions and wind charges fly past players as before. +pub(super) fn meets_players(kind: &ProjectileKind) -> bool { + matches!( + kind, + ProjectileKind::Arrow { .. } | ProjectileKind::Snowball | ProjectileKind::Egg + ) +} + /// Who a player's attack lands on. #[derive(Clone, Copy)] pub(super) enum Victim { @@ -105,6 +122,89 @@ impl Game<'_> { }) } + /// The guests by connection, with their entity ids. + pub(super) fn lan_guest_entities(&self) -> Vec<(u32, u32)> { + self.lan.as_ref().map_or_else(Vec::new, |host| { + host.hub + .guests + .iter() + .map(|g| (g.conn, g.entity_id as u32)) + .collect() + }) + } + + /// The player a player's projectile hit, when it hit one: the host for a + /// guest's shot, or a guest. + pub(super) fn projectile_pvp_victim(&self, p: &Projectile, hit: Hit) -> Option { + if p.owner != Some(Who::Player) || !meets_players(&p.kind) { + return None; + } + let Hit::Entity { who, .. } = hit else { + return None; + }; + match who { + Who::Player => p.guest.map(|_| Victim::Host), + Who::Mob(id) => self + .lan + .as_ref()? + .hub + .guests + .iter() + .find(|g| g.entity_id as u32 == id) + .map(|g| Victim::Guest(g.conn)), + } + } + + /// A player's projectile on a player: the hit runs as the victim, whose + /// hurt refuses it when the `pvp` game rule or their teams forbid it + /// (`ServerPlayer.canHarmPlayer`; `AbstractArrow.onHitEntity` then turns + /// the arrow back). + pub(super) fn projectile_hits_player( + &mut self, + p: &Projectile, + hit: Hit, + victim: Victim, + ) -> Result<()> { + let Hit::Entity { at, .. } = hit else { + return Ok(()); + }; + let Some(mut host) = self.lan.take() else { + return self.projectile_hit(p, hit); + }; + let team_of = |game: &Self, name: &str| game.score.board.players_team(name).cloned(); + let attacker = match p.guest { + Some(conn) => host.hub.guest(conn).and_then(|g| team_of(self, &g.name)), + None => self.player_team().cloned(), + }; + let target = match victim { + Victim::Host => self.player_team().cloned(), + Victim::Guest(conn) => host.hub.guest(conn).and_then(|g| team_of(self, &g.name)), + }; + let refused = !(self.ui.rules.bool("pvp") + && horizon_client::scoreboard::teams_allow_damage(target.as_ref(), attacker.as_ref())); + let on_player = Hit::Entity { + who: Who::Player, + at, + }; + let result = match victim { + Victim::Host => { + self.lan = Some(host); + self.combat.refuse_player_hit = refused; + let r = self.projectile_hit(p, on_player); + self.combat.refuse_player_hit = false; + return r; + } + Victim::Guest(conn) => self.guest_hit_by(&mut host, conn, |g| { + g.combat.refuse_player_hit = refused; + let r = g.projectile_hit(p, on_player); + g.combat.refuse_player_hit = false; + r + }), + }; + self.lan = Some(host); + result.unwrap_or(Ok(())) + } + /// The hit landing on the victim with its extra knockback, then the /// attacker's attack sound. Whether the victim was hurt. pub(super) fn pvp_land(&mut self, host: &mut LanHost, victim: Victim, s: &Strike) -> bool { diff --git a/crates/horizon-client/src/game/lan_stations.rs b/crates/horizon-client/src/game/lan_stations.rs new file mode 100644 index 000000000..25921f936 --- /dev/null +++ b/crates/horizon-client/src/game/lan_stations.rs @@ -0,0 +1,672 @@ +//! Workstation menus for LAN guests: the screen a guest's use opens runs on +//! the host's menu engine (`horizon_client::menu`), the one single player +//! uses, with vanilla's packets: OpenScreen with the station's `MenuType`, +//! container clicks, `ServerboundContainerButtonClickPacket`, the content and +//! data slot sync after each (`broadcastChanges`), and the inputs back into +//! the inventory when the menu closes (`AbstractContainerMenu.clearContainer`). +use super::{ + Game, + lan::LanHost, + lan_crafting::input, + stations::{Kind as StationKind, Station}, +}; +use horizon_client::{ + containers::BlockEntity, + items::ItemStack, + menu::{Kind, Menu}, +}; +use horizon_core::random::RandomSource; +use horizon_protocol::packets::play::{self, Clientbound as C}; + +/// A guest's open workstation menu. +pub(super) struct GuestStation { + window: i32, + state: i32, + kind: StationKind, + pos: [i32; 3], + menu: Box, + /// The data slots the client was last sent. + sent_data: Vec, + /// The game time of the menu's last sound (`lastSoundTime`). + last_sound: u64, +} + +/// A guest's open lectern: `LecternMenu` over the block entity, made on the +/// menu engine for each click (`Game::lectern_menu`). +pub(super) struct GuestLectern { + window: i32, + state: i32, + key: (i32, i32, i32), + /// The book and page the client was last sent (`broadcastChanges`). + sent: Option<(Option, i32)>, +} + +/// The `MenuType`, the engine's menu and the input slots +/// (`clearContainer`'s container) of a station a guest can use. +fn menu_of(kind: StationKind) -> Option<(&'static str, Kind, std::ops::Range)> { + Some(match kind { + StationKind::Loom => ("minecraft:loom", Kind::Loom, 0..3), + StationKind::Stonecutter => ("minecraft:stonecutter", Kind::Stonecutter, 0..1), + StationKind::Grindstone => ("minecraft:grindstone", Kind::Grindstone, 0..2), + StationKind::Anvil => ("minecraft:anvil", Kind::Anvil, 0..2), + StationKind::Smithing => ("minecraft:smithing", Kind::Smithing, 0..3), + StationKind::Enchanting => ("minecraft:enchantment", Kind::Enchanting, 0..2), + StationKind::Beacon => ("minecraft:beacon", Kind::Beacon, 0..1), + StationKind::Cartography => ("minecraft:cartography_table", Kind::Cartography, 0..2), + _ => return None, + }) +} + +impl Game<'_> { + /// A workstation a guest's use opened (`ServerPlayer.openMenu`); false + /// when guests can't use that one yet. + pub(super) fn lan_open_station( + &mut self, + host: &mut LanHost, + conn: u32, + station: &Station, + ) -> bool { + let Some((menu_type, kind, _)) = menu_of(station.kind) else { + return false; + }; + self.lan_station_closed(host, conn, None); + self.lan_crafting_closed(host, conn, None); + // The container it replaces loses its opener. + self.guest_container_closed(host, conn); + let title = horizon_protocol::text::translatable(station.kind.title_key(), &[]); + let Some(window) = host.hub.open_window(conn, menu_type, title) else { + return true; + }; + let mut menu = Box::new(Menu::new(kind)); + if let Some(g) = host.hub.guests.iter_mut().find(|g| g.conn == conn) + && kind == Kind::Enchanting + { + // Player.enchantmentSeed, made when first needed. + if g.xp_seed == 0 { + g.xp_seed = self.world.random.next_int(); + } + menu.data[3] = g.xp_seed; + } + if kind == Kind::Beacon { + menu.data = self.beacon_data(host, station.pos).to_vec(); + } + host.play.entry(conn).or_default().station = Some(GuestStation { + window, + state: 0, + kind: station.kind, + pos: station.pos, + menu, + sent_data: Vec::new(), + last_sound: 0, + }); + self.lan_send_station(host, conn); + true + } + + /// Runs `op` on the guest's open station (window `window`, any when + /// None) with their inventory in it, then sends what changed. False when + /// no such window is open. + fn lan_station_op( + &mut self, + host: &mut LanHost, + conn: u32, + window: Option, + op: impl FnOnce(&mut Menu, &horizon_client::menu::Env), + ) -> bool { + let Some(mut gs) = host + .play + .get_mut(&conn) + .and_then(|p| p.station.take_if(|s| window.is_none_or(|w| s.window == w))) + else { + return false; + }; + if let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) + && !host.hub.guests[gi].spectator() + { + self.guest_menu_op(host, gi, &mut gs.menu, op); + self.lan_station_sounds(&mut gs); + if let Some(amount) = gs.menu.ground.take() { + self.grindstone_taken(gs.pos, amount); + } + self.lan_station_combined(host, conn, &mut gs); + if let Some(button) = gs.menu.enchant_button.take() { + self.lan_enchant(host, gi, &mut gs, button); + } + if std::mem::take(&mut gs.menu.enchant_changed) { + self.lan_enchant_offers(host, gi, &mut gs); + } + } + host.play.entry(conn).or_default().station = Some(gs); + self.lan_send_station(host, conn); + true + } + + /// `LecternBlock.openScreen` for a guest: `minecraft:lectern` over the + /// block entity, with its book and page. + pub(super) fn lan_open_lectern(&mut self, host: &mut LanHost, conn: u32, key: (i32, i32, i32)) { + self.lan_station_closed(host, conn, None); + self.lan_crafting_closed(host, conn, None); + self.guest_container_closed(host, conn); + let title = horizon_protocol::text::translatable("container.lectern", &[]); + let Some(window) = host.hub.open_window(conn, "minecraft:lectern", title) else { + return; + }; + host.play.entry(conn).or_default().lectern = Some(GuestLectern { + window, + state: 0, + key, + sent: None, + }); + self.lan_send_lectern(host, conn, true); + } + + /// The lectern's book and page for the client: everything (`all`), or + /// what changed since it was last sent. + fn lan_send_lectern(&mut self, host: &mut LanHost, conn: u32, all: bool) { + let Some(gl) = host.play.get_mut(&conn).and_then(|p| p.lectern.as_mut()) else { + return; + }; + let (book, page) = match self.world.block_entities.get(&gl.key) { + Some(BlockEntity::Lectern(l)) => (l.book.clone(), l.page), + _ => (None, 0), + }; + let now = Some((book.clone(), page)); + if !all && gl.sent == now { + return; + } + let page_changed = gl.sent.as_ref().is_none_or(|(_, p)| *p != page); + gl.sent = now; + gl.state = (gl.state + 1) & 0x7FFF; + let (window, state) = (gl.window, gl.state); + let carried = host + .hub + .guests + .iter() + .find(|g| g.conn == conn) + .and_then(|g| g.carried.clone()); + let content = C::ContainerSetContent(play::ContainerSetContent { + container: window, + state, + items: vec![host.hub.stack(&book)], + carried: host.hub.stack(&carried), + }); + host.hub.send_to(conn, &content); + if all || page_changed { + host.hub.send_to( + conn, + &C::ContainerSetData(play::ContainerSetData { + container: window, + id: 0, + value: page as i16, + }), + ); + } + } + + /// Runs `op` on the guest's lectern menu (window `window`) with their + /// inventory, the block entity takes the book and page back, and the + /// client gets what changed. False when no such window is open. + fn lan_lectern_op( + &mut self, + host: &mut LanHost, + conn: u32, + window: i32, + op: impl FnOnce(&mut Menu, &horizon_client::menu::Env), + ) -> bool { + let Some(key) = host + .play + .get(&conn) + .and_then(|p| p.lectern.as_ref()) + .filter(|l| l.window == window) + .map(|l| l.key) + else { + return false; + }; + if let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) + && !host.hub.guests[gi].spectator() + && let Some(mut menu) = self.lectern_menu(key) + { + // Player.mayBuild: survival and creative. + let may_build = matches!(host.hub.guests[gi].game_mode, 0 | 1); + self.guest_menu_op(host, gi, &mut menu, |menu, env| { + menu.may_build = may_build; + op(menu, env); + }); + self.lectern_menu_done(key, &menu); + } + self.lan_send_lectern(host, conn, true); + true + } + + /// A click on the guest's lectern window; false for other windows. + pub(super) fn lan_lectern_click( + &mut self, + host: &mut LanHost, + conn: u32, + p: &play::ContainerClick, + ) -> bool { + self.lan_lectern_op(host, conn, p.container, |menu, env| { + let _ = menu.click(env, i32::from(p.slot), i32::from(p.button), input(p.input)); + }) + } + + /// The rest of a taken anvil or smithing result's `onTake`: the guest + /// pays the levels, the anvil wears (level event 1030 or 1029), the + /// smithing table sounds (1044). + fn lan_station_combined(&mut self, host: &mut LanHost, conn: u32, gs: &mut GuestStation) { + let change = std::mem::take(&mut gs.menu.level_change); + if change != 0 { + self.as_guest(host, conn, |g| g.give_levels(change)); + } + if !std::mem::take(&mut gs.menu.combined) { + return; + } + if gs.kind == StationKind::Smithing { + self.level_event_at(1044, gs.pos, 0); + } else { + let creative = gs.menu.creative; + // A broken anvil closes the menu on the next stillValid check. + self.anvil_used(gs.pos, creative); + } + } + + /// `EnchantmentMenu.slotsChanged` with a level: the costs and clues for + /// the guest's seed and the bookshelves around the table. + fn lan_enchant_offers(&mut self, host: &LanHost, gi: usize, gs: &mut GuestStation) { + let seed = host.hub.guests[gi].xp_seed; + let bookcases = self.count_bookshelves(gs.pos); + let offers = horizon_client::stations::enchant_offers( + &self.res.stations().enchantments, + self.res.items(), + seed, + bookcases, + gs.menu.slot(0), + ); + for i in 0..3 { + gs.menu.data[i] = offers.costs[i]; + let clue = offers.clues[i].as_ref(); + gs.menu.data[4 + i] = clue + .and_then(|(e, _)| host.hub.registry_id("minecraft:enchantment", e)) + .unwrap_or(-1); + gs.menu.data[7 + i] = clue.map_or(-1, |(_, l)| *l as i32); + } + gs.menu.data[3] = seed; + } + + /// `EnchantmentMenu.clickMenuButton`'s `access.execute`: the item gets + /// the offer's enchantments, the guest pays its levels and lapis and + /// gets a new seed, the table sounds, and the offers are made again. + fn lan_enchant(&mut self, host: &mut LanHost, gi: usize, gs: &mut GuestStation, button: usize) { + let Some(item) = gs.menu.slot(0).cloned() else { + return; + }; + let g = &host.hub.guests[gi]; + let (seed, creative, conn) = (g.xp_seed, g.creative(), g.conn); + let Some(enchanted) = horizon_client::stations::apply_enchantment( + &self.res.stations().enchantments, + self.res.items(), + seed, + button, + gs.menu.data[button], + &item, + ) else { + return; + }; + let need = button as i32 + 1; + // Player.onEnchantmentPerformed, and EnchantmentMenu's awardStat(ENCHANT_ITEM). + self.as_guest(host, conn, |game| { + game.give_levels(-need); + game.stats.custom("enchant_item", 1); + }); + host.hub.guests[gi].xp_seed = self.world.random.next_int(); + let env = self.menu_env(); + let lapis = gs.menu.slot(1).cloned().filter(|_| !creative).map(|mut l| { + l.count = l.count.saturating_sub(need as u32); + l + }); + gs.menu.set_slot(&env, 0, Some(enchanted)); + if !creative { + gs.menu.set_slot(&env, 1, lapis.filter(|l| l.count > 0)); + } + gs.menu.enchant_changed = false; + self.lan_enchant_offers(host, gi, gs); + let pitch = self.world.random.next_float() * 0.1 + 0.9; + let at = gs.pos.map(|v| f64::from(v) + 0.5); + self.audio.play( + "minecraft:block.enchantment_table.use", + Some(at), + 1.0, + pitch, + ); + } + + /// `ServerGamePacketListenerImpl.handleRenameItem`: the guest's anvil + /// takes the name (`AnvilMenu.setItemName`). + pub(super) fn lan_station_rename(&mut self, host: &mut LanHost, conn: u32, name: &str) { + let anvil = host + .play + .get(&conn) + .and_then(|p| p.station.as_ref()) + .is_some_and(|s| s.kind == StationKind::Anvil); + if anvil { + self.lan_station_op(host, conn, None, |menu, env| { + menu.rename(env, name); + }); + } + } + + /// The sounds the menu played, at the station (heard by everyone around, + /// as `level.playSound(null, pos, ...)`), once per tick. + fn lan_station_sounds(&mut self, gs: &mut GuestStation) { + let sounds = std::mem::take(&mut gs.menu.sounds); + if sounds.is_empty() || gs.last_sound == self.ticks { + return; + } + gs.last_sound = self.ticks; + let at = gs.pos.map(|v| f64::from(v) + 0.5); + for sound in sounds { + self.audio.play(sound, Some(at), 1.0, 1.0); + } + } + + /// A click on the guest's station window; false for other windows. + pub(super) fn lan_station_click( + &mut self, + host: &mut LanHost, + conn: u32, + p: &play::ContainerClick, + ) -> bool { + self.lan_station_op(host, conn, Some(p.container), |menu, env| { + let _ = menu.click(env, i32::from(p.slot), i32::from(p.button), input(p.input)); + }) + } + + /// `ServerGamePacketListenerImpl.handleContainerButtonClick`: + /// `clickMenuButton`, then `broadcastChanges` when the menu took it. + pub(super) fn lan_station_button( + &mut self, + host: &mut LanHost, + conn: u32, + window: i32, + id: i32, + ) { + // LecternMenu's page buttons and Take Book. + if self.lan_lectern_op(host, conn, window, |menu, env| { + menu.button(env, id); + }) { + return; + } + self.lan_station_op(host, conn, Some(window), |menu, env| { + menu.button(env, id); + }); + } + + /// The whole station menu and its changed data slots for the client + /// (`sendAllDataToRemote` / `broadcastChanges`). + fn lan_send_station(&mut self, host: &mut LanHost, conn: u32) { + let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else { + return; + }; + let Some(gs) = host.play.get_mut(&conn).and_then(|p| p.station.as_mut()) else { + return; + }; + gs.state = (gs.state + 1) & 0x7FFF; + let own = gs.menu.slot_count() - 36; + let mut items: Vec> = + (0..own).map(|s| gs.menu.slot(s).cloned()).collect(); + let g = &host.hub.guests[gi]; + items.extend((9..36).chain(0..9).map(|i| g.inventory[i].clone())); + let carried = g.carried.clone(); + let packet = C::ContainerSetContent(play::ContainerSetContent { + container: gs.window, + state: gs.state, + items: items.iter().map(|s| host.hub.stack(s)).collect(), + carried: host.hub.stack(&carried), + }); + gs.sent_data.resize(gs.menu.data.len(), i32::MIN); + let mut data = Vec::new(); + for (k, &v) in gs.menu.data.iter().enumerate() { + if gs.sent_data[k] != v { + gs.sent_data[k] = v; + data.push(C::ContainerSetData(play::ContainerSetData { + container: gs.window, + id: k as i16, + value: v as i16, + })); + } + } + host.hub.send_to(conn, &packet); + for packet in data { + host.hub.send_to(conn, &packet); + } + } + + /// `AbstractContainerMenu.removed` of the guest's station (`window`; + /// None closes it whichever it is): the carried stack and the inputs go + /// back to the inventory, what doesn't fit is dropped. False when no such + /// window is open. + pub(super) fn lan_station_closed( + &mut self, + host: &mut LanHost, + conn: u32, + window: Option, + ) -> bool { + // A lectern's menu keeps nothing of its own (the book is the block entity's). + let lectern = host + .play + .get_mut(&conn) + .and_then(|p| p.lectern.take_if(|l| window.is_none_or(|w| l.window == w))); + if lectern.is_some() { + // AbstractContainerMenu.removed: the carried stack goes back. + if let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) + && let Some(carried) = host.hub.guests[gi].carried.take() + { + self.lan_place_back(host, gi, vec![carried]); + } + if window.is_some() { + return true; + } + } + let Some(gs) = host + .play + .get_mut(&conn) + .and_then(|p| p.station.take_if(|s| window.is_none_or(|w| s.window == w))) + else { + return false; + }; + let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else { + return true; + }; + // AbstractContainerMenu.removed: the carried stack first, then the inputs. + let mut back: Vec = host.hub.guests[gi].carried.take().into_iter().collect(); + let inputs = station_inputs(&gs); + if gs.kind == StationKind::Beacon { + // BeaconMenu.removed drops the payment (player.drop). + if !back.is_empty() { + self.lan_place_back(host, gi, std::mem::take(&mut back)); + } + self.drop_guest_items(host, gi, inputs); + } else { + back.extend(inputs); + } + if !back.is_empty() { + self.lan_place_back(host, gi, back); + } + true + } + + /// `BeaconBlockEntity.dataAccess`: the pyramid's levels and the powers + /// (`BeaconMenu.encodeEffect`: the `mob_effect` id + 1, 0 for none). + fn beacon_data(&self, host: &LanHost, pos: [i32; 3]) -> [i32; 3] { + let Some(BlockEntity::Beacon(b)) = self.world.block_entities.get(&(pos[0], pos[1], pos[2])) + else { + return [0; 3]; + }; + let encode = |e: &Option| { + e.as_deref() + .and_then(|n| host.hub.registry_id("minecraft:mob_effect", n)) + .map_or(0, |id| id + 1) + }; + [b.levels, encode(&b.primary), encode(&b.secondary)] + } + + /// `ServerGamePacketListenerImpl.handleSetBeaconPacket`: the guest's + /// beacon menu takes the powers (`BeaconMenu.updateEffects`), and they + /// become the block entity's (`dataAccess.set`: the power_select sound + /// while the beam is up). + pub(super) fn lan_station_beacon( + &mut self, + host: &mut LanHost, + conn: u32, + primary: Option, + secondary: Option, + ) { + let Some(pos) = host + .play + .get(&conn) + .and_then(|p| p.station.as_ref()) + .filter(|s| s.kind == StationKind::Beacon) + .map(|s| s.pos) + else { + return; + }; + // An id the registry doesn't have fails the packet's codec. + let mut powers: [Option<(i32, String)>; 2] = [None, None]; + for (k, id) in [primary, secondary].into_iter().enumerate() { + if let Some(id) = id { + let Some(name) = host.hub.registry_name("minecraft:mob_effect", id) else { + return; + }; + powers[k] = Some((id, name.to_owned())); + } + } + let data = self.beacon_data(host, pos); + let mut updated = false; + self.lan_station_op(host, conn, None, |menu, env| { + menu.data.copy_from_slice(&data); + let power = |k: usize| powers[k].as_ref().map(|(id, n)| (*id, n.as_str())); + updated = menu.beacon_update(env, power(0), power(1)); + }); + if !updated { + return; + } + let [primary, secondary] = powers.map(|p| p.map(|(_, n)| n)); + let mut select_sound = false; + if let Some(BlockEntity::Beacon(b)) = + self.world.block_entities.get_mut(&(pos[0], pos[1], pos[2])) + { + b.primary = primary; + b.secondary = secondary; + select_sound = !b.sections.is_empty(); + } + if select_sound { + self.beacon_sound(pos, "minecraft:block.beacon.power_select"); + } + self.world.modified.insert((pos[0] >> 4, pos[2] >> 4)); + } + + /// `ServerPlayer.doTick`'s `stillValid`: a guest's station closes once its + /// block is gone or the guest is out of reach (`isWithinBlockInteractionRange(pos, 4)`). + pub(super) fn lan_stations_tick(&mut self, host: &mut LanHost) { + self.lan_lecterns_tick(host); + let conns: Vec = host + .play + .iter() + .filter(|(_, p)| p.station.is_some()) + .map(|(c, _)| *c) + .collect(); + for conn in conns { + let Some(g) = host.hub.guests.iter().find(|g| g.conn == conn) else { + continue; + }; + if !host.hub.here(g) { + continue; + } + let Some(gs) = host.play.get(&conn).and_then(|p| p.station.as_ref()) else { + continue; + }; + let [x, y, z] = gs.pos; + let name = &self.res.facts().get(self.world.block(x, y, z)).name; + let block = StationKind::from_block(name) == Some(gs.kind); + let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]]; + // The block interaction range (4.5, creative 5) and the buffer. + let reach = if g.creative() { 5.0 } else { 4.5 } + 4.0; + let near = (0..3) + .map(|k| { + let lo = f64::from(gs.pos[k]); + (lo - eye[k]).max(eye[k] - lo - 1.0).max(0.0).powi(2) + }) + .sum::() + < reach * reach; + if !(block && near) { + let window = gs.window; + self.lan_station_closed(host, conn, Some(window)); + host.hub.send_to( + conn, + &C::ContainerClose(play::ContainerClose { container: window }), + ); + } else if gs.kind == StationKind::Beacon { + // The beacon's data slots follow its block entity. + let data = self.beacon_data(host, gs.pos); + if let Some(gs) = host.play.get_mut(&conn).and_then(|p| p.station.as_mut()) + && gs.menu.data[..] != data[..] + { + gs.menu.data.copy_from_slice(&data); + self.lan_send_station(host, conn); + } + } + } + } +} + +impl Game<'_> { + /// The guests' lecterns each tick: `stillValid` (the block entity, its + /// book, the reach) closes them, and `broadcastChanges` sends a book or + /// page another player changed. + fn lan_lecterns_tick(&mut self, host: &mut LanHost) { + let open: Vec<(u32, i32, (i32, i32, i32))> = host + .play + .iter() + .filter_map(|(c, p)| p.lectern.as_ref().map(|l| (*c, l.window, l.key))) + .collect(); + for (conn, window, key) in open { + let Some(g) = host.hub.guests.iter().find(|g| g.conn == conn) else { + continue; + }; + if !host.hub.here(g) { + continue; + } + let has_book = matches!( + self.world.block_entities.get(&key), + Some(BlockEntity::Lectern(l)) if l.book.is_some() + ); + // Container.stillValidBlockEntity: the interaction range and its buffer. + let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]]; + let reach = if g.creative() { 5.0 } else { 4.5 } + 4.0; + let pos = [key.0, key.1, key.2]; + let near = (0..3) + .map(|k| { + let lo = f64::from(pos[k]); + (lo - eye[k]).max(eye[k] - lo - 1.0).max(0.0).powi(2) + }) + .sum::() + < reach * reach; + if has_book && near { + self.lan_send_lectern(host, conn, false); + } else { + self.lan_station_closed(host, conn, Some(window)); + host.hub.send_to( + conn, + &C::ContainerClose(play::ContainerClose { container: window }), + ); + } + } + } +} + +/// What `clearContainer` gives back from a station's menu. +pub(super) fn station_inputs(gs: &GuestStation) -> Vec { + menu_of(gs.kind) + .map(|(_, _, inputs)| inputs.filter_map(|s| gs.menu.slot(s).cloned()).collect()) + .unwrap_or_default() +} diff --git a/crates/horizon-client/src/game/lan_trading.rs b/crates/horizon-client/src/game/lan_trading.rs index c7f8a94a6..786399dac 100644 --- a/crates/horizon-client/src/game/lan_trading.rs +++ b/crates/horizon-client/src/game/lan_trading.rs @@ -55,8 +55,9 @@ impl Game<'_> { state.session.update_special_prices(); } let title = self.merchant_display_name(&state); - // The container the trading screen replaces loses its opener. + // The container or workstation the trading screen replaces is closed. self.guest_container_closed(host, conn); + self.lan_station_closed(host, conn, None); let Some(window) = host.hub.open_merchant_window(conn, title) else { self.merchant_closed(&mut state); return; @@ -254,7 +255,11 @@ impl Game<'_> { recipes: self.res.recipes(), brewing: &self.res.stations().brewing, banners: &self.res.stations().banners, + station_recipes: &self.res.stations().recipes, + enchantments: &self.res.stations().enchantments, + names: &self.pack.names, trade: Some(&trade_env), + maps: None, }; let mut menu = Menu::new(Kind::Merchant); { @@ -393,8 +398,8 @@ impl Game<'_> { }); } } - /// Takes a station a guest's action opened: a trading screen goes to the - /// guest; other stations are not shown to guests yet. + /// Takes a station a guest's action opened: a trading screen or a + /// workstation menu goes to the guest (game/lan_stations.rs). pub(super) fn lan_station_opened( &mut self, host: &mut LanHost, @@ -406,6 +411,8 @@ impl Game<'_> { && let Some(m) = station.merchant.take() { self.lan_open_merchant(host, conn, *m); + return; } + self.lan_open_station(host, conn, &station); } } diff --git a/crates/horizon-client/src/game/lan_waypoints.rs b/crates/horizon-client/src/game/lan_waypoints.rs index 0d0ab69e4..ba1512a00 100644 --- a/crates/horizon-client/src/game/lan_waypoints.rs +++ b/crates/horizon-client/src/game/lan_waypoints.rs @@ -1,5 +1,5 @@ //! The locator bar of the players on a served world (lan/waypoints.rs): what -//! each player looks like to the waypoint manager this tick. +//! each player looks like to their level's waypoint manager this tick. use super::{Game, lan::LanHost}; use horizon_client::{ items::ItemStack, @@ -27,8 +27,12 @@ impl Game<'_> { Some((team.name.clone(), color)) } + /// Each level's `ServerWaypointManager` ticked with the players in that + /// level: a player who changes level leaves the old one's manager + /// (`ServerLevel.removePlayerImmediately`: untracked for everyone there) + /// and joins the new one's (`addDuringTeleport`). pub(super) fn lan_update_waypoints(&mut self, host: &mut LanHost, state: Option<&HostState>) { - let mut players = Vec::new(); + let mut players: Vec<(&str, waypoints::Player)> = Vec::new(); if let Some(h) = state { let icon = self .cmds @@ -39,22 +43,25 @@ impl Game<'_> { color: i.color, }) .unwrap_or_default(); - players.push(waypoints::Player { - uuid: h.uuid, - conn: None, - position: h.position, - spectator: self.spectator(), - transmit_range: transmit_range( - h.sneaking, - self.potions.effects.get("invisibility").is_some(), - h.equipment[5].as_ref(), - ), - receive_range: PLAYER_RANGE, - first_tick: false, - view_distance: host.hub.config.view_distance, - team: self.waypoint_team(&h.name), - icon, - }); + players.push(( + self.dim.id(), + waypoints::Player { + uuid: h.uuid, + conn: None, + position: h.position, + spectator: self.spectator(), + transmit_range: transmit_range( + h.sneaking, + self.potions.effects.get("invisibility").is_some(), + h.equipment[5].as_ref(), + ), + receive_range: PLAYER_RANGE, + first_tick: false, + view_distance: host.hub.config.view_distance, + team: self.waypoint_team(&h.name), + icon, + }, + )); } let mut respawned = Vec::new(); for g in host.hub.guests.iter().filter(|g| g.placed) { @@ -66,27 +73,56 @@ impl Game<'_> { } // Player.updatePlayerPose: the shift key crouches unless flying. let crouching = g.sneaking && !g.flying && !g.fall_flying && !g.sleeping; - players.push(waypoints::Player { - uuid: g.uuid, - conn: Some(g.conn), - position: g.position, - spectator: g.spectator(), - transmit_range: transmit_range( - crouching, - g.effects.get("invisibility").is_some(), - g.armor[0].as_ref(), - ), - receive_range: PLAYER_RANGE, - first_tick: g.ticks == 0, - view_distance: g.view_distance, - team: self.waypoint_team(&g.name), - icon: Icon::default(), - }); + players.push(( + &g.dimension, + waypoints::Player { + uuid: g.uuid, + conn: Some(g.conn), + position: g.position, + spectator: g.spectator(), + transmit_range: transmit_range( + crouching, + g.effects.get("invisibility").is_some(), + g.armor[0].as_ref(), + ), + receive_range: PLAYER_RANGE, + first_tick: g.ticks == 0, + view_distance: g.view_distance, + team: self.waypoint_team(&g.name), + icon: Icon::default(), + }, + )); } host.waypoint_dead - .retain(|uuid| players.iter().any(|p| p.uuid == *uuid)); + .retain(|uuid| players.iter().any(|(_, p)| p.uuid == *uuid)); let locator_bar = self.ui.rules.bool("locator_bar"); - for (conn, packet) in host.waypoints.tick(&players, &respawned, locator_bar) { + let mut levels: Vec = host.waypoints.keys().cloned().collect(); + for (level, _) in &players { + if !levels.iter().any(|l| l == level) { + levels.push((*level).to_owned()); + } + } + levels.sort(); + let mut out = Vec::new(); + for level in levels { + let here: Vec = players + .iter() + .filter(|(l, _)| *l == level) + .map(|(_, p)| p.clone()) + .collect(); + let away: Vec<(u128, u32)> = players + .iter() + .filter(|(l, _)| *l != level) + .filter_map(|(_, p)| Some((p.uuid, p.conn?))) + .collect(); + let manager = host.waypoints.entry(level.clone()).or_default(); + out.extend(manager.tick_level(&here, &away, &respawned, locator_bar)); + // Nobody left in the level: nothing to remember there. + if here.is_empty() { + host.waypoints.remove(&level); + } + } + for (conn, packet) in out { if let Some(g) = host.hub.guest(conn) { g.send(&packet); } diff --git a/crates/horizon-client/src/game/levels.rs b/crates/horizon-client/src/game/levels.rs index 31b34a9d0..7df5541b4 100644 --- a/crates/horizon-client/src/game/levels.rs +++ b/crates/horizon-client/src/game/levels.rs @@ -312,15 +312,10 @@ impl Game<'_> { .map_or_else(String::new, |(end, start)| { format!(", cpu {:.1} ms", (end - start).as_secs_f32() * 1000.0) }); - let list: Vec = spans - .iter() - .filter(|(_, ms)| *ms >= 0.5) - .map(|(n, ms)| format!("{n} {ms:.1}")) - .collect(); log::info!( "Horizon: slow tick {wall:.1} ms{cpu} ({} mobs): {}", self.mobs.len(), - list.join(", ") + horizon_client::spans::describe(&spans) ); } result diff --git a/crates/horizon-client/src/game/loom.rs b/crates/horizon-client/src/game/loom.rs index f1ff1a300..ef49c8cf1 100644 --- a/crates/horizon-client/src/game/loom.rs +++ b/crates/horizon-client/src/game/loom.rs @@ -68,8 +68,9 @@ impl Game<'_> { } l.last_inputs = inputs; } - /// A sound the loom menu played: the result's once per tick. - pub(super) fn loom_sound(&mut self, sound: &str) { + /// A sound the loom or stonecutter menu played: the result's once per + /// tick (`lastSoundTime`). + pub(super) fn station_sound(&mut self, sound: &str) { let ticks = self.ticks; let Some(s) = self.station.as_mut() else { return; @@ -98,6 +99,7 @@ impl Game<'_> { if taken { self.audio .play("minecraft:ui.loom.select_pattern", None, 1.0, 1.0); + self.remote_station_button(index as i32); } taken } diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index c05c7295f..8ce1940c9 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -327,6 +327,46 @@ impl Containers<'_> { } } +/// The block columns any item entity's box reaches, so that a hopper with +/// no item over it skips the scan of every item. Kept for one block-entity +/// pass, in which items do not move: removing one leaves a superset, still +/// right, and adding one (always pushed at the end, under a new id) or +/// removing the last rebuilds the columns. +#[derive(Default)] +pub(super) struct ItemColumns { + /// The item count and last item id when last asked, if built. + seen: Option<(usize, Option)>, + cells: horizon_client::fast_hash::FxHashSet<(i32, i32)>, +} +impl ItemColumns { + /// Whether an item's box may reach into column (x, z). + fn may_reach( + &mut self, + items: &[horizon_client::entities::ItemEntity], + x: i32, + z: i32, + ) -> bool { + let (len, last) = (items.len(), items.last().map(|i| i.id)); + let stale = self + .seen + .is_none_or(|(seen_len, seen_last)| len > seen_len || last != seen_last); + self.seen = Some((len, last)); + if stale { + self.cells.clear(); + for item in items { + let b = item.bounds(); + let (lo, hi) = (b.min_position(), b.max_position()); + for cx in lo.x.floor() as i32..=hi.x.floor() as i32 { + for cz in lo.z.floor() as i32..=hi.z.floor() as i32 { + self.cells.insert((cx, cz)); + } + } + } + } + self.cells.contains(&(x, z)) + } +} + fn bone_meal() -> ItemStack { ItemStack { item: "minecraft:bone_meal".into(), @@ -648,6 +688,11 @@ impl Game<'_> { f64::from(pos.2) + 1.0, ], ); + if let Some(columns) = self.item_columns.as_mut() + && !columns.may_reach(&self.dropped, pos.0, pos.2) + { + return false; + } let mut i = 0; while i < self.dropped.len() { let b = self.dropped[i].bounds(); @@ -880,3 +925,122 @@ impl Game<'_> { true } } + +#[cfg(test)] +mod item_column_tests { + use super::ItemColumns; + use horizon_client::{entities::ItemEntity, items::ItemStack}; + use horizon_core::geometry::Vec3; + + fn item(id: u32, x: f64, y: f64, z: f64) -> ItemEntity { + let at = Vec3::new(x, y, z); + ItemEntity { + health: 5, + fire_ticks: 0, + id, + stack: ItemStack::new("minecraft:stone", 1), + thrower: None, + position: at, + previous: at, + velocity: Vec3::ZERO, + on_ground: true, + age: 0, + pickup_delay: 0, + bob_offset: 0.0, + ticks: 0, + } + } + /// `hopper_suck`'s test: some item box meets the hopper's SUCK_AABB. + fn scan(items: &[ItemEntity], (x, y, z): (i32, i32, i32)) -> bool { + let (min, max) = ( + Vec3::new(f64::from(x), f64::from(y) + 11.0 / 16.0, f64::from(z)), + Vec3::new(f64::from(x) + 1.0, f64::from(y) + 2.0, f64::from(z) + 1.0), + ); + items.iter().any(|i| { + let b = i.bounds(); + let (lo, hi) = (b.min_position(), b.max_position()); + lo.x < max.x + && hi.x > min.x + && lo.y < max.y + && hi.y > min.y + && lo.z < max.z + && hi.z > min.z + }) + } + + /// One tick of empty hoppers looking for items: each scans every item + /// (before) or asks the columns first (after, build included). + #[test] + #[ignore] + fn hopper_suck_cost() { + for (hoppers, count) in [(500i32, 200u32), (2000, 500), (2000, 2000)] { + let mut seed = 99u64; + let mut next = |range: f64| { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1); + (seed >> 11) as f64 / (1u64 << 53) as f64 * range + }; + let items: Vec = (0..count) + .map(|id| item(id, next(160.0), 64.0, next(160.0))) + .collect(); + let at: Vec<(i32, i32, i32)> = (0..hoppers) + .map(|_| (next(160.0) as i32, 63, next(160.0) as i32)) + .collect(); + let t = std::time::Instant::now(); + let a: Vec = at.iter().map(|&h| scan(&items, h)).collect(); + let before = t.elapsed().as_secs_f64() * 1e3; + let t = std::time::Instant::now(); + let mut columns = ItemColumns::default(); + let b: Vec = at + .iter() + .map(|&h| columns.may_reach(&items, h.0, h.2) && scan(&items, h)) + .collect(); + let after = t.elapsed().as_secs_f64() * 1e3; + assert_eq!(a, b); + println!("{hoppers} hoppers, {count} items: {before:.3} ms -> {after:.3} ms"); + } + } + + #[test] + fn no_hopper_with_an_item_over_it_is_skipped() { + let mut seed = 0x1234_5678_9abc_def1u64; + let mut next = |range: f64| { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1); + (seed >> 11) as f64 / (1u64 << 53) as f64 * range + }; + let mut items: Vec = Vec::new(); + let mut columns = ItemColumns::default(); + let mut next_id = 0; + let mut skipped = 0; + for round in 0..3000 { + // Items come and go as hoppers take them and crafters drop them. + match round % 5 { + 0 | 1 => { + next_id += 1; + // On edges too: a quarter of them sit on a block line. + let snap = |v: f64, edge: bool| if edge { v.floor() + 0.125 } else { v }; + let edge = round % 4 == 0; + items.push(item( + next_id, + snap(next(24.0) - 12.0, edge), + 64.0, + snap(next(24.0) - 12.0, edge), + )); + } + 2 if !items.is_empty() => { + let i = next(items.len() as f64) as usize; + items.remove(i); + } + _ => {} + } + let hopper = (next(26.0) as i32 - 13, 63, next(26.0) as i32 - 13); + let reach = columns.may_reach(&items, hopper.0, hopper.2); + let found = scan(&items, hopper); + assert!( + reach || !found, + "round {round}: skipped a hopper with an item over it" + ); + skipped += usize::from(!reach); + } + assert!(skipped > 1000, "skipped only {skipped}"); + } +} diff --git a/crates/horizon-client/src/game/machines/crafter.rs b/crates/horizon-client/src/game/machines/crafter.rs index d87646fe0..0fe66f7c8 100644 --- a/crates/horizon-client/src/game/machines/crafter.rs +++ b/crates/horizon-client/src/game/machines/crafter.rs @@ -8,6 +8,7 @@ use horizon_client::{ containers::Crafter, hud::{HudBatch, rgba}, }; +use horizon_protocol::packets::play::{self, Serverbound as S}; use serde_json::Value; /// `CrafterBlock`'s crafting animation length. @@ -323,6 +324,15 @@ impl Game<'_> { menu.set_slot_state(i, enabled); Some(true) }); + if let Some((container, _)) = self.remote.as_ref().and_then(|r| r.menu.clone()) { + self.send(S::ContainerSlotStateChanged( + play::ContainerSlotStateChanged { + slot: i as i32, + container, + enabled, + }, + )); + } let pitch = if enabled { 1.0 } else { 0.75 }; self.audio .play("minecraft:ui.button.click", None, 0.4, pitch); diff --git a/crates/horizon-client/src/game/moving_pistons.rs b/crates/horizon-client/src/game/moving_pistons.rs new file mode 100644 index 000000000..17247850e --- /dev/null +++ b/crates/horizon-client/src/game/moving_pistons.rs @@ -0,0 +1,110 @@ +//! `PistonHeadRenderer`: while a piston moves them, blocks are +//! `minecraft:moving_piston` block entities (drawn as nothing by the chunk +//! mesher); this draws each moved block at its interpolated offset. +use super::Game; +use horizon_client::mesher::Vertex; +use horizon_world::{piston_shape::MovingPistonState, registry::BlockStateId}; + +impl Game<'_> { + /// `PistonHeadRenderer.extractRenderState` and `submit`. + pub(super) fn moving_piston_geometry( + &self, + camera: glam::DVec3, + alpha: f64, + out: &mut Vec, + ) { + let partial = alpha as f32; + for &(p, piston) in &self.world.moving_pistons { + let Some((block, base)) = self.moving_piston_blocks(piston, partial) else { + continue; + }; + let step = piston.movement_direction().normal(); + let from = horizon_core::position::BlockPos::new( + p[0] - step[0], + p[1] - step[1], + p[2] - step[2], + ); + let offset = piston.interpolated_offset(partial); + let light = self.world.light(p[0], p[1], p[2]); + let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8); + let corner = glam::DVec3::new(f64::from(p[0]), f64::from(p[1]), f64::from(p[2])); + let moved = corner + glam::Vec3::from_array(offset).as_dvec3(); + self.moving_block_vertices(block, from, moved - camera, packed, out); + if let Some(base) = base { + let at = horizon_core::position::BlockPos::new(p[0], p[1], p[2]); + self.moving_block_vertices(base, at, corner - camera, packed, out); + } + } + } + /// The moved block and, for a retracting piston, its extended base. + fn moving_piston_blocks( + &self, + piston: MovingPistonState, + partial: f32, + ) -> Option<(BlockStateId, Option)> { + let facts = self.res.facts(); + if facts.is_air(piston.moved_state) { + return None; + } + let progress = piston.interpolated_progress(partial); + let name = &*facts.get(piston.moved_state).name; + // Vanilla tests `progress <= 4.0`: a moving head is always drawn so. + if name == "minecraft:piston_head" { + let short = if progress <= 0.5 { "true" } else { "false" }; + return Some(( + self.with_props(piston.moved_state, &[("short", short)])?, + None, + )); + } + if piston.source && !piston.extending { + let registry = &self.pack.assets.registry; + let facing = registry + .state(piston.moved_state)? + .properties + .get("facing")? + .clone(); + let kind = if name == "minecraft:sticky_piston" { + "sticky" + } else { + "normal" + }; + let short = if progress >= 0.5 { "true" } else { "false" }; + let head = self.with_props( + registry.default_state("minecraft:piston_head")?, + &[("type", kind), ("facing", &facing), ("short", short)], + )?; + let base = self.with_props(piston.moved_state, &[("extended", "true")])?; + return Some((head, Some(base))); + } + Some((piston.moved_state, None)) + } + /// One `MovingBlockRenderState`: the baked model at `at` (camera-relative), + /// seeded by its block position and tinted like a falling block. + fn moving_block_vertices( + &self, + state: BlockStateId, + seed: horizon_core::position::BlockPos, + at: glam::DVec3, + light: u32, + out: &mut Vec, + ) { + let tint = self + .particle_sprite(state, [seed.x, seed.y, seed.z]) + .map(|(_, tint)| tint); + let start = out.len(); + self.block_model_vertices( + state, + horizon_core::random::position_seed(seed), + glam::Mat4::from_translation(at.as_vec3()), + light, + false, + out, + ); + if let Some(tint) = tint { + let tint = horizon_client::mobs::render::abgr(tint); + for vertex in &mut out[start..] { + vertex.color = horizon_client::hud_layout::multiply(vertex.color, tint); + } + } + } +} diff --git a/crates/horizon-client/src/game/natural_spawning.rs b/crates/horizon-client/src/game/natural_spawning.rs index 0fab09bde..6dda8e0ac 100644 --- a/crates/horizon-client/src/game/natural_spawning.rs +++ b/crates/horizon-client/src/game/natural_spawning.rs @@ -9,6 +9,7 @@ use horizon_client::{ mobs::{ Mob, MobWorld, Species, data::{self, MobData}, + seen_grid::SeenGrid, spawn_rules::{Dimension, SpawnLevel}, spawn_selection::{ self, Category, Counted, Heightmap, NaturalLevel, SpawnCost, SpawnPlayer, SpawnRequest, @@ -75,8 +76,72 @@ pub(super) struct GameLevel<'g, 'a> { pub(super) pending: std::cell::RefCell>, /// The types and boxes of what a spawner created this tick. pub(super) pending_ids: std::cell::RefCell>, + /// The game's mobs by box, built once a pass has asked more than + /// [`SCANNED_QUERIES`] box queries (the mobs do not change while it + /// holds the game); the first ones scan, as the build costs a few scans. + pub(super) boxes: std::cell::OnceCell, + pub(super) box_queries: std::cell::Cell, +} +const SCANNED_QUERIES: u32 = 8; +/// A mob not removed: its index in `Game::mobs`, box, alive, and whether +/// it is a living shulker. +type MobBox = (usize, Aabb, bool, bool); +fn mob_box(i: usize, m: &Mob) -> MobBox { + let alive = m.alive(); + ( + i, + m.bounds(), + alive, + alive && m.species() == Species::Shulker, + ) +} +/// The boxes of the game's mobs not removed, and a grid over them. +pub(super) struct MobBoxes { + entries: Vec, + grid: SeenGrid, +} +impl MobBoxes { + fn new(mobs: &[Mob]) -> Self { + let entries: Vec<_> = mobs + .iter() + .enumerate() + .filter(|(_, m)| !m.removed) + .map(|(i, m)| mob_box(i, m)) + .collect(); + let grid = SeenGrid::new(entries.iter().map(|e| e.1)); + Self { entries, grid } + } + /// The entries whose boxes meet `area` (and possibly a few more). + fn near(&self, area: Aabb) -> impl Iterator + '_ { + let mut near = Vec::new(); + let indexed = self.grid.candidates(area, &mut near); + let all = (!indexed).then(|| self.entries.iter()); + near.into_iter() + .map(|i| self.entries[i as usize]) + .chain(all.into_iter().flatten().copied()) + } } impl GameLevel<'_, '_> { + /// The mobs not removed whose boxes may meet `area` (callers test them). + fn mobs_near(&self, area: Aabb) -> Box + '_> { + let asked = self.box_queries.get() + 1; + self.box_queries.set(asked); + if asked <= SCANNED_QUERIES && self.boxes.get().is_none() { + return Box::new( + self.game + .mobs + .iter() + .enumerate() + .filter(|(_, m)| !m.removed) + .map(|(i, m)| mob_box(i, m)), + ); + } + Box::new( + self.boxes + .get_or_init(|| MobBoxes::new(&self.game.mobs)) + .near(area), + ) + } fn biome(&self, x: i32, y: i32, z: i32) -> Option<&BiomeInfo> { let chunk = self.game.world.chunks.get(&(x >> 4, z >> 4))?; Some(self.game.res.biomes().get(chunk.biome(x, y, z))) @@ -191,7 +256,13 @@ impl NaturalLevel for GameLevel<'_, '_> { StructureSpawns::shared(&self.game.options.resources) } fn nearest_player_distance_sqr(&self, x: f64, y: f64, z: f64) -> Option { - nearest_player(&self.players, x, y, z).map(|p| p.distance_sqr(x, y, z)) + // The nearest player's distance (`nearest_player`), without finding + // which player it is: every spawn attempt asks. + self.players + .iter() + .filter(|p| !p.spectator) + .map(|p| p.distance_sqr(x, y, z)) + .reduce(f64::min) } fn respawn(&self) -> Option<[i32; 3]> { // The world spawn point lives in the overworld. @@ -218,12 +289,9 @@ impl NaturalLevel for GameLevel<'_, '_> { // getEntityCollisions(null, box): living shulkers are solid. let grown = bounds.inflate(Vec3::new(1e-7, 1e-7, 1e-7)); no_collision_empty(&mut scene, bounds) - && !self.game.mobs.iter().any(|m| { - m.species() == Species::Shulker - && m.alive() - && !m.removed - && m.bounds().intersects(grown) - }) + && !self + .mobs_near(grown) + .any(|(_, b, _, shulker)| shulker && b.intersects(grown)) && !self .pending_ids .borrow() @@ -238,10 +306,8 @@ impl NaturalLevel for GameLevel<'_, '_> { !player && !self.pending.borrow().iter().any(|b| b.intersects(bounds)) && !self - .game - .mobs - .iter() - .any(|m| m.alive() && !m.removed && m.bounds().intersects(bounds)) + .mobs_near(bounds) + .any(|(_, b, alive, _)| alive && b.intersects(bounds)) } fn spawn_mobs(&self) -> bool { self.game.ui.rules.bool("spawn_mobs") @@ -283,10 +349,8 @@ impl horizon_client::mobs::spawner::SpawnerLevel for GameLevel<'_, '_> { } fn count_entities(&self, id: &str, bounds: Aabb) -> usize { let mobs = self - .game - .mobs - .iter() - .filter(|m| !m.removed && m.kind.id == id && m.bounds().intersects(bounds)) + .mobs_near(bounds) + .filter(|&(i, b, ..)| self.game.mobs[i].kind.id == id && b.intersects(bounds)) .count(); let pending = self .pending_ids @@ -305,6 +369,8 @@ impl<'a> Game<'a> { players: self.level_players(), pending: Default::default(), pending_ids: Default::default(), + boxes: Default::default(), + box_queries: Default::default(), } } /// Creates a mob the spawner accepted, finalized the game's way; the diff --git a/crates/horizon-client/src/game/ominous_item_spawner.rs b/crates/horizon-client/src/game/ominous_item_spawner.rs index 1470a3124..8084faf9e 100644 --- a/crates/horizon-client/src/game/ominous_item_spawner.rs +++ b/crates/horizon-client/src/game/ominous_item_spawner.rs @@ -1,8 +1,7 @@ //! `OminousItemSpawner`: the item an ominous trial spawner drops on its //! fight. It floats, growing and turning (`OminousItemSpawnerRenderer`), for //! 60 to 120 ticks, then falls as an item or is fired straight down as a -//! projectile (`spawnItem`). Not saved: a spawner left in an unloaded chunk -//! is lost. +//! projectile (`spawnItem`). Saved with its chunk's entities (persist.rs). use super::Game; use horizon_assets::item_model::DisplayContext; use horizon_client::{ @@ -22,10 +21,14 @@ const TICKS_SCALING: f32 = 50.0; const ROTATION_SPEED: f32 = 40.0; pub(super) struct OminousItemSpawner { - item: ItemStack, - position: [f64; 3], - spawn_item_after: i64, + pub(super) item: ItemStack, + pub(super) position: [f64; 3], + pub(super) spawn_item_after: i64, tick_count: i64, + /// Its UUID, and the compound it was loaded from (fields Horizon doesn't + /// model survive a save). + pub(super) uuid: [i32; 4], + pub(super) raw: Option>, } /// `ProjectileItem.DispenseConfig` of the items fired down: power, @@ -66,6 +69,26 @@ impl Game<'_> { position, spawn_item_after: i64::from(delay), tick_count: 0, + uuid: horizon_client::save::random_uuid(), + raw: None, + }); + } + /// A saved spawner, as `readAdditionalSaveData` leaves it: its tick + /// count starts again from 0. + pub(super) fn load_ominous_item_spawner(&mut self, tag: horizon_world::nbt::Tag) { + let Some((item, at, spawn_item_after)) = + horizon_client::entity_nbt::ominous_item_spawner_from_nbt(&tag) + else { + return; + }; + self.ominous_spawners.push(OminousItemSpawner { + item, + position: [at.x, at.y, at.z], + spawn_item_after, + tick_count: 0, + uuid: horizon_client::entity_nbt::uuid(&tag) + .unwrap_or_else(horizon_client::save::random_uuid), + raw: Some(Box::new(tag)), }); } /// Every item spawner's tick: `commonTick`'s count, `tickServer` (the diff --git a/crates/horizon-client/src/game/options.rs b/crates/horizon-client/src/game/options.rs index 12efde5be..61036d18c 100644 --- a/crates/horizon-client/src/game/options.rs +++ b/crates/horizon-client/src/game/options.rs @@ -230,6 +230,11 @@ impl Game<'_> { let _ = std::fs::create_dir_all(&dir); super::packs::open_folder(&dir); } + Event::OpenShaderPackFolder => { + let dir = horizon_client::shader_pack::folder(); + let _ = std::fs::create_dir_all(&dir); + super::packs::open_folder(&dir); + } } } Ok(()) diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 3e824e72e..eb30ab5ed 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -274,6 +274,7 @@ impl Game<'_> { self.carts.push(c); } } + "minecraft:ominous_item_spawner" => self.load_ominous_item_spawner(tag), "minecraft:ender_dragon" => { let seed = self.world.random.next_long(); if self.dragon.is_none() @@ -685,6 +686,19 @@ impl Game<'_> { .push(c.to_nbt(uuid, raw.as_ref())); } } + for s in &self.ominous_spawners { + let at = Vec3::new(s.position[0], s.position[1], s.position[2]); + if keys.contains(&chunk_of(at)) { + let tag = entity_nbt::ominous_item_spawner_to_nbt( + &s.item, + at, + s.spawn_item_after, + s.uuid, + s.raw.as_deref(), + ); + out.entry(chunk_of(at)).or_default().push(tag); + } + } for c in &self.carts { if keys.contains(&chunk_of(c.position)) { let uuid = self @@ -774,6 +788,8 @@ impl Game<'_> { keep }); self.crystals.retain(|c| !gone(c.position)); + self.ominous_spawners + .retain(|s| !gone(Vec3::new(s.position[0], s.position[1], s.position[2]))); if self.dragon.as_ref().is_some_and(|d| gone(d.position)) { self.dragon = None; } diff --git a/crates/horizon-client/src/game/perspective.rs b/crates/horizon-client/src/game/perspective.rs index cdc7fa2d8..bd2721648 100644 --- a/crates/horizon-client/src/game/perspective.rs +++ b/crates/horizon-client/src/game/perspective.rs @@ -223,6 +223,14 @@ impl Game<'_> { .riding .and_then(|id| self.mobs.iter().find(|m| m.id == id)) .map(|_| (1.0, 4.0)); + // AbstractBoat.positionRider turns a passenger by the boat's + // deltaRotation after its yRotO was saved, and LocalPlayer.getViewYRot + // interpolates a passenger's yaw: the boat's turn is spread over the + // frames of a tick. + let ride_turn = self + .riding + .and_then(|id| self.boats.iter().find(|b| b.id == id)) + .map_or(0.0, |b| b.delta_rotation); let entity = CameraEntity { position: [p.position.x, p.position.y, p.position.z], previous: [ @@ -235,7 +243,7 @@ impl Game<'_> { x_rot: self.pitch, y_rot: self.yaw, x_rot_o: self.pitch, - y_rot_o: self.yaw, + y_rot_o: self.yaw - ride_turn, eye_height: p.dimensions.eye_height, living: Some(LivingCamera { scale, @@ -304,6 +312,7 @@ impl Game<'_> { let crouching = p.pose == Pose::Crouching; let (position, flying) = (p.position, p.flying || p.fall_flying); let (fall_flying, fly_ticks, velocity) = (p.fall_flying, p.fall_fly_ticks, p.velocity); + let spinning = p.auto_spin_attack_ticks > 0; let using = self.using.map(|(_, ticks)| ticks as i32 + 1).unwrap_or(0); let using_off_hand = self .using @@ -389,6 +398,7 @@ impl Game<'_> { m.velocity = velocity; m.extra.fall_flying = fall_flying; m.extra.fall_fly_ticks = fly_ticks; + m.extra.auto_spin_attack = spinning; m.extra.main_hand_left = self.settings.main_hand_left; m.extra.using_item = using; m.extra.using_off_hand = using_off_hand; @@ -443,6 +453,7 @@ impl Game<'_> { out, ); self.player_elytra_geometry(m, camera, alpha as f32, packed, out); + self.spin_attack_geometry(m, camera, alpha as f32, packed, out); self.held_item_geometry(m, camera, alpha, packed, true, out); } /// `extractEntityInInventoryFollowsMouse`: the player in the box @@ -584,6 +595,47 @@ impl Game<'_> { out, ); } + /// `SpinAttackEffectLayer`: Riptide's two boxes turning around a spinning + /// player (`SpinAttackEffectModel.setupAnim`). + fn spin_attack_geometry( + &self, + m: &Mob, + camera: glam::DVec3, + partial: f32, + light: u32, + out: &mut Vec, + ) { + if !m.extra.auto_spin_attack { + return; + } + let (Some(model), Some(rect)) = ( + self.res.spin_attack().as_ref(), + self.gui.atlas.sprites.get("entity/trident/trident_riptide"), + ) else { + return; + }; + let age = m.age as f32 + partial; + horizon_client::mobs::render_model( + model, + horizon_client::mobs::render::base_transform(m, partial, camera), + &|part| { + let mut p = part.pose; + if let Some(i) = part + .name + .strip_prefix("box") + .and_then(|i| i.parse::().ok()) + { + let angle = age * -(45.0 + f32::from(i + 1) * 5.0); + p[4] = wrap(angle).to_radians(); + } + p + }, + [rect.u0, rect.v0, rect.u1, rect.v1], + light, + 0, + out, + ); + } } fn player_preview_quads( diff --git a/crates/horizon-client/src/game/piglins.rs b/crates/horizon-client/src/game/piglins.rs index 9df5311aa..bcf9e6ab5 100644 --- a/crates/horizon-client/src/game/piglins.rs +++ b/crates/horizon-client/src/game/piglins.rs @@ -6,7 +6,7 @@ use horizon_client::{ items::ItemStack, mobs::{Species, Who, piglin::ADMIRE}, }; -use horizon_core::random::RandomSource; +use horizon_core::{geometry::Vec3, random::RandomSource}; impl Game<'_> { fn piglin_loved(&self, item: &str) -> bool { @@ -34,6 +34,9 @@ impl Game<'_> { if !self.ui.rules.bool("mob_griefing") { return; } + // Whether each item is piglin-loved, kept until an item is added or + // removed (added ones are pushed at the end under a new id). + let mut loved: (Option<(usize, Option)>, Vec) = (None, Vec::new()); for i in 0..self.mobs.len() { let m = &self.mobs[i]; if m.species() != Species::Piglin @@ -46,11 +49,20 @@ impl Game<'_> { continue; } let pos = m.position; + let key = (self.dropped.len(), self.dropped.last().map(|e| e.id)); + if loved.0 != Some(key) { + loved.0 = Some(key); + loved.1 = self + .dropped + .iter() + .map(|e| self.piglin_loved(&e.stack.item)) + .collect(); + } let best = self .dropped .iter() .enumerate() - .filter(|(_, e)| self.piglin_loved(&e.stack.item)) + .filter(|&(j, _)| loved.1[j]) .map(|(j, e)| (j, e.position.distance_squared(pos))) .filter(|(_, d)| *d <= 81.0) .min_by(|a, b| a.1.total_cmp(&b.1)); @@ -132,12 +144,29 @@ impl Game<'_> { } else { vec![ItemStack::new(&item, 1)] }; - // BehaviorUtils.throwItem toward the nearest visible player, else nearby. - let target = self + // BehaviorUtils.throwItem toward the nearest visible player + // (NEAREST_VISIBLE_PLAYER: within 16, alive, no spectators; the + // guests count as much as the host), else nearby. + let at = m.position; + let host = self .player .as_ref() - .filter(|p| p.position.distance_squared(m.position) < 256.0) - .map(|p| [p.position.x, p.position.y + 1.0, p.position.z]); + .filter(|p| !p.health.dead_or_dying() && !self.spectator()) + .map(|p| [p.position.x, p.position.y, p.position.z]); + let guests = self.lan.iter().flat_map(|h| { + h.hub + .guests + .iter() + .filter(|g| h.hub.here(g) && g.loaded && !g.dead && !g.spectator()) + .map(|g| g.position) + }); + let d = |p: &[f64; 3]| at.distance_squared(Vec3::new(p[0], p[1], p[2])); + let target = host + .into_iter() + .chain(guests) + .filter(|p| d(p) < 256.0) + .min_by(|a, b| d(a).total_cmp(&d(b))) + .map(|p| [p[0], p[1] + 1.0, p[2]]); for stack in items { let to = target.unwrap_or_else(|| { let r = &mut self.world.random; diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index 52ab5060a..72c8fe885 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -2,13 +2,16 @@ //! `Consumable`), throwing splash/lingering potions (`ThrownSplashPotion`), //! filling glass bottles (`BottleItem`), the per-tick effect application, //! effect attribute modifiers and the HUD effect icons (`Hud.extractEffects`). -use super::{Game, Screen}; +use super::{Game, Screen, item_draw::owner_at}; +use horizon_assets::item_model::DisplayContext; use horizon_client::{ + block_entity_render::vertex_light, brewing, effects::{EffectAction, EffectInstance, PlayerEffects}, hud::HudBatch, hud_layout, hud_overlays, inventory_effects, items::ItemStack, + mesher::Vertex, }; use horizon_core::{geometry::Vec3, random::RandomSource}; @@ -16,6 +19,8 @@ use horizon_core::{geometry::Vec3, random::RandomSource}; #[derive(Clone, Debug)] pub(super) struct ThrownPotion { stack: ItemStack, + /// The position before the last tick, for drawing between ticks. + previous: Vec3, position: Vec3, velocity: Vec3, age: u32, @@ -43,6 +48,7 @@ impl Game<'_> { pub(super) fn launch_thrown(&mut self, stack: ItemStack, position: Vec3, velocity: Vec3) { self.potions.thrown.push(ThrownPotion { stack, + previous: position, position, velocity, age: 0, @@ -411,6 +417,7 @@ impl Game<'_> { let mut landed = Vec::new(); thrown.retain_mut(|t| { t.age += 1; + t.previous = t.position; let next = Vec3::new( t.position.x + t.velocity.x, t.position.y + t.velocity.y, @@ -461,33 +468,56 @@ impl Game<'_> { ); t.age < 1200 && t.position.y > -128.0 }); - // ThrownItemRenderer stand-in: a short-lived sprite of the potion at its position. - for t in &thrown { - let sprite = match &*t.stack.item { - "minecraft:lingering_potion" => "item/lingering_potion", - "minecraft:experience_bottle" => "item/experience_bottle", - _ => "item/splash_potion", - }; - let mut fixed = horizon_core::random::LegacyRandom::new(0); - let mut p = horizon_client::particles::Particle::terrain( - &mut fixed, - [t.position.x, t.position.y, t.position.z], - [0.0; 3], - sprite.into(), - 0xFFFFFF, - ); - p.velocity = [0.0; 3]; - p.gravity = 0.0; - p.lifetime = 2; - p.size = 0.25; - p.uv = [0.0, 0.0, 1.0, 1.0]; - self.particles.push(p); - } self.potions.thrown = thrown; for (stack, at) in landed { self.splash(&stack, at); } } + /// `ThrownItemRenderer` for thrown splash and lingering potions and + /// experience bottles: the item (GROUND) facing the camera at scale 1, + /// lit at the light probe (the eye, 0.85 of the 0.25 height). + pub(super) fn thrown_potion_geometry( + &self, + camera: glam::DVec3, + alpha: f64, + out: &mut Vec, + ) { + let orientation = glam::Mat4::from_quat(self.camera_orientation()); + for t in &self.potions.thrown { + let previous = glam::DVec3::new(t.previous.x, t.previous.y, t.previous.z); + let position = glam::DVec3::new(t.position.x, t.position.y, t.position.z); + // ThrowableProjectile.shouldRenderAtSqrDistance: hidden for its + // first two ticks within 3.5 blocks (not in the thrower's face). + if t.age < 2 && position.distance_squared(camera) < 12.25 { + continue; + } + if !self.standing_entity_in_view( + camera, + super::entity_culling::at(t.previous), + super::entity_culling::at(t.position), + alpha, + 0.25, + 0.25, + 64.0, + 0.0, + ) { + continue; + } + let p = previous.lerp(position, alpha); + let owner = owner_at(p.to_array(), 0.0, &t.stack.item); + let state = self.resolve_item(&t.stack, DisplayContext::Ground, Some(&owner), 0); + if state.is_empty() { + continue; + } + let pose = glam::Mat4::from_translation((p - camera).as_vec3()) * orientation; + let light = self.world.light( + p.x.floor() as i32, + (p.y + 0.2125).floor() as i32, + p.z.floor() as i32, + ); + self.submit_item_world(&state, pose, vertex_light(light), out); + } + } /// A splash potion's effects on the player in place, by their distance. fn splash_on_player( &mut self, diff --git a/crates/horizon-client/src/game/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs index 843c01476..d3c14ffc7 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -279,7 +279,11 @@ impl Game<'_> { recipes: self.res.recipes(), brewing: &self.res.stations().brewing, banners: &self.res.stations().banners, + station_recipes: &self.res.stations().recipes, + enchantments: &self.res.stations().enchantments, + names: &self.pack.names, trade: None, + maps: None, }; for i in 0..36 { menu.set_player_item(i, self.inventory[i].clone()); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 5bb3e172c..7c96e7bad 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -41,7 +41,11 @@ use horizon_protocol::{ text::{Language, format_java, plain}, }; use horizon_world::{nbt::Tag, registry::BlockStateId}; -use std::{collections::HashMap, sync::Arc, time::Instant}; +use std::{ + collections::{HashMap, VecDeque}, + sync::Arc, + time::{Duration, Instant}, +}; use winit::{event::MouseButton, keyboard::KeyCode}; /// A text component the server sent, for the HUD. @@ -99,6 +103,10 @@ pub(super) struct Remote { last_input: u8, was_sprinting: bool, carried: Option, + /// The last ClientboundPlayerAbilitiesPacket. Vanilla's LocalPlayer + /// holds its abilities from the login on; here the player is made at + /// the first teleport, which takes them then. + abilities: Option, loaded_sent: bool, /// The view distance last sent in ClientInformation. sent_view: i8, @@ -108,9 +116,9 @@ pub(super) struct Remote { /// only replace the remembered state; then the block takes it. predictions: HashMap<[i32; 3], (i32, i32)>, /// Open container: (window id, menu name). - menu: Option<(i32, String)>, + pub(super) menu: Option<(i32, String)>, /// The open menu's title as the server named it. - menu_title: Option, + pub(super) menu_title: Option, state_id: i32, use_target: Option<[i32; 3]>, entities: HashMap, @@ -158,8 +166,22 @@ pub(super) struct Remote { clock_game_time: i64, /// `ClientChunkCache.Storage`'s view centre (ClientboundSetChunkCacheCenterPacket). chunk_center: (i32, i32), + /// Received events a frame left for the next one, in order, and when + /// the oldest of them first waited (`poll_remote`). + backlog: VecDeque, + backlog_since: Option, } +/// The time a frame spends on chunk packets before it leaves the rest of +/// the received events for the next frame. A batch of 25 to 60 columns +/// (0.1 ms each on an M4 Pro) all in one frame was a 3 to 8 ms frame every +/// time the player crossed a chunk border at 32 chunks. +const CHUNK_PACKETS_PER_FRAME: Duration = Duration::from_millis(1); +/// Events that have waited this long are all handled in the next frame, +/// whatever their cost: the packets after a slow machine's chunks never +/// wait more than a tick. +const BACKLOG_LIMIT: Duration = Duration::from_millis(50); + fn face_direction(face: [i32; 3]) -> u8 { match face { [0, -1, 0] => 0, @@ -313,6 +335,7 @@ impl Game<'_> { last_input: 0, was_sprinting: false, carried: None, + abilities: None, loaded_sent: false, sent_view: view, predictions: HashMap::new(), @@ -350,6 +373,8 @@ impl Game<'_> { clock_partial: 0.0, clock_game_time: 0, chunk_center: (0, 0), + backlog: VecDeque::new(), + backlog_since: None, }); // The level's TickRateManager follows the server's ticking packets. self.clock = horizon_client::clock::FixedStep::client(); @@ -446,8 +471,15 @@ impl Game<'_> { .unwrap_or("minecraft:air"), ) } + /// The server's network id of a mob effect (`brewing::EFFECTS` id). + pub(super) fn remote_effect_network_id(&self, effect: &str) -> Option { + let r = self.remote.as_ref()?; + r.builtin + .get("minecraft:mob_effect")? + .id(&format!("minecraft:{effect}")) + } /// A mob effect's network id as the effect (`brewing::EFFECTS` id). - fn remote_effect_id(&self, effect: i32) -> Option<&'static str> { + pub(super) fn remote_effect_id(&self, effect: i32) -> Option<&'static str> { let r = self.remote.as_ref()?; let name = r.builtin.get("minecraft:mob_effect")?.name(effect)?; horizon_client::brewing::effect(name).map(|d| d.id) @@ -493,6 +525,54 @@ impl Game<'_> { if let Some(Component::Int(id)) = s.component(component::MAP_ID) { out.data_mut().map_id = Some(*id); } + if let Some(Component::Int(cost)) = s.component(component::REPAIR_COST) { + out.data_mut().repair_cost = (*cost).max(0) as u32; + } + if let Some(Component::Int(mode)) = s.component(component::MAP_POST_PROCESSING) { + out.data_mut().map_post_processing = Some((*mode).clamp(0, 1) as u8); + } + if let Some(Component::WritableBook(pages)) = s.component(component::WRITABLE_BOOK_CONTENT) + { + out.data_mut().writable_pages = pages.clone(); + } + if let Some(Component::WrittenBook(b)) = s.component(component::WRITTEN_BOOK_CONTENT) { + let lang = self + .remote + .as_ref() + .map(|r| r.lang.clone()) + .unwrap_or_default(); + out.data_mut().written = Some(horizon_client::item_data::WrittenBook { + title: b.title.clone(), + author: b.author.clone(), + generation: b.generation.clamp(0, 3) as u8, + pages: b.pages.iter().map(|p| plain(p, &lang)).collect(), + }); + } + if let Some(Component::Text(name)) = s.component(component::CUSTOM_NAME) { + let lang = self + .remote + .as_ref() + .map(|r| r.lang.clone()) + .unwrap_or_default(); + out.data_mut().custom_name = Some(plain(name, &lang)); + } + // The enchantments by the server's registry ids. + let levels = |list: &[(i32, i32)]| -> Vec<(Arc, u32)> { + let names = self.remote.as_ref().map(|r| &r.registries); + list.iter() + .filter_map(|(id, level)| { + let name = names?.name("minecraft:enchantment", *id)?; + Some((Arc::from(name), (*level).max(0) as u32)) + }) + .collect() + }; + if let Some(Component::Enchantments(list)) = s.component(component::ENCHANTMENTS) { + out.data_mut().enchantments = levels(list); + } + if let Some(Component::Enchantments(list)) = s.component(component::STORED_ENCHANTMENTS) { + out.data_mut().stored_enchantments = levels(list); + } + out.tidy(); Some(out) } fn to_network(&self, s: &Option) -> Option { @@ -524,6 +604,28 @@ impl Game<'_> { } } + /// The minecarts the server sent, for the control socket's `status` + /// (their velocity is not tracked here). + pub(super) fn remote_carts(&self) -> Option> { + let r = self.remote.as_ref()?; + let mut carts: Vec<&Tracked> = r + .entities + .values() + .filter(|t| t.kind.ends_with("minecart")) + .collect(); + carts.sort_by(|a, b| { + a.position + .partial_cmp(&b.position) + .unwrap_or(std::cmp::Ordering::Equal) + }); + Some( + carts + .into_iter() + .map(|t| serde_json::json!({"kind": t.kind, "position": t.position, "velocity": [0.0, 0.0, 0.0]})) + .collect(), + ) + } + /// The names in the server's player list, sorted. pub(super) fn remote_online_names(&self) -> Option> { let r = self.remote.as_ref()?; @@ -544,12 +646,34 @@ impl Game<'_> { Some(r.chat.iter().rev().take(n).map(|l| l.0.clone()).collect()) } - /// Process everything the network thread received (once per frame, like - /// the client's packet processor). + /// Received events left for the next frame (`poll_remote`): until they + /// are handled, the terrain the server sent is not all there. + pub(super) fn remote_backlog(&self) -> usize { + self.remote.as_ref().map_or(0, |r| r.backlog.len()) + } + /// Process what the network thread received (once per frame, like the + /// client's packet processor), in order. Chunk packets get + /// `CHUNK_PACKETS_PER_FRAME`: once a frame has spent it, the events from + /// the next chunk packet on wait for the next frame, unless they have + /// already waited `BACKLOG_LIMIT`. pub(super) fn poll_remote(&mut self) -> Result<()> { - let Some(r) = &self.remote else { return Ok(()) }; - let events = r.session.poll(); - for event in events { + let Some(r) = self.remote.as_mut() else { + return Ok(()); + }; + let mut events = std::mem::take(&mut r.backlog); + events.extend(r.session.poll()); + let overdue = r + .backlog_since + .is_some_and(|since| since.elapsed() >= BACKLOG_LIMIT); + let mut chunks = Duration::ZERO; + while let Some(event) = events.pop_front() { + let chunk = + matches!(&event, Event::Packet(p) if matches!(**p, C::LevelChunkWithLight(_))); + if chunk && !overdue && chunks >= CHUNK_PACKETS_PER_FRAME { + events.push_front(event); + break; + } + let started = chunk.then(Instant::now); match event { Event::Status(s) => { if let Some(r) = self.remote.as_mut() { @@ -595,10 +719,19 @@ impl Game<'_> { } Event::Packet(packet) => self.handle_packet(*packet)?, } + chunks += started.map_or(Duration::ZERO, |t| t.elapsed()); if self.remote.is_none() { break; } } + if let Some(r) = self.remote.as_mut() { + r.backlog_since = if events.is_empty() { + None + } else { + Some(r.backlog_since.unwrap_or_else(Instant::now)) + }; + r.backlog = events; + } self.send_suggestion_request(); Ok(()) } @@ -1216,9 +1349,39 @@ impl Game<'_> { "minecraft:hopper" => slots(5), "minecraft:generic_3x3" => slots(9), "minecraft:brewing_stand" => slots(5), - _ => None, + // CrafterMenu: the grid, the inventory, then the result (the + // client's own). + "minecraft:crafter_3x3" => slots(9), + // A workstation: its inputs, its result, then the inventory. + m => { + let kind = Self::remote_station_kind(m)?; + let inputs = kind.inputs(); + let own = inputs + usize::from(kind.has_result()); + match s { + _ if s < inputs => Some(super::stations::INPUT + s), + _ if s < own => Some(super::stations::RESULT), + _ if s < own + 27 => Some(9 + s - own), + _ if s < own + 36 => Some(s - own - 27), + _ => None, + } + } } } + /// The workstation screen of a menu type a server opens. + pub(super) fn remote_station_kind(menu: &str) -> Option { + use super::stations::Kind; + Some(match menu { + "minecraft:loom" => Kind::Loom, + "minecraft:stonecutter" => Kind::Stonecutter, + "minecraft:grindstone" => Kind::Grindstone, + "minecraft:anvil" => Kind::Anvil, + "minecraft:smithing" => Kind::Smithing, + "minecraft:enchantment" => Kind::Enchanting, + "minecraft:beacon" => Kind::Beacon, + "minecraft:cartography_table" => Kind::Cartography, + _ => return None, + }) + } fn open_menu_name(&self, container: i32) -> String { match self.remote.as_ref().and_then(|r| r.menu.as_ref()) { Some((id, name)) if *id == container && container != 0 => name.clone(), @@ -1227,6 +1390,12 @@ impl Game<'_> { } fn set_menu_slot(&mut self, container: i32, slot: i32, item: Option) { let menu = self.open_menu_name(container); + if menu == "minecraft:lectern" { + if slot == 0 { + self.remote_lectern_book(item); + } + return; + } if container != 0 && menu == "inventory" { return; } @@ -1237,6 +1406,9 @@ impl Game<'_> { return; // the result slot is recomputed from the grid } *self.slot_mut(internal) = item; + if internal >= super::stations::INPUT && self.station.is_some() { + self.remote_station_slot_changed(internal); + } } fn handle_packet(&mut self, packet: C) -> Result<()> { @@ -1342,6 +1514,10 @@ impl Game<'_> { })); } C::BlockUpdate(p) => self.server_block(p.pos, p.state), + // ClientPacketListener.handleBlockDestruction: another player's crack. + C::BlockDestruction(p) => { + self.destroy_block_progress(p.id, p.pos, i32::from(p.progress)); + } C::SectionBlocksUpdate(p) => { let [sx, sy, sz] = p.section; for change in p.changes { @@ -1544,6 +1720,18 @@ impl Game<'_> { } } } + // LivingEntity.onSyncedDataUpdated(SLEEPING_POS_ID): another + // player lies down in their bed (drawn lying in it), or gets up. + if other { + for (index, _, value) in &p.values { + if let (14, Value::OptPos(bed)) = (index, value) { + let code = bed.map_or(0, |b| self.bed_facing(b)); + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { + m.extra.ints[1] = code; + } + } + } + } // LivingEntity.onSyncedDataUpdated(SLEEPING_POS_ID): this // player lies down in the bed, or gets up. if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) { @@ -1824,9 +2012,10 @@ impl Game<'_> { }, C::PlayerAbilities(p) => { self.creative = p.flags & 8 != 0; - if let Some(player) = &mut self.player { - player.flying_speed = p.flying_speed; + if let Some(r) = self.remote.as_mut() { + r.abilities = Some(p); } + self.apply_remote_abilities(); } C::SetHeldSlot(p) => { self.selected = p.slot.clamp(0, 8) as usize; @@ -1865,6 +2054,12 @@ impl Game<'_> { } self.remote_synced(); } + C::ContainerSetData(p) if self.open_menu_name(p.container) == "minecraft:lectern" => { + self.remote_lectern_page(i32::from(p.value)); + } + C::ContainerSetData(p) if self.remote_station_open(p.container) => { + self.remote_station_data(usize::try_from(p.id).unwrap_or(usize::MAX), p.value); + } C::ContainerSetData(p) => { let v = i32::from(p.value); match self @@ -1878,6 +2073,12 @@ impl Game<'_> { 3 => f.cooking_total = v, _ => {} }, + // CrafterBlockEntity.containerData. + Some(BlockEntity::Crafter(c)) => match usize::try_from(p.id) { + Ok(k @ 0..9) => c.disabled[k] = v == 1, + Ok(9) => c.triggered = v == 1, + _ => {} + }, // BrewingStandBlockEntity.dataAccess. Some(BlockEntity::Brewing(b)) => match p.id { 0 => b.brew_time = v, @@ -1895,6 +2096,7 @@ impl Game<'_> { C::RecipeBookSettings(p) => self.remote_recipe_book_settings(p), C::PlaceGhostRecipe(p) => self.remote_ghost_recipe(p), C::MerchantOffers(p) => self.remote_merchant_offers(p), + C::ContainerClose(_) if self.remote_lectern_closed() => {} C::ContainerClose(_) => { if self.screen == Screen::Inventory { self.remote_close_local(); @@ -2469,6 +2671,7 @@ impl Game<'_> { self.previous_eye = 1.62; self.clock.reset(); self.apply_remote_health(); + self.apply_remote_abilities(); } } self.previous_position = position; @@ -2604,6 +2807,7 @@ impl Game<'_> { [player.velocity.x, player.velocity.y, player.velocity.z], [player.position.x, player.position.y, player.position.z], ); + let was_flying = player.flying; player.yaw = self.yaw; let dead = self.screen == Screen::Dead; // LivingEntity.isImmobile: a sleeper lies still in the bed. @@ -2626,6 +2830,9 @@ impl Game<'_> { } .controlled_simulation_tick(keys)?; } + // LocalPlayer.onUpdateAbilities: flight turned on or off (a double + // jump, a spectator, landing) is sent to the server. + let flying = player.flying; let events = std::mem::take(&mut player.events); self.previous_eye = self.eye; self.eye += (player.dimensions.eye_height - self.eye) * 0.5; @@ -2660,9 +2867,29 @@ impl Game<'_> { if !dead { self.remote_tick_using(); } + if flying != was_flying { + self.send(S::PlayerAbilities(play::PlayerAbilitiesRequest { + flags: if flying { 2 } else { 0 }, + })); + } self.remote_send_state(input); Ok(()) } + + /// ClientPacketListener.handlePlayerAbilities: the player flies, may fly + /// and is invulnerable as the server says (bits 2, 4 and 1). + fn apply_remote_abilities(&mut self) { + let (Some(player), Some(a)) = ( + self.player.as_mut(), + self.remote.as_ref().and_then(|r| r.abilities.as_ref()), + ) else { + return; + }; + player.invulnerable = a.flags & 1 != 0; + player.flying = a.flags & 2 != 0; + player.may_fly = a.flags & 4 != 0; + player.flying_speed = a.flying_speed; + } /// The local player's share of every touching entity's /// `LivingEntity.pushEntities`: on a client `EntitySelector.pushableBy` /// lets entities push only the local player, so the server never sends @@ -3228,7 +3455,11 @@ impl Game<'_> { .and_then(|h| self.res.items().get(&h.item)) .is_some_and(|i| i.block.is_some()); if let Some(hit) = self.pick() { - let reacts = hand == Hand::Main && self.remote_block_reacts(&hit, held.as_ref()); + let (reacts, changes) = if hand == Hand::Main { + self.remote_block_reacts(&hit, held.as_ref()) + } else { + (false, DryUse::default()) + }; let seq = self.next_sequence(); let cursor = [ (hit.point[0] - f64::from(hit.pos[0])) as f32, @@ -3254,6 +3485,9 @@ impl Game<'_> { r.use_target = Some(hit.pos); r.placing = Some((target, ticks)); } + if reacts { + self.predict_use(&changes, seq); + } if held_block { self.with_hand(hand, Game::swing_arm); return true; @@ -3263,15 +3497,61 @@ impl Game<'_> { false } + /// MultiPlayerGameMode.useItemOn inside startPrediction: the blocks the + /// use changed on this client's level at once, each kept as predicted + /// under the use's sequence until the server acknowledges it (a use the + /// server refused goes back). Only the blocks a hand opens or flips: a + /// wooden or copper door, trapdoor or fence gate, a lever or a button; + /// whatever else the use changes waits for the server. + fn predict_use(&mut self, (changes, sounds): &DryUse, seq: i32) { + let facts = self.res.facts(); + let predicted = |state: BlockStateId| hand_operated(&facts.get(state).name); + if changes.is_empty() + || !changes + .iter() + .all(|(p, s)| predicted(*s) && predicted(self.world.block(p.x, p.y, p.z))) + { + return; + } + for &(p, state) in changes { + let pos = [p.x, p.y, p.z]; + let before = self.world.block(p.x, p.y, p.z); + // BlockStatePredictionHandler.retainKnownServerState. + if let Some(r) = self.remote.as_mut() { + r.predictions + .entry(pos) + .and_modify(|e| e.0 = seq) + .or_insert((seq, before.0 as i32)); + } + self.set_block(pos, state.0 as i32); + } + // `level.playSound(player, ...)`: the clicker hears it from its own use; the + // server sends it to the others only. + for (pos, sound, volume, pitch) in sounds { + let at = [ + f64::from(pos.x) + 0.5, + f64::from(pos.y) + 0.5, + f64::from(pos.z) + 0.5, + ]; + let name = if sound.contains(':') { + sound.to_string() + } else { + format!("minecraft:{sound}") + }; + self.audio.play(&name, Some(at), *volume, *pitch); + } + } + /// Whether the block hit takes a main-hand right click with `held` /// (`BlockState.useItemOn`, then `useWithoutItem`): a door, a button, a - /// container. Vanilla's client runs it on its own level first; this runs - /// it on a copy that keeps no change. - fn remote_block_reacts(&self, hit: &super::Hit, held: Option<&ItemStack>) -> bool { + /// container, and the blocks it changed. Vanilla's client runs it on its + /// own level first; this runs it on a copy, and `predict_use` keeps the + /// changes it predicts. + fn remote_block_reacts(&self, hit: &super::Hit, held: Option<&ItemStack>) -> (bool, DryUse) { // Player.isSecondaryUseActive with something in either hand. let hands_full = self.stack_in(self.selected).is_some() || self.offhand.is_some(); if self.keys.contains(&KeyCode::ShiftLeft) && hands_full { - return false; + return (false, DryUse::default()); } use horizon_core::geometry::Direction; let face = match hit.face { @@ -3286,8 +3566,10 @@ impl Game<'_> { world: &self.world, changed: HashMap::new(), random: horizon_core::random::LegacyRandom::new(0), + sounds: Vec::new(), }; - self.res + let reacts = self + .res .behaviours() .use_item_on( &mut level, @@ -3298,7 +3580,8 @@ impl Game<'_> { self.use_context(), held.map(|s| &*s.item), ) - .consumes_action() + .consumes_action(); + (reacts, (level.changed.into_iter().collect(), level.sounds)) } /// MultiPlayerGameMode.useItem for `hand`, if it holds something: whether @@ -3320,6 +3603,16 @@ impl Game<'_> { // MultiPlayerGameMode.useItem runs the use here too: food starts // being eaten (Consumable.startConsuming). self.with_hand(hand, |g| g.start_eating(&info)); + // BowItem.use: startUsingItem here too (with an arrow, or in creative), so that letting + // go sends RELEASE_USE_ITEM (Minecraft.handleKeybinds) and the server shoots. + if &*held.item == "minecraft:bow" { + self.with_hand(hand, |g| { + if g.using.is_none() && (g.creative || g.projectile_slot("minecraft:bow").is_some()) + { + g.using = Some((g.held_slot(), 0)); + } + }); + } item_has_use(&info) } @@ -3335,14 +3628,20 @@ impl Game<'_> { } self.remote_use_item(Hand::Off); } - /// `LivingEntity.updatingUsingItem` for a consumable on a server client: the - /// eating animation and its crumbs. The server eats it and sends the - /// stack, the hunger and the sounds. + /// `LivingEntity.updatingUsingItem` on a server client: a drawn bow, and a + /// consumable's eating animation and its crumbs. The server eats it and + /// sends the stack, the hunger and the sounds. fn remote_tick_using(&mut self) { let Some((slot, ticks)) = self.using else { return; }; let stack = self.stack_in(slot).cloned(); + // A drawn bow: held until the button lets go (or another slot is picked). + if stack.as_ref().is_some_and(|s| &*s.item == "minecraft:bow") { + self.using = (slot == self.selected || slot == super::shield::OFFHAND_SLOT) + .then_some((slot, ticks + 1)); + return; + } let consumable = stack .as_ref() .and_then(|s| self.res.items().get(&s.item)) @@ -3452,7 +3751,18 @@ impl Game<'_> { return true; } let mut instant = false; - if let Some((i, distance)) = self.mob_hit() + // A ghast's fireball or a wind charge nearer than any mob: the + // server turns it (game/deflect.rs). + if let Some((i, distance)) = self.redirectable_hit() + && self.mob_hit().is_none_or(|(_, d)| distance <= d) + && self.before_block(distance) + && self.creatures.projectiles[i].id != 0 + { + self.send(S::Attack(play::Attack { + id: self.creatures.projectiles[i].id as i32, + })); + self.reset_attack_strength(); + } else if let Some((i, distance)) = self.mob_hit() && self.before_block(distance) { self.send(S::Attack(play::Attack { @@ -3633,6 +3943,10 @@ impl Game<'_> { /// engine doesn't model sends the clicks unpredicted. False when a click's /// slot isn't one of the menu's. pub(super) fn remote_menu_ops(&mut self, ops: &[(Option, i32, Input)]) -> bool { + // CrafterScreen.slotClicked: a slot toggle goes out before the click. + if let [(Some(slot), button, input)] = ops { + self.crafter_slot_clicked(*slot, *button, *input); + } let (container, menu) = self.remote_menu(); let mut clicks = Vec::with_capacity(ops.len()); for &(slot, button, input) in ops { @@ -3785,13 +4099,8 @@ impl Game<'_> { r.menu = None; r.menu_title = None; } - if self - .station - .as_ref() - .is_some_and(|s| s.kind == super::stations::Kind::Merchant) - { - self.station = None; - } + // The client's menu has no level access: what it holds is the server's. + self.station = None; self.craft_size = 2; if let Some(key) = self.container.take() { // Server containers stay renderable but lose their copied slots. @@ -3865,6 +4174,27 @@ impl Game<'_> { .as_ref() .and_then(|r| r.use_target) .map(|t| (t[0], t[1], t[2])); + if menu == "minecraft:lectern" { + // LecternScreen: the book and page come in the menu's content and data. + if let Some(r) = self.remote.as_mut() { + r.menu = Some((p.container, menu)); + } + self.remote_open_lectern(target.unwrap_or_default()); + return; + } + if let Some(kind) = Self::remote_station_kind(&menu) { + let title = plain( + &p.title, + &self + .remote + .as_ref() + .map(|r| r.lang.clone()) + .unwrap_or_default(), + ); + let pos = target.map_or([0, 0, 0], |t| [t.0, t.1, t.2]); + self.remote_open_station(p.container, menu, kind, title, pos); + return; + } if menu == "minecraft:merchant" { // A trading window: its offers follow in a MerchantOffers packet. let title = plain( @@ -3904,6 +4234,8 @@ impl Game<'_> { horizon_client::brewing::BrewingStand::new(), ))), "minecraft:generic_3x3" => Some(BlockEntity::Chest(vec![None; 9])), + // CrafterMenu: the disabled slots and triggered come in ContainerSetData. + "minecraft:crafter_3x3" => Some(BlockEntity::Crafter(Default::default())), m if m.starts_with("minecraft:generic_9x") || m == "minecraft:shulker_box" => { let rows = m .strip_prefix("minecraft:generic_9x") @@ -4102,6 +4434,13 @@ impl Game<'_> { .filter(|m| r.level_players.contains_key(&(m.id as i32)) && !m.alive()) .map(|m| m.id) .collect::>(), + // The other players this client draws lying in a bed (SLEEPING_POS). + "lying_players": self + .mobs + .iter() + .filter(|m| r.level_players.contains_key(&(m.id as i32)) && m.extra.ints[1] != 0) + .map(|m| m.id) + .collect::>(), // The player's own model exists (third person and the inventory draw it). "player_model": self.player_model.is_some(), "health": r.health.0, @@ -4193,9 +4532,45 @@ struct DryLevel<'w> { world: &'w horizon_client::world::World, changed: HashMap, random: horizon_core::random::LegacyRandom, + /// The sounds the use plays (a door's creak). + sounds: Vec, +} + +type DrySound = ( + horizon_core::position::BlockPos, + std::sync::Arc, + f32, + f32, +); +/// What a use on the dry level changed, and the sounds it played. +type DryUse = ( + Vec<(horizon_core::position::BlockPos, BlockStateId)>, + Vec, +); + +/// The blocks a guest's hand flips that its use predicts (and hears at once): a wooden or +/// copper door, trapdoor or fence gate, a lever or a button. An iron door or trapdoor has +/// no hand use. +pub(super) fn hand_operated(name: &str) -> bool { + let name = name.trim_start_matches("minecraft:"); + ((name.ends_with("_door") || name.ends_with("_trapdoor")) && !name.starts_with("iron_")) + || name.ends_with("_fence_gate") + || name.ends_with("_button") + || name == "lever" } impl horizon_world::level::LevelAccess for DryLevel<'_> { + fn emit(&mut self, event: horizon_world::level::LevelEvent) { + if let horizon_world::level::LevelEvent::Sound { + pos, + sound, + volume, + pitch, + } = event + { + self.sounds.push((pos, sound, volume, pitch)); + } + } fn block_state(&self, pos: horizon_core::position::BlockPos) -> BlockStateId { self.changed .get(&pos) diff --git a/crates/horizon-client/src/game/remote_stations.rs b/crates/horizon-client/src/game/remote_stations.rs new file mode 100644 index 000000000..b46725345 --- /dev/null +++ b/crates/horizon-client/src/game/remote_stations.rs @@ -0,0 +1,156 @@ +//! A server's workstation menus on this client: the server opens the menu +//! (`ClientboundOpenScreenPacket` with the station's `MenuType`), the +//! station screen draws it, and its clicks and buttons are predicted on the +//! menu engine (`Game::menu_session`) and sent, as +//! `MultiPlayerGameMode.handleContainerInput` and `handleInventoryButtonClick` +//! do. The menu's client-side `slotsChanged` follows the server's slots, and +//! its data slots come in `ClientboundContainerSetDataPacket`. +use super::{ + Game, Screen, + stations::{Kind, Station}, +}; +use horizon_protocol::packets::play::{self, Serverbound as S}; + +impl Game<'_> { + /// The server opened workstation menu `menu` in window `container`. + pub(super) fn remote_open_station( + &mut self, + container: i32, + menu: String, + kind: Kind, + title: String, + pos: [i32; 3], + ) { + if let Some(r) = self.remote.as_mut() { + r.menu = Some((container, menu)); + r.menu_title = Some(title); + } + self.craft_size = 2; + self.container = None; + self.station = Some(Station::new_kind(kind, pos)); + self.screen = Screen::Inventory; + self.capture(false); + } + + /// Window `container` is the server's workstation menu, open here. + pub(super) fn remote_station_open(&self, container: i32) -> bool { + self.station.is_some() + && self + .remote + .as_ref() + .and_then(|r| r.menu.as_ref()) + .is_some_and(|(id, name)| { + *id == container && Self::remote_station_kind(name).is_some() + }) + } + + /// The server set station slot `internal`: the client menu's + /// `Slot.set` runs its container's `setChanged`, so the loom lists the + /// patterns its inputs allow and the stonecutter the recipes of its input. + pub(super) fn remote_station_slot_changed(&mut self, internal: usize) { + if !self.station.as_ref().is_some_and(|s| { + matches!( + s.kind, + Kind::Loom + | Kind::Stonecutter + | Kind::Grindstone + | Kind::Anvil + | Kind::Smithing + | Kind::Cartography + ) + }) { + return; + } + self.menu_session(|menu, env, to_menu| { + let i = to_menu(internal)?; + let stack = menu.slot(i).cloned(); + menu.set_slot(env, i, stack); + Some(true) + }); + // AnvilScreen.slotChanged: the box shows the new input's name, which + // its responder sends. + self.remote_anvil_rename(); + } + + /// `AbstractContainerMenu.setData` from the server. + pub(super) fn remote_station_data(&mut self, id: usize, value: i16) { + let Some(s) = self.station.as_mut() else { + return; + }; + match (s.kind, id) { + // LoomMenu.selectedBannerPatternIndex. + (Kind::Loom, 0) => s.loom.selected = usize::try_from(value).ok(), + // StonecutterMenu.selectedRecipeIndex. + (Kind::Stonecutter, 0) => s.selected = usize::try_from(value).ok(), + // AnvilMenu.cost. + (Kind::Anvil, 0) => s.anvil.cost = i32::from(value), + // EnchantmentMenu: costs, the seed (the screen's glyph names), + // the clues' enchantments and levels. + (Kind::Enchanting, 0..3) => s.offers.costs[id] = i32::from(value), + (Kind::Enchanting, 3) => self.level.xp_seed = i32::from(value), + (Kind::Enchanting, 4..7) => { + let name = self.remote.as_ref().and_then(|r| { + r.registries + .name("minecraft:enchantment", i32::from(value)) + .map(std::sync::Arc::::from) + }); + let level = s.offers.clues[id - 4].as_ref().map_or(1, |(_, l)| *l); + s.offers.clues[id - 4] = name.map(|n| (n, level)); + } + (Kind::Enchanting, 7..10) => { + if let Some((_, level)) = s.offers.clues[id - 7].as_mut() { + *level = value.max(0) as u32; + } + } + // BeaconMenu: the levels, then the powers (BeaconScreen's + // dataChanged shows the menu's). + (Kind::Beacon, 0) => s.beacon_levels = Some(i32::from(value)), + (Kind::Beacon, 1 | 2) => { + let effect = self.remote_effect_id(i32::from(value) - 1); + let index = + effect.and_then(|e| super::beacon::EFFECTS.iter().position(|(n, _)| *n == e)); + if let Some(s) = self.station.as_mut() { + s.beacon[id - 1] = index; + } + } + _ => {} + } + } + + /// `AnvilScreen.onNameChanged` on a server: the rename box's text (blank + /// when it is the input's own name) goes to the server when the menu's + /// `setItemName` takes it. + pub(super) fn remote_anvil_rename(&mut self) { + if self.remote.is_none() { + return; + } + let Some(s) = self + .station + .as_ref() + .filter(|s| s.kind == Kind::Anvil && s.inputs[0].is_some()) + else { + return; + }; + let name = self.anvil_item_name(s); + if s.anvil_sent.as_deref() == Some(&name) { + return; + } + if let Some(s) = self.station.as_mut() { + s.anvil_sent = Some(name.clone()); + } + self.send(S::RenameItem(play::RenameItem { name })); + } + + /// `MultiPlayerGameMode.handleInventoryButtonClick`: the screen already + /// ran `clickMenuButton` on its own menu. + pub(super) fn remote_station_button(&self, button: i32) { + if let Some((container, _)) = self.remote.as_ref().and_then(|r| r.menu.as_ref()) + && self.remote_station_open(*container) + { + self.send(S::ContainerButtonClick(play::ContainerButtonClick { + container: *container, + button, + })); + } + } +} diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index 99dae39a5..e01d6ed03 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -431,20 +431,18 @@ impl Game<'_> { self.score.board.players_team(self.acting_player_name()) } /// The teams of the player and of the mobs on one (empty without teams). - pub(super) fn mob_teams(&self) -> horizon_client::mobs::Teams { + pub(super) fn mob_teams(&self) -> horizon_client::mobs::Teams<'_> { let board = &self.score.board; if board.teams.is_empty() { return Default::default(); } horizon_client::mobs::Teams { - player: self.player_team().cloned(), + player: self.player_team(), mobs: self .persist .uuids .iter() - .filter_map(|(id, uuid)| { - Some((*id, board.players_team(&uuid_text(*uuid))?.clone())) - }) + .filter_map(|(id, uuid)| Some((*id, board.players_team(&uuid_text(*uuid))?))) .collect(), } } diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs index 096562608..8667f305f 100644 --- a/crates/horizon-client/src/game/sculk.rs +++ b/crates/horizon-client/src/game/sculk.rs @@ -71,6 +71,8 @@ pub(super) struct SculkState { /// The sculk block entities in the order they were added. index: Index, pub known: HashSet<(i32, i32)>, + /// The chunk map's membership revision `known` was taken at. + pub known_revision: Option, // Keyed by mob ids the server gives out: the fast hasher is safe. steps: FxHashMap, damaged: FxHashMap, @@ -336,7 +338,10 @@ impl Game<'_> { /// the block writes recorded since the last tick. pub(super) fn sculk_sync_index(&mut self) { // Chunks that arrived or left (every half second is plenty). - if self.sculk.ticks.is_multiple_of(10) { + // Nothing to do while no chunk came or went. + let revision = self.world.chunks.membership_revision(); + if self.sculk.ticks.is_multiple_of(10) && self.sculk.known_revision != Some(revision) { + self.sculk.known_revision = Some(revision); let loaded: HashSet<(i32, i32)> = self.world.chunks.keys().copied().collect(); let arrived: Vec<(i32, i32)> = loaded.difference(&self.sculk.known).copied().collect(); for key in arrived { diff --git a/crates/horizon-client/src/game/sculk_fixture.rs b/crates/horizon-client/src/game/sculk_fixture.rs index 890e571b8..b02dfe998 100644 --- a/crates/horizon-client/src/game/sculk_fixture.rs +++ b/crates/horizon-client/src/game/sculk_fixture.rs @@ -433,6 +433,7 @@ impl Game<'_> { }); self.level_events.clear(); self.sculk.known = self.world.chunks.keys().copied().collect(); + self.sculk.known_revision = Some(self.world.chunks.membership_revision()); self.sculk_sync_index(); let mut names: HashMap = HashMap::new(); let mut sources: Vec = Vec::new(); @@ -665,7 +666,7 @@ impl Game<'_> { if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { m.damage(amount, horizon_client::mobs::Damage::player(at)); } - self.last_hurt_by_player.insert(id); + self.last_hurt_by_player.insert(id, self.lan_acting); } "set" => { let n = |i: usize| words[i].parse::().unwrap_or(0); diff --git a/crates/horizon-client/src/game/shader_packs.rs b/crates/horizon-client/src/game/shader_packs.rs index 6b9ee33dc..7d628ef44 100644 --- a/crates/horizon-client/src/game/shader_packs.rs +++ b/crates/horizon-client/src/game/shader_packs.rs @@ -37,11 +37,8 @@ impl ShaderPacks { } } -/// `shaderpacks/` beside `options.txt`. pub(super) fn dir() -> PathBuf { - std::env::current_dir() - .unwrap_or_default() - .join(shader_pack::DIR) + shader_pack::folder() } impl Game<'_> { @@ -77,6 +74,7 @@ impl Game<'_> { return self.shader_pack_error(&id, &e.to_string()); } self.shader_packs.pack = pack; + self.ui.options.shader_pack_error = None; } /// Give the loaded pack to the renderer (also after it is rebuilt). pub(super) fn apply_shader_pack(&mut self) -> horizon_client::Result<()> { @@ -105,6 +103,11 @@ impl Game<'_> { } fn shader_pack_error(&mut self, id: &str, error: &str) { log::warn!("Horizon: shader pack {id}: {error}"); + // The Shader Packs page says why on the pack's row: the first line, + // since translator errors go on with a drawn source excerpt. + let first = error.lines().map(str::trim).find(|l| !l.is_empty()); + self.ui.options.shader_pack_error = + Some((id.to_owned(), first.unwrap_or(error).to_owned())); self.system_message(Text::literal(format!("Shader pack {id}: {error}"))); } } diff --git a/crates/horizon-client/src/game/startup_menu.rs b/crates/horizon-client/src/game/startup_menu.rs index c5b19763c..ffbbe7193 100644 --- a/crates/horizon-client/src/game/startup_menu.rs +++ b/crates/horizon-client/src/game/startup_menu.rs @@ -373,6 +373,11 @@ impl Loading { let _ = std::fs::create_dir_all(&dir); packs::open_folder(&dir); } + Event::OpenShaderPackFolder => { + let dir = horizon_client::shader_pack::folder(); + let _ = std::fs::create_dir_all(&dir); + packs::open_folder(&dir); + } Event::ButtonClick => {} } } diff --git a/crates/horizon-client/src/game/station_control.rs b/crates/horizon-client/src/game/station_control.rs index 75ad9225e..ecbbad0b8 100644 --- a/crates/horizon-client/src/game/station_control.rs +++ b/crates/horizon-client/src/game/station_control.rs @@ -10,6 +10,7 @@ pub(super) const HELP: &[&str] = &[ "use X Y Z open the block's menu as if right-clicked", "click-slot ID [right] [shift] click a menu slot (0-35 inventory, 300+ container, 600+ station, 650 result)", "click-gui X Y [right] [shift] click at GUI pixel X Y relative to the menu's top-left corner", + "book [next|back|take|done] the open book or lectern: its page, or press one of its buttons", "type TEXT | type-back type into the anvil name box / delete one character", "enchant ID LEVEL enchant the held item (books store the enchantment)", "potion ITEM POTION give a potion item (potion, splash_potion, lingering_potion, tipped_arrow)", @@ -136,6 +137,7 @@ impl Game<'_> { self.apply_equipment(); ok() } + "book" => Ok(Some(self.book_control(words.get(1).copied())?)), "potion" => { let stack = ItemStack::new(&id(arg(1)?), 1).with_potion(&id(arg(2)?)); let rest = self.give(stack); diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index c19f6165c..ffe56d699 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -13,7 +13,6 @@ use horizon_client::{ stations::{self, AnvilResult, EnchantOffers}, }; use horizon_core::random::{LegacyRandom, RandomSource}; -use std::sync::Arc; /// Slot ids of the open station: inputs from 600, the result at 650. pub(super) const INPUT: usize = 600; @@ -36,7 +35,7 @@ pub(super) enum Kind { Loom, } impl Kind { - fn from_block(name: &str) -> Option { + pub(super) fn from_block(name: &str) -> Option { Some(match name { "minecraft:enchanting_table" => Self::Enchanting, "minecraft:anvil" | "minecraft:chipped_anvil" | "minecraft:damaged_anvil" => { @@ -51,7 +50,7 @@ impl Kind { _ => return None, }) } - fn inputs(self) -> usize { + pub(super) fn inputs(self) -> usize { match self { Self::Smithing | Self::Loom => 3, Self::Stonecutter | Self::Beacon => 1, @@ -71,7 +70,7 @@ impl Kind { Self::Loom => "gui/container/loom", } } - fn title_key(self) -> &'static str { + pub(super) fn title_key(self) -> &'static str { match self { Self::Enchanting => "container.enchant", Self::Anvil => "container.repair", @@ -108,6 +107,10 @@ impl Kind { }; table[i.min(table.len() - 1)] } + /// Whether the menu has a result slot after its inputs. + pub(super) fn has_result(self) -> bool { + self.result_pos().is_some() + } fn result_pos(self) -> Option<(f32, f32)> { match self { Self::Enchanting => None, @@ -128,18 +131,20 @@ pub(super) struct Station { pub(super) pos: [i32; 3], pub(super) inputs: Vec>, pub(super) result: Option, - offers: EnchantOffers, + pub(super) offers: EnchantOffers, bookcases: i32, - anvil: AnvilResult, + pub(super) anvil: AnvilResult, /// Anvil rename box text. pub(super) name: String, - /// Stonecutter: recipe indices for the input, selection and first shown index. - recipes: Vec, - selected: Option, + /// Stonecutter: the menu's recipe list (horizon_client::menu), its + /// `selectedRecipeIndex` and the screen's first shown index. + pub(super) stone: horizon_client::menu::Stonecutter, + pub(super) selected: Option, start: usize, - input_item: Option>, /// Anvil: the input the rename box was last filled from. anvil_last: Option, + /// Anvil on a server: the name last sent (the client menu's `itemName`). + pub(super) anvil_sent: Option, /// When the screen opened: the rename box has the focus from then. opened: std::time::Instant, pub(super) last_sound: u64, @@ -147,6 +152,8 @@ pub(super) struct Station { pub(super) merchant: Option>, /// Beacon menu: the selected primary and secondary power (EFFECTS index). pub(super) beacon: [Option; 2], + /// A server's beacon menu: the pyramid's levels (its data slot 0). + pub(super) beacon_levels: Option, /// The loom's patterns, selection and scroller (game/loom.rs). pub(super) loom: super::loom::LoomState, } @@ -161,21 +168,29 @@ impl Station { bookcases: 0, anvil: AnvilResult::default(), name: String::new(), - recipes: Vec::new(), + stone: Default::default(), selected: None, start: 0, - input_item: None, anvil_last: None, + anvil_sent: None, opened: std::time::Instant::now(), last_sound: 0, merchant: None, beacon: [None; 2], + beacon_levels: None, loom: Default::default(), } } pub(super) fn new_kind(kind: Kind, pos: [i32; 3]) -> Self { Self::new(kind, pos) } + /// `StonecutterScreen.containerChanged`: without recipes to show, the + /// list scrolls back to the top. + pub(super) fn stonecutter_changed(&mut self) { + if self.inputs[0].is_none() || self.stone.recipes.is_empty() { + self.start = 0; + } + } } /// The 108x19 enchantment button `i` (relative to the GUI origin). @@ -323,6 +338,10 @@ impl Game<'_> { let Some(mut station) = self.station.take() else { return; }; + if self.remote.is_some() && station.kind != Kind::Merchant { + // A server's workstation: its removed() gives the inputs back. + return; + } if let Some(m) = station.merchant.as_mut() { self.merchant_closed(m); } @@ -375,7 +394,7 @@ impl Game<'_> { _ => &mut self.scratch_slot, } } - fn count_bookshelves(&self, pos: [i32; 3]) -> i32 { + pub(super) fn count_bookshelves(&self, pos: [i32; 3]) -> i32 { let tags = &self.res.items().block_tags; let is = |p: [i32; 3], tag: &str| { let name = &self @@ -399,7 +418,7 @@ impl Game<'_> { .count() as i32 } /// The anvil name the menu works with (`AnvilScreen.onNameChanged`). - fn anvil_item_name(&self, s: &Station) -> String { + pub(super) fn anvil_item_name(&self, s: &Station) -> String { match &s.inputs[0] { Some(input) if input.custom_name().is_none() && s.name == self.pack.names.item(&input.item) => @@ -419,6 +438,16 @@ impl Game<'_> { let data = self.res.stations(); let items = self.res.items(); match s.kind { + // A server's table: its data slots carry the offers, and its + // client menu only clears them without an enchantable item. + Kind::Enchanting if self.remote.is_some() => { + let enchantable = s.inputs[0].as_ref().is_some_and(|i| { + data.enchantments.enchantable(&i.item) > 0 && i.enchantments().is_empty() + }); + if !enchantable { + s.offers = Default::default(); + } + } Kind::Enchanting => { s.bookcases = self.count_bookshelves(s.pos); s.offers = stations::enchant_offers( @@ -465,35 +494,9 @@ impl Game<'_> { // The menu engine keeps the merchant's result (Game::menu_session). Kind::Merchant => {} Kind::Beacon => {} - Kind::Cartography => s.result = self.cartography_result(&s), - // The menu engine keeps the loom's state (Game::menu_session). - Kind::Loom => {} - Kind::Stonecutter => { - let item = s.inputs[0].as_ref().map(|i| i.item.clone()); - if item != s.input_item { - s.input_item = item; - s.selected = None; - s.start = 0; - s.recipes = match &s.inputs[0] { - Some(input) => data - .recipes - .stonecutting - .iter() - .enumerate() - .filter(|(_, r)| r.input.test(input)) - .map(|(i, _)| i) - .collect(), - None => Vec::new(), - }; - } - s.result = match (s.selected, &s.inputs[0]) { - (Some(i), Some(_)) => s - .recipes - .get(i) - .map(|&r| data.recipes.stonecutting[r].result.clone()), - _ => None, - }; - } + // The menu engine keeps the cartography table's, the loom's and + // the stonecutter's state (Game::menu_session). + Kind::Cartography | Kind::Loom | Kind::Stonecutter => {} } self.station = Some(s); } @@ -505,7 +508,6 @@ impl Game<'_> { } /// `Slot.mayPlace` and `getMaxStackSize` for station slots. fn slot_rules(&self, slot: usize, stack: &ItemStack) -> (bool, u32) { - let data = self.data(); if slot >= super::mount_menu::SADDLE { return self.mount_slot_rules(slot, stack); } @@ -528,24 +530,7 @@ impl Game<'_> { if slot == RESULT { return (false, 64); } - let i = slot - INPUT; - match s.kind { - Kind::Enchanting if i == 0 => (true, 1), - Kind::Beacon => (super::beacon::is_payment(&stack.item), 1), - Kind::Loom => (false, 64), - Kind::Cartography if i == 0 => (super::maps::map_id(stack).is_some(), 64), - Kind::Cartography => ( - matches!( - &*stack.item, - "minecraft:paper" | "minecraft:map" | "minecraft:glass_pane" - ), - 64, - ), - Kind::Enchanting => (&*stack.item == "minecraft:lapis_lazuli", 64), - Kind::Grindstone => (stations::grindstone_accepts(self.res.items(), stack), 64), - Kind::Smithing => (data.recipes.smithing_accepts(i, stack), 64), - _ => (true, 64), - } + (s.kind != Kind::Loom, 64) } /// `AbstractContainerMenu.doClick` PICKUP on a filtered slot. pub(super) fn click_filtered(&mut self, slot: usize, right: bool) { @@ -644,112 +629,80 @@ impl Game<'_> { } stack.count != start } - /// The player inventory in menu order: main rows, then the hotbar. - fn player_slots() -> Vec { - (9..36).chain(0..9).collect() + /// After an anvil or smithing click on the menu engine: the anvil's cost + /// and state back into the station and the rename box following the + /// input (`AnvilScreen.slotChanged`), then the rest of a taken result's + /// `onTake` (the levels, the anvil's wear, the use sound) unless a + /// server does it. + pub(super) fn combiner_session_end( + &mut self, + menu: &horizon_client::menu::Menu, + predicting: bool, + ) { + let Some(s) = self.station.as_mut() else { + return; + }; + let (pos, kind) = (s.pos, s.kind); + if kind == Kind::Anvil { + s.anvil.cost = menu.data[0]; + s.anvil.repair_item_count_cost = menu.anvil.repair_count; + s.anvil.only_renaming = menu.anvil.only_renaming; + s.anvil.result = s.result.clone(); + } + self.station_after_input(); + if !menu.combined || predicting { + return; + } + if kind == Kind::Smithing { + self.level_event_at(1044, pos, 0); + return; + } + self.give_levels(menu.level_change); + if self.anvil_used(pos, self.creative) { + self.close_station(); + self.screen = Screen::Playing; + self.capture(true); + } } - /// A shift-click: `AbstractContainerMenu.doClick`'s QUICK_MOVE repeats - /// `quickMoveStack` while it moves something and the slot still holds the - /// same item. - fn quick_move(&mut self, slot: usize) { - while let Some(item) = self.slot_mut(slot).as_ref().map(|s| s.item.clone()) - && self.quick_move_once(slot) - && self.slot_mut(slot).as_ref().is_some_and(|s| s.item == item) - {} - } - /// The station menu's `quickMoveStack` for one slot (`EnchantmentMenu`, - /// `BeaconMenu`, `GrindstoneMenu`, `StonecutterMenu`, - /// `CartographyTableMenu`, and `ItemCombinerMenu` with `SmithingMenu`'s - /// `canMoveIntoInputSlots`); whether the stack's count changed. Each - /// rule that names its target slots moves nowhere else when they are full. - fn quick_move_once(&mut self, slot: usize) -> bool { - let Some(kind) = self.station.as_ref().map(|s| s.kind) else { - return false; - }; - let Some(mut stack) = self.slot_mut(slot).take() else { - return false; - }; - let start = stack.count; - let empty = |game: &mut Self, i: usize| game.station_slot_mut(INPUT + i).is_none(); - // The other half of the inventory: main rows to the hotbar and back. - let halves: Vec = if slot < 9 { - (9..36).collect() - } else { - (0..9).collect() - }; - if slot >= INPUT { - // An input slot: into the inventory, the hotbar's last slot first - // where vanilla moves in reverse. - let reverse = matches!(kind, Kind::Enchanting | Kind::Beacon); - self.move_to(&mut stack, &Self::player_slots(), reverse); - } else { - match kind { - Kind::Enchanting => { - if &*stack.item == "minecraft:lapis_lazuli" { - self.move_to(&mut stack, &[INPUT + 1], true); - } else if empty(self, 0) { - *self.station_slot_mut(INPUT) = Some(ItemStack { - count: 1, - ..stack.clone() - }); - stack.count -= 1; - } + /// `AnvilMenu.onTake`'s level part: out of creative a 12% chance + /// (`AnvilBlock.damage`) to wear the anvil a stage, or break a damaged one + /// (level event 1029); otherwise level event 1030. True when it broke. + pub(super) fn anvil_used(&mut self, pos: [i32; 3], creative: bool) -> bool { + let state = self.world.block(pos[0], pos[1], pos[2]); + let name = self.res.facts().get(state).name.clone(); + let anvil = matches!( + &*name, + "minecraft:anvil" | "minecraft:chipped_anvil" | "minecraft:damaged_anvil" + ); + if !creative && anvil && self.world.random.next_float() < 0.12 { + match &*name { + "minecraft:anvil" => { + let _ = self.set_state_named(pos, "minecraft:chipped_anvil", &["facing"]); } - Kind::Beacon => { - if empty(self, 0) && super::beacon::is_payment(&stack.item) && stack.count == 1 - { - self.move_to(&mut stack, &[INPUT], false); - } else { - self.move_to(&mut stack, &halves, false); - } + "minecraft:chipped_anvil" => { + let _ = self.set_state_named(pos, "minecraft:damaged_anvil", &["facing"]); } - Kind::Grindstone => { - if empty(self, 0) || empty(self, 1) { - self.move_to(&mut stack, &[INPUT, INPUT + 1], false); - } else { - self.move_to(&mut stack, &halves, false); - } + _ => { + let _ = self.world.set(pos[0], pos[1], pos[2], self.world.air); + self.world.modified.insert((pos[0] >> 4, pos[2] >> 4)); + self.level_event_at(1029, pos, 0); + return true; } - Kind::Stonecutter => { - if self.data().recipes.stonecutter(&stack).is_empty() { - self.move_to(&mut stack, &halves, false); - } else { - self.move_to(&mut stack, &[INPUT], false); - } - } - Kind::Cartography => { - if super::maps::map_id(&stack).is_some() { - self.move_to(&mut stack, &[INPUT], false); - } else if matches!( - &*stack.item, - "minecraft:paper" | "minecraft:map" | "minecraft:glass_pane" - ) { - self.move_to(&mut stack, &[INPUT + 1], false); - } else { - self.move_to(&mut stack, &halves, false); - } - } - Kind::Anvil | Kind::Smithing => { - let inputs: Vec = (0..kind.inputs()).map(|i| INPUT + i).collect(); - // ItemCombinerMenu.canMoveIntoInputSlots: always for the - // anvil; the smithing table needs an empty slot whose - // ingredient test takes the stack. - let into_inputs = kind == Kind::Anvil - || (0..3).any(|i| { - empty(self, i) && self.data().recipes.smithing_accepts(i, &stack) - }); - let targets = if into_inputs { &inputs } else { &halves }; - self.move_to(&mut stack, targets, false); - } - // Their clicks run on the menu engine. - Kind::Merchant | Kind::Loom => {} } } - let moved = stack.count != start; - if stack.count > 0 { - *self.slot_mut(slot) = Some(stack); + self.level_event_at(1030, pos, 0); + false + } + /// The grindstone result's `onTake` with a level (`amount`: the menu's + /// `getExperienceAmount` sum): the orbs at the block's centre + /// (`ExperienceOrb.award`), then level event 1042, the grindstone's sound + /// for everyone around. + pub(super) fn grindstone_taken(&mut self, pos: [i32; 3], amount: i32) { + let xp = stations::grindstone_xp_roll(amount, &mut self.world.random); + if xp > 0 { + self.spawn_orbs(pos.map(|v| f64::from(v) + 0.5), xp); } - moved + self.level_event_at(1042, pos, 0); } fn play_at(&mut self, sound: &str, pos: [i32; 3], volume: f32, pitch: f32) { let at = [ @@ -788,185 +741,6 @@ impl Game<'_> { _ => true, } } - /// The result slot's `onTake`. - fn take_result(&mut self) { - let Some(mut s) = self.station.take() else { - return; - }; - let pos = s.pos; - match s.kind { - Kind::Anvil => { - let cost = s.anvil.cost; - let repair = s.anvil.repair_item_count_cost; - if repair > 0 { - if let Some(a) = s.inputs[1].as_mut() - && a.count > repair - { - a.count -= repair; - } else { - s.inputs[1] = None; - } - } else if !s.anvil.only_renaming { - s.inputs[1] = None; - } - s.inputs[0] = None; - s.name.clear(); - if !self.creative { - self.give_levels(-cost); - } - let pitch = self.world.random.next_float() * 0.1 + 0.9; - if !self.creative && self.world.random.next_float() < 0.12 { - // AnvilBlock.damage - let state = self.world.block(pos[0], pos[1], pos[2]); - let name = self.res.facts().get(state).name.clone(); - let next = match &*name { - "minecraft:anvil" => Some("minecraft:chipped_anvil"), - "minecraft:chipped_anvil" => Some("minecraft:damaged_anvil"), - _ => None, - }; - match next { - Some(next) => { - let _ = self.set_state_named(pos, next, &["facing"]); - self.play_at("minecraft:block.anvil.use", pos, 1.0, pitch); - } - None => { - let _ = self.world.set(pos[0], pos[1], pos[2], self.world.air); - self.world.modified.insert((pos[0] >> 4, pos[2] >> 4)); - self.play_at("minecraft:block.anvil.destroy", pos, 1.0, pitch); - self.station = Some(s); - self.close_station(); - self.screen = Screen::Playing; - self.capture(true); - return; - } - } - } else { - self.play_at("minecraft:block.anvil.use", pos, 1.0, pitch); - } - } - Kind::Grindstone => { - let (a, b) = (s.inputs[0].take(), s.inputs[1].take()); - let mut random = LegacyRandom::new(self.world.random.next_long()); - let xp = stations::grindstone_experience( - &self.res.stations().enchantments, - &mut random, - a.as_ref(), - b.as_ref(), - ); - if xp > 0 { - self.spawn_orbs( - [ - f64::from(pos[0]) + 0.5, - f64::from(pos[1]) + 0.5, - f64::from(pos[2]) + 0.5, - ], - xp, - ); - } - let pitch = self.world.random.next_float() * 0.1 + 0.9; - self.play_at("minecraft:block.grindstone.use", pos, 1.0, pitch); - } - Kind::Smithing => { - for slot in s.inputs.iter_mut() { - if let Some(x) = slot.as_mut() { - x.count -= 1; - if x.count == 0 { - *slot = None; - } - } - } - let pitch = self.world.random.next_float() * 0.1 + 0.9; - self.play_at("minecraft:block.smithing_table.use", pos, 1.0, pitch); - } - Kind::Stonecutter => { - if let Some(x) = s.inputs[0].as_mut() { - x.count -= 1; - if x.count == 0 { - s.inputs[0] = None; - } - } - if s.last_sound != self.ticks { - s.last_sound = self.ticks; - self.play_at("minecraft:ui.stonecutter.take_result", pos, 1.0, 1.0); - } - } - Kind::Merchant => {} - Kind::Beacon => {} - Kind::Cartography => { - for slot in &mut s.inputs { - if let Some(x) = slot.as_mut() { - x.count -= 1; - if x.count == 0 { - *slot = None; - } - } - } - if s.last_sound != self.ticks { - s.last_sound = self.ticks; - self.cartography_taken(pos); - } - } - Kind::Loom => {} - Kind::Enchanting => {} - } - self.station = Some(s); - self.station_changed(); - } - fn click_result(&mut self, shift: bool) { - loop { - let Some(result) = self.station.as_ref().and_then(|s| s.result.clone()) else { - return; - }; - if !self.may_take_result() { - return; - } - let result = if self - .station - .as_ref() - .is_some_and(|s| s.kind == Kind::Cartography) - { - self.cartography_post(result) - } else { - result - }; - if shift { - let mut stack = result.clone(); - let player = Self::player_slots(); - // Simulate first so nothing is lost when the inventory is full. - let saved: Vec> = self.inventory.clone(); - self.move_to(&mut stack, &player, true); - if stack.count > 0 { - self.inventory = saved; - return; - } - } else { - match &mut self.carried { - None => self.carried = Some(result.clone()), - Some(c) - if c.same_item_same_components(&result) - && c.count + result.count - <= self.res.items().get(&c.item).map_or(64, |i| i.max_stack) => - { - c.count += result.count - } - _ => return, - } - } - if let Some(s) = self.station.as_mut() { - s.result = None; - } - self.take_result(); - let again = shift - && self - .station - .as_ref() - .and_then(|s| s.result.as_ref()) - .is_some_and(|r| r.item == result.item); - if !again { - return; - } - } - } /// `EnchantmentMenu.clickMenuButton`. fn click_enchant(&mut self, button: usize) { let Some(s) = self.station.as_ref() else { @@ -987,6 +761,11 @@ impl Game<'_> { { return; } + if self.remote.is_some() { + // EnchantmentScreen.mouseClicked: the client menu took it, the server enchants. + self.remote_station_button(button as i32); + return; + } let Some(enchanted) = stations::apply_enchantment( &self.res.stations().enchantments, self.res.items(), @@ -1036,7 +815,7 @@ impl Game<'_> { }) .collect(), Kind::Stonecutter if s.inputs[0].is_some() => (s.start - ..(s.start + 12).min(s.recipes.len())) + ..(s.start + 12).min(s.stone.recipes.len())) .map(|index| { let p = index - s.start; [ @@ -1089,64 +868,21 @@ impl Game<'_> { } } } - if kind == Kind::Stonecutter - && let Some(s) = self.station.as_ref() - && s.inputs[0].is_some() - { - for index in s.start..(s.start + 12).min(s.recipes.len()) { - let p = index - s.start; - let (x, y) = (52.0 + (p % 4) as f32 * 16.0, 14.0 + (p / 4) as f32 * 18.0); - if inside(local, x, y, 16.0, 18.0) { - if s.selected != Some(index) { - if let Some(st) = self.station.as_mut() { - st.selected = Some(index); - } - self.audio.play( - "minecraft:ui.stonecutter.select_recipe", - None, - 1.0, - 1.0, - ); - self.station_changed(); - } - return true; - } - } + if kind == Kind::Stonecutter && self.stonecutter_click(local) { + return true; } } let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else { return true; }; - if self - .station - .as_ref() - .is_none_or(|s| matches!(s.kind, Kind::Loom | Kind::Merchant)) - { - // LoomMenu, MerchantMenu and the brewing stand's BrewingStandMenu - // clicks run on the verified menu engine. - let input = if shift { - horizon_client::menu::Input::QuickMove - } else { - horizon_client::menu::Input::Pickup - }; - self.menu_click(Some(slot), i32::from(right), input); - return true; - } - if slot == RESULT { - self.click_result(shift); - return true; - } - if shift { - self.quick_move(slot); - } else if slot >= INPUT { - self.click_filtered(slot, right); + // Every station's clicks (and the brewing stand's) run on the + // verified menu engine. + let input = if shift { + horizon_client::menu::Input::QuickMove } else { - return false; - } - if let Some(key) = self.container { - self.world.modified.insert((key.0 >> 4, key.2 >> 4)); - } - self.station_after_input(); + horizon_client::menu::Input::Pickup + }; + self.menu_click(Some(slot), i32::from(right), input); true } /// Recompute after slot changes; the anvil box follows its input item. @@ -1164,16 +900,49 @@ impl Game<'_> { } self.station_changed(); } + /// `StonecutterScreen.mouseClicked` on its recipe grid: `clickMenuButton` + /// with the cell's index (an empty cell's too), and the select sound when + /// the menu took it. + fn stonecutter_click(&mut self, local: (f32, f32)) -> bool { + let Some(start) = self + .station + .as_ref() + .filter(|s| s.inputs[0].is_some() && !s.stone.recipes.is_empty()) + .map(|s| s.start) + else { + return false; + }; + for index in start..start + 12 { + let p = index - start; + let (x, y) = (52.0 + (p % 4) as f32 * 16.0, 14.0 + (p / 4) as f32 * 18.0); + if !inside(local, x, y, 16.0, 18.0) { + continue; + } + let mut taken = false; + let flag = &mut taken; + self.menu_session(|menu, env, _| { + *flag = menu.button(env, index as i32); + Some(*flag) + }); + if taken { + self.audio + .play("minecraft:ui.stonecutter.select_recipe", None, 1.0, 1.0); + self.remote_station_button(index as i32); + return true; + } + } + false + } pub(super) fn station_scroll(&mut self, d: f32) { self.merchant_scroll(d); self.loom_scroll(d); let Some(s) = self.station.as_mut() else { return; }; - if s.kind != Kind::Stonecutter || s.recipes.len() <= 12 { + if s.kind != Kind::Stonecutter || s.stone.recipes.len() <= 12 { return; } - let rows = s.recipes.len().div_ceil(4) - 3; + let rows = s.stone.recipes.len().div_ceil(4) - 3; let first_row = (s.start / 4) as i32 - d.signum() as i32; s.start = first_row.clamp(0, rows as i32) as usize * 4; } @@ -1207,6 +976,7 @@ impl Game<'_> { } } self.station_changed(); + self.remote_anvil_rename(); } /// Ctrl+A/C/V/X in the anvil's rename box (an `EditBox` of 50) or the /// recipe book's search box. @@ -1227,6 +997,7 @@ impl Game<'_> { ANVIL_NAME_CHARS, ) { self.station_changed(); + self.remote_anvil_rename(); } } @@ -1740,9 +1511,9 @@ impl Game<'_> { } Kind::Merchant | Kind::Beacon | Kind::Cartography | Kind::Loom => {} Kind::Stonecutter => { - let display = s.inputs[0].is_some() && !s.recipes.is_empty(); - let active = display && s.recipes.len() > 12; - let rows = s.recipes.len().div_ceil(4).saturating_sub(3).max(1); + let display = s.inputs[0].is_some() && !s.stone.recipes.is_empty(); + let active = display && s.stone.recipes.len() > 12; + let rows = s.stone.recipes.len().div_ceil(4).saturating_sub(3).max(1); let offs = if active { (s.start / 4) as f32 / rows as f32 } else { @@ -1763,13 +1534,14 @@ impl Game<'_> { let (start, selected) = (s.start, s.selected); // graphics.item: the icon only, without the count. let shown: Vec<(usize, ItemStack)> = (start - ..(start + 12).min(s.recipes.len())) + ..(start + 12).min(s.stone.recipes.len())) .map(|i| { ( i, ItemStack { count: 1, - ..self.res.stations().recipes.stonecutting[s.recipes[i]] + ..self.res.stations().recipes.stonecutting + [s.stone.recipes[i]] .result .clone() }, @@ -2082,7 +1854,7 @@ impl Game<'_> { "bookcases": s.bookcases, "anvil_cost": s.anvil.cost, "result": s.result.as_ref().map(|r| format!("{} x{}", r.item, r.count)), - "recipes": s.recipes.iter().map(|&i| recipes[i].id.clone()).collect::>(), + "recipes": s.stone.recipes.iter().map(|&i| recipes[i].id.clone()).collect::>(), "selected": s.selected, }) } diff --git a/crates/horizon-client/src/game/trident.rs b/crates/horizon-client/src/game/trident.rs index b24f4540e..c31094596 100644 --- a/crates/horizon-client/src/game/trident.rs +++ b/crates/horizon-client/src/game/trident.rs @@ -122,6 +122,38 @@ impl Game<'_> { let sky = self.world.light(x, y + 1, z) >> 4 == 15; water || (self.world.weather.raining && sky) } + /// The living entities a spinning player can touch this tick, for + /// `LivingEntity.checkAutoSpinAttack` (none when not spinning). + pub(super) fn spin_targets(&self) -> Vec<(u32, Aabb)> { + let Some(p) = self + .player + .as_ref() + .filter(|p| p.auto_spin_attack_ticks > 0) + else { + return Vec::new(); + }; + // A spin moves a few blocks a tick at most. + let near = p.bounds().inflate(Vec3::new(16.0, 16.0, 16.0)); + self.mobs + .iter() + .filter(|m| m.alive() && m.bounds().intersects(near)) + .map(|m| (m.id, m.bounds())) + .collect() + } + /// `Player.doAutoAttackOnTouch`: the touched entity takes `Player.attack` + /// with the spin's damage; once the spin is over its damage is cleared. + pub(super) fn end_spin_attack(&mut self, hit: Option) { + if let Some(id) = hit + && let Some(index) = self.mobs.iter().position(|m| m.id == id) + { + self.attack_mob(index); + } + if let Some(p) = self.player.as_mut() + && p.auto_spin_attack_ticks <= 0 + { + p.auto_spin_attack_dmg = 0.0; + } + } /// `TridentItem.releaseUsing`. pub(super) fn release_trident(&mut self, ticks: u32) { if ticks < 10 { @@ -152,6 +184,9 @@ impl Game<'_> { p.velocity.y + d[1] * f64::from(strength), p.velocity.z + d[2] * f64::from(strength), ); + // Player.startAutoSpinAttack(20, 8, stack). + p.auto_spin_attack_ticks = 20; + p.auto_spin_attack_dmg = 8.0; if p.ground.on_ground { p.position.y += 1.2; } diff --git a/crates/horizon-client/src/game/wind.rs b/crates/horizon-client/src/game/wind.rs index 355b5b877..72e6ee0e8 100644 --- a/crates/horizon-client/src/game/wind.rs +++ b/crates/horizon-client/src/game/wind.rs @@ -131,7 +131,7 @@ impl Game<'_> { m.damage(1.0, source); } if p.owner == Some(Who::Player) { - self.last_hurt_by_player.insert(id); + self.last_hurt_by_player.insert(id, self.lan_acting); } } } diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 5141b6089..14c040c5c 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -34,6 +34,7 @@ fn entity_shader() -> String { mod entity_batch; use entity_batch::EntityBatch; +pub use entity_batch::WATER_MASK_OVERLAY; /// Window.getAppropriateLineWidth, in framebuffer pixels. pub fn outline_width(width: u32) -> f32 { @@ -106,12 +107,16 @@ struct Globals { fog_ends: [f32; 4], /// Atlas rects (u0, v0, width, height) of end_sky.png and end_portal.png. end_portal_sprites: [[f32; 4]; 2], - /// x: vanilla's `GameTime` uniform; y: nether cardinal lighting, zw unused. + /// x: vanilla's `GameTime` uniform; y: nether cardinal lighting; z: how many + /// `dynamic_lights` are set; w unused. time: [f32; 4], - /// Atlas rect of the current destroy stage (entity.wgsl). + /// Atlas rect of a destroy stage (entity.wgsl takes only its size: every stage's is the same, + /// and each crack carries its own stage's origin). crumbling_sprite: [f32; 4], /// Framebuffer size, selection stroke width, perspective layering scale. outline_params: [f32; 4], + /// Horizon Extras' dynamic lights: camera-relative position and level (`dynamic_light`). + dynamic_lights: [[f32; 4]; crate::dynamic_light::MAX], } pub type SectionKey = (i32, i32, i32); struct SectionGpu { @@ -184,6 +189,8 @@ pub struct Frame<'a> { pub nether_lighting: bool, /// Camera-relative entity geometry textured from the shared atlas. pub entities: &'a [Vertex], + /// Horizon Extras' dynamic lights, nearest first (`dynamic_light::select`); empty when off. + pub dynamic_lights: &'a [[f32; 4]], /// Cloud mesh inputs; geometry and GPU storage are retained by the renderer. pub clouds: Option>, /// Additive translucent geometry after the entities (lightning, dragon rays). @@ -212,7 +219,8 @@ pub struct Frame<'a> { /// Atlas rects (u0, v0, width, height) of end_sky.png and end_portal.png /// (`rendertype_end_portal`'s Sampler0 and Sampler1). pub end_portal_sprites: [[f32; 4]; 2], - /// Current destroy-stage sprite: projected UVs repeat inside this atlas rect. + /// A destroy-stage sprite: projected UVs repeat inside a rect of this size, from the + /// origin each crack vertex carries (`breaking::stage_light`). pub crumbling_sprite: [f32; 4], pub ticks: u64, /// The darkness effect on the lightmap: the brightness it takes off the @@ -317,6 +325,8 @@ pub struct Renderer { crosshair_globals: wgpu::Buffer, entity_pipeline: wgpu::RenderPipeline, crumbling_pipeline: wgpu::RenderPipeline, + /// `RenderPipelines.WATER_MASK`: depth writes only, no colour. + water_mask_pipeline: wgpu::RenderPipeline, cloud_pipeline: wgpu::RenderPipeline, cloud_mesh: crate::clouds::Mesh, cloud_buffer: wgpu::Buffer, @@ -1539,7 +1549,16 @@ impl Renderer { step_mode: wgpu::VertexStepMode::Vertex, attributes: &entity_attributes, })]; - let entity_pipeline = |label, cull_mode, depth_write, compare, bias, blend, clouds| { + #[allow(clippy::too_many_arguments)] + let entity_pipeline_with = |label, + cull_mode, + depth_write, + compare, + bias, + blend, + clouds, + fragment: &str, + write_mask| { device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some(label), layout: Some(if clouds { @@ -1567,18 +1586,43 @@ impl Renderer { multisample: Default::default(), fragment: Some(wgpu::FragmentState { module: &entity_shader, - entry_point: Some("fs_entity"), + entry_point: Some(fragment), compilation_options: Default::default(), targets: &[Some(wgpu::ColorTargetState { format: config.format.remove_srgb_suffix(), blend: Some(blend), - write_mask: wgpu::ColorWrites::ALL, + write_mask, })], }), multiview_mask: None, cache: None, }) }; + let entity_pipeline = |label, cull_mode, depth_write, compare, bias, blend, clouds| { + entity_pipeline_with( + label, + cull_mode, + depth_write, + compare, + bias, + blend, + clouds, + "fs_entity", + wgpu::ColorWrites::ALL, + ) + }; + // RenderPipelines.WATER_MASK: the boat's water patch writes depth only. + let water_mask_pipeline = entity_pipeline_with( + "Water mask", + None, + true, + wgpu::CompareFunction::GreaterEqual, + Default::default(), + alpha_blend, + false, + "fs_water_mask", + wgpu::ColorWrites::empty(), + ); let crumbling_pipeline = entity_pipeline( "Breaking cracks", Some(wgpu::Face::Back), @@ -2058,6 +2102,7 @@ impl Renderer { crosshair_globals, entity_pipeline, crumbling_pipeline, + water_mask_pipeline, cloud_pipeline, cloud_mesh: Default::default(), cloud_buffer, @@ -2868,10 +2913,17 @@ impl Renderer { time: [ frame.shader_game_time, f32::from(frame.nether_lighting), - 0.0, + frame.dynamic_lights.len().min(crate::dynamic_light::MAX) as f32, 0.0, ], outline_params: outline_params(self.config.width, self.config.height), + dynamic_lights: { + let mut lights = [[0.0; 4]; crate::dynamic_light::MAX]; + for (to, from) in lights.iter_mut().zip(frame.dynamic_lights) { + *to = *from; + } + lights + }, }; self.uploads .buffer(&mut encoder, &self.globals, 0, bytemuck::bytes_of(&globals)); @@ -3183,14 +3235,19 @@ impl Renderer { self.uploads .buffer(&mut encoder, &self.outline, 0, bytemuck::cast_slice(&lines)); } - let [entity_quads, crumbling_quads, translucent_crumbling_quads] = - self.entity_batch.update( - frame.entities, - frame.additive, - frame.hand, - frame.see_through, - ); - let world_quads = entity_quads + crumbling_quads + translucent_crumbling_quads; + let [ + entity_quads, + crumbling_quads, + translucent_crumbling_quads, + water_mask_quads, + ] = self.entity_batch.update( + frame.entities, + frame.additive, + frame.hand, + frame.see_through, + ); + let world_quads = + entity_quads + crumbling_quads + translucent_crumbling_quads + water_mask_quads; let cloud_quads = if let Some(input) = &frame.clouds { let (rebuilt, uniform) = crate::spans::time("clouds", || self.cloud_mesh.prepare(input)); @@ -3552,6 +3609,19 @@ impl Renderer { pass.draw_indexed(0..crumbling_quads * 6, (entity_quads * 4) as i32, 0..1); pass.set_bind_group(0, &self.group, &[]); } + // BoatRenderer's water patch (RenderTypes.waterMask): depth only, + // before translucent terrain, so no water shows inside the boat. + if water_mask_quads > 0 { + pass.set_pipeline(&self.water_mask_pipeline); + pass.set_bind_group(0, &self.entity_group, &[]); + pass.set_vertex_buffer(0, self.entity_buffer.slice(..)); + pass.draw_indexed( + 0..water_mask_quads * 6, + ((entity_quads + crumbling_quads + translucent_crumbling_quads) * 4) as i32, + 0..1, + ); + pass.set_bind_group(0, &self.group, &[]); + } if additive_quads > 0 { pass.set_pipeline(&self.additive_pipeline); pass.set_bind_group(0, &self.entity_group, &[]); @@ -4097,6 +4167,34 @@ mod tests { ); assert_eq!(surface_format(&[Rgba16Float], Bgra8UnormSrgb), Rgba16Float); } + /// A Wayland surface on a compositor with colour management, as wgpu lists it (Mesa 26.2 + /// ANV on an Intel HD 620 under weston 16): wide formats first. The pre-#1075 choice, + /// the first non-sRGB format, took `Rgba16Float` and the window looked washed out, as if + /// under a white overlay (#1007); XWayland lists no such format, which is why it looked fine. + #[test] + fn a_colour_managed_wayland_surface_still_gets_8_bit() { + use super::surface_format; + use wgpu::TextureFormat::*; + let wayland = [ + Rgba16Float, + Rgba16Unorm, + Rgb10a2Unorm, + Bgra8UnormSrgb, + Bgra8Unorm, + Rgba8UnormSrgb, + Rgba8Unorm, + ]; + assert_eq!(surface_format(&wayland, Bgra8UnormSrgb), Bgra8Unorm); + // Without Bgra8: Rgba8, still not a 16- or 10-bit format. + let without_bgra = [ + Rgba16Float, + Rgba16Unorm, + Rgb10a2Unorm, + Rgba8UnormSrgb, + Rgba8Unorm, + ]; + assert_eq!(surface_format(&without_bgra, Rgba8UnormSrgb), Rgba8Unorm); + } #[test] fn special_material_batches_preserve_quad_order_and_offsets() { let quad = |layer, id| { @@ -4116,7 +4214,7 @@ mod tests { let mut batch = super::EntityBatch::default(); let counts = batch.update(&entities, &quad(3, 5), &quad(0, 6), &quad(0, 8)); let vertices = &batch.combined; - assert_eq!(counts, [4, 1, 1]); + assert_eq!(counts, [4, 1, 1, 0]); assert_eq!( vertices .as_chunks::<4>() diff --git a/crates/horizon-client/src/gfx/entity_batch.rs b/crates/horizon-client/src/gfx/entity_batch.rs index e7bfccb96..999113761 100644 --- a/crates/horizon-client/src/gfx/entity_batch.rs +++ b/crates/horizon-client/src/gfx/entity_batch.rs @@ -1,12 +1,19 @@ //! Stable entity material grouping with renderer-owned, reusable CPU scratch. use super::Vertex; +/// Entity materials by a quad's overlay (`Vertex::layer`), in draw order: +/// ordinary entities, breaking cracks (11), translucent breaking cracks (12) +/// and the boat water mask (13, `RenderPipelines.WATER_MASK`). +const MATERIALS: usize = 4; +/// The overlay of depth-only quads that hide water (`RenderTypes.waterMask`). +pub const WATER_MASK_OVERLAY: u32 = 13; + #[derive(Default)] pub(super) struct EntityBatch { // Quad indices avoid copying vertices twice while grouping materials. // Keep initialized high-water storage; local counts delimit active entries. // Each bucket can hold all quads, removing per-quad Vec growth checks. - buckets: [Vec; 3], + buckets: [Vec; MATERIALS], pub(super) combined: Vec, } @@ -17,18 +24,19 @@ impl EntityBatch { additive: &[Vertex], hand: &[Vertex], see_through: &[Vertex], - ) -> [u32; 3] { + ) -> [u32; MATERIALS] { let quads = entities.as_chunks::<4>().0; for bucket in &mut self.buckets { if bucket.len() < quads.len() { bucket.resize(quads.len(), 0); } } - let mut counts = [0usize; 3]; + let mut counts = [0usize; MATERIALS]; for (index, quad) in quads.iter().enumerate() { let material = match quad[0].layer { 11 => 1, 12 => 2, + WATER_MASK_OVERLAY => 3, _ => 0, }; self.buckets[material][counts[material]] = index; @@ -77,14 +85,15 @@ mod tests { entities: &[Vertex], additive: &[Vertex], hand: &[Vertex], - ) -> (Vec, [u32; 3]) { + ) -> (Vec, [u32; MATERIALS]) { let mut combined = Vec::with_capacity(entities.len() + additive.len() + hand.len()); - let mut counts = [0; 3]; - for (i, layer) in [0, 11, 12].into_iter().enumerate() { + let mut counts = [0; MATERIALS]; + for (i, layer) in [0, 11, 12, 13].into_iter().enumerate() { for quad in entities.as_chunks::<4>().0 { let material = match quad[0].layer { 11 => 11, 12 => 12, + 13 => 13, _ => 0, }; if material == layer { @@ -104,7 +113,7 @@ mod tests { pos: [index as f32, 2.0, 3.0], uv: [index as f32, 5.0], layer: if mixed { - [7, 11, 12, 4, 0][index / 4 % 5] + [7, 11, 12, 4, 13, 0][index / 4 % 6] } else { 0 }, diff --git a/crates/horizon-client/src/graphics_ui.rs b/crates/horizon-client/src/graphics_ui.rs index eea2d03cb..9722ddc21 100644 --- a/crates/horizon-client/src/graphics_ui.rs +++ b/crates/horizon-client/src/graphics_ui.rs @@ -237,7 +237,7 @@ pub fn rows(level: Level) -> Vec { h( H::ShaderPack, High, - "Redraws the world with a pack from shaderpacks/. Off is vanilla.", + "Redraws the world with a pack from the shaderpacks folder. Off is vanilla.", ), Row::Header("Preferences"), v(Opt::ViewBobbing, None, "Sways the view while walking."), @@ -422,17 +422,6 @@ impl H { H::Antialiasing => g.fxaa = !g.fxaa, H::BatteryMode => g.battery = !g.battery, H::GraphicsApi => g.api = step(&GraphicsApi::ALL, g.api, back), - H::ShaderPack => { - // Off, then every pack in shaderpacks/ by folder name. - let dir = std::env::current_dir() - .unwrap_or_default() - .join(crate::shader_pack::DIR); - let mut all = vec![String::new()]; - all.extend(crate::shader_pack::list(&dir).into_iter().map(|(id, _)| id)); - let i = all.iter().position(|x| *x == g.shader_pack).unwrap_or(0); - let n = all.len(); - g.shader_pack = all[if back { (i + n - 1) % n } else { (i + 1) % n }].clone(); - } H::Pacing => { g.pacing = match g.pacing { Pacing::Efficient => Pacing::Precise, @@ -559,6 +548,8 @@ pub enum Action { Changed, OpenAdvanced, OpenSimple, + /// The Shader Pack row: the Shader Packs page (where packs are picked). + OpenShaderPacks, Done, } @@ -784,6 +775,9 @@ impl GraphicsUi { } return match wd.target { Target::Button(action) => vec![Action::ButtonClick, action], + Target::Item(Item::Horizon(H::ShaderPack)) => { + vec![Action::ButtonClick, Action::OpenShaderPacks] + } Target::Item(item) => { if item.slider(s).is_some() { self.dragging = Some(item); @@ -1003,11 +997,30 @@ mod tests { ); s.horizon.shader_pack = "horizon-sample".into(); assert_eq!(row.label(&s).plain(), "Shader Pack: horizon-sample"); - // Picking a pack keeps the preset. - Item::Horizon(H::Preset).cycle(&mut s, false, [854, 480]); - let preset = s.horizon.preset; - row.cycle(&mut s, false, [854, 480]); - assert_eq!(s.horizon.preset, preset); + // The row opens the Shader Packs page, where packs are picked. + let mut ui = GraphicsUi::default(); + let find = |ui: &mut GraphicsUi| { + let (widgets, ..) = ui.layout(Level::Advanced, 854.0, 480.0); + widgets + .into_iter() + .find(|w| matches!(w.target, Target::Item(i) if i == row)) + .unwrap() + }; + ui.scroll = find(&mut ui).y - GraphicsUi::bounds(480.0).0 - 4.0; + let w = find(&mut ui); + assert_eq!( + ui.click( + Level::Advanced, + &mut s, + (w.x + 1.0, w.y + 1.0), + (854.0, 480.0), + [854, 480], + false, + false + ), + [Action::ButtonClick, Action::OpenShaderPacks] + ); + assert_eq!(s.horizon.shader_pack, "horizon-sample"); } #[test] diff --git a/crates/horizon-client/src/health.rs b/crates/horizon-client/src/health.rs index 493488732..442a826f0 100644 --- a/crates/horizon-client/src/health.rs +++ b/crates/horizon-client/src/health.rs @@ -231,6 +231,10 @@ impl PlayerHealth { .get(self.ids.absorption) .expect("validated absorption field") } + /// The game time the damage clock has counted. + pub fn game_time(&self) -> i64 { + self.game_time + } pub fn dead_or_dying(&self) -> bool { self.health() <= 0.0 || self.dead } @@ -274,6 +278,11 @@ impl PlayerMotion { .damage .source::<()>(source, None, None, None) .ok_or("unknown resident damage source")?; + let armor = self.attribute("minecraft:armor").unwrap_or(0.0) as f32; + let toughness = self.attribute("minecraft:armor_toughness").unwrap_or(0.0) as f32; + let before = self.health.health() + self.health.absorption(); + let fire_ticks = self.fire_ticks; + let source_name = source.definition().name.clone(); let totem_ready = self.health.totem_ready; let invulnerable = self.invulnerable; let h = &mut self.health; @@ -312,6 +321,23 @@ impl PlayerMotion { if outcome.hurt { h.hurt_animation_time = h.hurt.hurt_time; } + let after = h.health() + h.absorption(); + if self.hurt_log.len() >= HURT_LOG { + self.hurt_log.remove(0); + } + self.hurt_log.push(HurtRecord { + game_time: h.game_time, + source: source_name, + amount, + blocked: outcome.blocked, + taken: before - after, + hurt: outcome.hurt, + armor, + toughness, + health: after, + fire_ticks, + knockback: None, + }); Ok(outcome) } pub fn set_health(&mut self, value: f32, absorption: bool) -> Result<()> { @@ -363,6 +389,45 @@ pub struct Blocking { /// Angle between the head's view and the source position (pi without one). pub angle: f64, } +/// How many hurts `PlayerMotion::hurt_log` keeps. +const HURT_LOG: usize = 64; +/// One hurt as it was taken: what came in, what a raised blocking item +/// stopped, the armour it met and what health it left. +#[derive(Clone, Debug, PartialEq)] +pub struct HurtRecord { + pub game_time: i64, + /// The damage type. + pub source: String, + /// The damage before blocking, armour and effects. + pub amount: f32, + pub blocked: f32, + /// Health and absorption lost. + pub taken: f32, + pub hurt: bool, + /// `minecraft:armor` and `minecraft:armor_toughness` when it came. + pub armor: f32, + pub toughness: f32, + pub health: f32, + /// The fire ticks before the hurt. + pub fire_ticks: i32, + /// The push the hurt gave, if the caller applied one. + pub knockback: Option<[f64; 3]>, +} +/// One melee attack on a mob: the damage after the attack strength, the +/// strength (`getAttackStrengthScale`), and the health it took. +#[derive(Clone, Debug, PartialEq)] +pub struct AttackRecord { + pub game_time: i64, + pub target: String, + /// The mob's entity id, and whether the blow killed it. + pub id: u32, + pub killed: bool, + pub amount: f32, + pub scale: f32, + pub crit: bool, + pub landed: bool, + pub dealt: f32, +} /// The outcome of a hurt with a raised blocking item. #[derive(Clone, Copy, Debug, Default)] pub struct BlockOutcome { diff --git a/crates/horizon-client/src/heartbeat.rs b/crates/horizon-client/src/heartbeat.rs new file mode 100644 index 000000000..f73c7131f --- /dev/null +++ b/crates/horizon-client/src/heartbeat.rs @@ -0,0 +1,74 @@ +//! The anonymous "I'm playing" ping (`horizon_telemetry::live`, docs/telemetry.md) behind the +//! launcher's "N playing now". While the game runs, a thread of its own sends a random session +//! ID made here and kept only in memory, the version, the platform and whether a LAN or +//! play-with-friends world is open, every minute and at once when that last one changes. +//! It sends nothing when there is no server (`HORIZON_TELEMETRY_URL`, none by default) or +//! with `HORIZON_NO_HEARTBEAT=1` (automated runs). +use std::sync::OnceLock; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::thread::Thread; +use std::time::Duration; + +use horizon_telemetry::live::{self, Ping}; + +/// A world is open to LAN or to friends. +static LAN: AtomicBool = AtomicBool::new(false); +static PINGER: OnceLock = OnceLock::new(); + +/// After a failure the next ping waits longer, doubling up to this. +const MAX_WAIT: Duration = Duration::from_secs(600); + +/// Starts the pings, once. Call when the game itself starts (not a dedicated server, not a +/// benchmark or an automated run). +pub fn start() { + if PINGER.get().is_some() || std::env::var_os("HORIZON_NO_HEARTBEAT").is_some() { + return; + } + let Some(endpoint) = horizon_telemetry::endpoint() else { + return; + }; + let spawned = std::thread::Builder::new() + .name("Heartbeat".into()) + .spawn(move || run(&endpoint)); + match spawned { + Ok(handle) => { + let _ = PINGER.set(handle.thread().clone()); + } + Err(e) => log::warn!("Horizon: no live count ping: {e}"), + } +} + +/// Whether a world is open to LAN or friends; a change is sent at once. +pub fn set_lan(open: bool) { + if LAN.swap(open, Ordering::Relaxed) != open + && let Some(pinger) = PINGER.get() + { + pinger.unpark(); + } +} + +fn run(endpoint: &str) { + let session = live::session_id(); + let version = crate::telemetry::version(); + let mut wait = live::INTERVAL; + let mut failed = false; + loop { + let ping = Ping::new(&session, &version, LAN.load(Ordering::Relaxed)); + match live::send(endpoint, &ping) { + Ok(()) => { + wait = live::INTERVAL; + failed = false; + } + Err(e) => { + // Said once, not every minute the server is away. + if !failed { + log::info!("Horizon: the live count ping failed ({e}); trying again later"); + } + failed = true; + wait = (wait * 2).min(MAX_WAIT); + } + } + // Woken early by `set_lan`; a spurious wake only sends one ping more. + std::thread::park_timeout(wait); + } +} diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs index adc4e0f18..2ba8d39a9 100644 --- a/crates/horizon-client/src/item_data.rs +++ b/crates/horizon-client/src/item_data.rs @@ -594,12 +594,8 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option { ), )); } - if let Some(mode) = d.map_post_processing { - entries.push(( - "minecraft:map_post_processing", - Tag::String(if mode == 0 { "lock" } else { "scale" }.into()), - )); - } + // minecraft:map_post_processing is transient: ItemStack.CODEC never + // saves it (only the network carries it). if !d.charged.is_empty() { entries.push(( "minecraft:charged_projectiles", diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index edf094d39..ab9c98804 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -1434,6 +1434,13 @@ impl LootContext<'_> { .count() as u32; } } + // SetPotionFunction (the barter's fire resistance potions). + "minecraft:set_potion" => { + if let Some(id) = f["id"].as_str() { + *stack = std::mem::replace(stack, ItemStack::new("minecraft:air", 0)) + .with_potion(id); + } + } "minecraft:limit_count" => { let limit = &f["limit"]; if let Some(min) = limit["min"].as_i64() { @@ -1631,6 +1638,18 @@ mod tests { ); } + #[test] + fn set_potion_gives_the_potion_its_contents() { + let items = Items::for_tests(HashMap::new()); + let props = BTreeMap::new(); + let table = json!({"pools":[{"rolls":1,"entries":[{"type":"minecraft:item","name":"minecraft:splash_potion", + "modifier":{"type":"minecraft:set_potion","id":"minecraft:fire_resistance"}}]}]}); + let drops = ctx(&items, None, &props, "").evaluate(&table, &mut LegacyRandom::new(1)); + assert_eq!(drops.len(), 1); + assert_eq!(&*drops[0].item, "minecraft:splash_potion"); + assert_eq!(drops[0].potion(), Some("minecraft:fire_resistance")); + } + #[test] fn always_edible_and_consume_effects_loaded() { let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) diff --git a/crates/horizon-client/src/java_pack.rs b/crates/horizon-client/src/java_pack.rs index fb170d152..a5bc2904e 100644 --- a/crates/horizon-client/src/java_pack.rs +++ b/crates/horizon-client/src/java_pack.rs @@ -179,4 +179,43 @@ mod tests { ); assert_eq!(vendor_name(0, "Apple M4 Pro"), "Apple"); } + + /// The packs in `HORIZON_TEST_SHADERPACKS` (folders or zips) load as the + /// game loads them, with their default options: the compatibility table + /// of docs/shader-packs.md. Skipped when the variable isn't set. + #[test] + fn real_packs_load() { + let Some(dir) = std::env::var_os("HORIZON_TEST_SHADERPACKS") else { + return; + }; + let mut entries: Vec<_> = std::fs::read_dir(dir) + .unwrap() + .flatten() + .map(|e| e.path()) + .filter(|p| is_java_pack(p)) + .collect(); + entries.sort(); + let mut failures = Vec::new(); + for path in entries { + let name = path.file_name().unwrap().to_string_lossy().into_owned(); + match load(&path, &BTreeMap::new(), "Apple", "Apple M4 Pro") { + Ok(pack) => { + let folders: Vec = pack + .folders + .iter() + .map(|f| { + let n = f.passes.len() + usize::from(f.final_pass.is_some()); + format!("{} {n} passes", f.folder) + }) + .collect(); + println!("{name}: loads ({})", folders.join(", ")); + } + Err(e) => { + println!("{name}: {e}"); + failures.push(name); + } + } + } + assert!(failures.is_empty(), "{failures:?}"); + } } diff --git a/crates/horizon-client/src/lan/conn.rs b/crates/horizon-client/src/lan/conn.rs index 7a92040f2..a8ec46dad 100644 --- a/crates/horizon-client/src/lan/conn.rs +++ b/crates/horizon-client/src/lan/conn.rs @@ -778,7 +778,7 @@ fn play(c: Connection, shared: &Arc, parts: Parts, address: std::net::So std::thread::Builder::new() .name(format!("horizon-lan-out-{conn_id}")) .spawn(move || { - // A dedicated server's tick comes first (horizon_threads). + // Ticks and frames come first (horizon_threads). horizon_threads::behind_server(); write_loop(writer, rx, alive, latency, pending) }) diff --git a/crates/horizon-client/src/lan/containers.rs b/crates/horizon-client/src/lan/containers.rs index 66fbfe4b6..88f50aa3b 100644 --- a/crates/horizon-client/src/lan/containers.rs +++ b/crates/horizon-client/src/lan/containers.rs @@ -455,18 +455,30 @@ impl Hub { let Slots::Block(pos) = m.slots else { return; }; - // AbstractFurnaceBlockEntity.dataAccess, BrewingStandBlockEntity.dataAccess. + // AbstractFurnaceBlockEntity.dataAccess, BrewingStandBlockEntity.dataAccess, + // CrafterBlockEntity.containerData. let data = match world.block_entities.get(&pos) { - Some(BlockEntity::Furnace(f)) => [ + Some(BlockEntity::Furnace(f)) => vec![ f.lit_remaining, f.lit_total, f.cooking_timer, f.cooking_total, ], - Some(BlockEntity::Brewing(b)) => [b.brew_time, b.fuel, b.total_brew_time, b.total_fuel], + Some(BlockEntity::Brewing(b)) => { + vec![b.brew_time, b.fuel, b.total_brew_time, b.total_fuel] + } + // CrafterBlockEntity.containerData: the disabled slots, then triggered. + Some(BlockEntity::Crafter(c)) => c + .disabled + .iter() + .chain([&c.triggered]) + .map(|&d| i32::from(d)) + .collect(), _ => return, } - .map(|v| v as i16); + .into_iter() + .map(|v| v as i16) + .collect::>(); m.sent_data.resize(data.len(), i16::MIN); let window = m.window; let changed: Vec<(usize, i16)> = data diff --git a/crates/horizon-client/src/lan/entity.rs b/crates/horizon-client/src/lan/entity.rs index 9082e01fa..c4e8052c0 100644 --- a/crates/horizon-client/src/lan/entity.rs +++ b/crates/horizon-client/src/lan/entity.rs @@ -34,7 +34,7 @@ pub fn changed_attributes( } /// What the game says about one entity this tick. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Default, PartialEq)] pub struct EntityState { pub id: i32, pub uuid: u128, @@ -61,6 +61,72 @@ pub struct EntityState { pub precise: bool, } +impl EntityState { + /// The entity `id` of type `kind` as a fresh state has it: at the origin, + /// at rest, with no data, equipment or attributes. Keeps the allocations + /// of the strings and vectors it held. + pub fn reset(&mut self, id: i32, uuid: u128, kind: &str) { + self.id = id; + self.uuid = uuid; + self.kind.clear(); + self.kind.push_str(kind); + self.position = [0.0; 3]; + (self.yaw, self.pitch, self.head_yaw) = (0.0, 0.0, 0.0); + self.on_ground = false; + self.velocity = [0.0; 3]; + self.data = 0; + self.meta.clear(); + self.equipment.clear(); + self.attributes.clear(); + self.precise = false; + } +} + +/// The states a level describes its entities with, kept from tick to tick: +/// each tick's are written over the last tick's in place, so the strings and +/// vectors in them are reused instead of being made and freed again for every +/// entity on every tick. +#[derive(Default)] +pub struct States { + list: Vec, + len: usize, +} + +impl States { + /// Start a new tick's states. + pub fn clear(&mut self) { + self.len = 0; + } + /// The next entity's state, reset (`EntityState::reset`). + pub fn add(&mut self, id: i32, uuid: u128, kind: &str) -> &mut EntityState { + if self.len == self.list.len() { + self.list.push(EntityState::default()); + } + let e = &mut self.list[self.len]; + self.len += 1; + e.reset(id, uuid, kind); + e + } + pub fn push(&mut self, e: EntityState) { + match self.list.get_mut(self.len) { + Some(slot) => *slot = e, + None => self.list.push(e), + } + self.len += 1; + } + pub fn as_slice(&self) -> &[EntityState] { + &self.list[..self.len] + } +} + +impl Extend for States { + fn extend>(&mut self, states: I) { + for e in states { + self.push(e); + } + } +} + /// `AbstractArrow`: every update sends its position and rotation. fn is_arrow(kind: &str) -> bool { matches!( @@ -393,11 +459,13 @@ impl ServerEntity { .collect(); // A value back at its default is left out of the state, but the // clients still hold the old one: Entity's shared flags and pose go - // back to 0 (a player standing up again, a mob no longer on fire). + // back to 0 (a player standing up again, a mob no longer on fire), + // a sleeper's bed to none. for (index, kind, _) in &self.meta { let default = match (*index, *kind) { (0, serializer::BYTE) => Value::Byte(0), (6, serializer::POSE) => Value::Id(0), + (14, serializer::OPTIONAL_BLOCK_POS) => Value::OptPos(None), _ => continue, }; if !e.meta.iter().any(|m| m.0 == *index) { @@ -790,6 +858,31 @@ mod tests { } } + #[test] + fn states_are_written_over_last_ticks_in_place() { + let mut states = States::default(); + let e = states.add(1, 1, "minecraft:zombie"); + e.position = [1.0, 2.0, 3.0]; + e.meta.push((9, serializer::FLOAT, Value::Float(20.0))); + e.equipment.push((0, None)); + let (kind, meta) = (e.kind.as_ptr(), e.meta.as_ptr()); + states.push(state(2.0)); + states.clear(); + let e = states.add(3, 3, "minecraft:husk"); + // Nothing of the last tick's state is left, but its allocations are. + let fresh = EntityState { + id: 3, + uuid: 3, + kind: "minecraft:husk".into(), + ..EntityState::default() + }; + assert_eq!(*e, fresh); + assert_eq!((e.kind.as_ptr(), e.meta.as_ptr()), (kind, meta)); + assert_eq!(states.as_slice(), std::slice::from_ref(&fresh)); + states.extend([state(5.0), state(6.0)]); + assert_eq!(states.as_slice(), [fresh, state(5.0), state(6.0)]); + } + /// The entity as added this tick, then its updates (one a tick). fn added(e: &EntityState) -> ServerEntity { ServerEntity::new(e, Some(100), &Riding::default()) diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 91bf2709f..4be5aa29f 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -122,6 +122,13 @@ pub struct Guest { pub tracker: Tracker, // Player state the gameplay code reads and writes. pub motion: Option>, + /// The hurt and attack logs of the body it had before it respawned, + /// until the new body takes them over (the control socket's `hurtlog` + /// reads across a death). + pub logs_kept: Option<( + Vec, + Vec, + )>, /// The 36 inventory slots (hotbar first), armor (head..feet) and off hand. pub inventory: Vec>, pub armor: [Option; 4], @@ -140,6 +147,8 @@ pub struct Guest { pub xp_level: i32, pub xp_progress: f32, pub xp_total: i32, + /// `Player.enchantmentSeed` (the enchanting table's offers). + pub xp_seed: i32, /// Active status effects (`LivingEntity.activeEffects`). pub effects: crate::effects::PlayerEffects, /// What the client was told of each effect: id, amplifier, flags, and @@ -251,6 +260,7 @@ impl Guest { batch_quota: 0.0, tracker: Tracker::default(), motion: None, + logs_kept: None, inventory: vec![None; 36], armor: [None, None, None, None], offhand: None, @@ -265,6 +275,7 @@ impl Guest { xp_level: 0, xp_progress: 0.0, xp_total: 0, + xp_seed: 0, effects: Default::default(), sent_effects: Vec::new(), menu_sent: vec![None; 46], @@ -410,6 +421,43 @@ pub fn stack_to_network( horizon_protocol::item::Component::Int(id), )); } + if d.repair_cost > 0 { + stack.added.push(( + horizon_protocol::item::component::REPAIR_COST, + horizon_protocol::item::Component::Int(d.repair_cost as i32), + )); + } + if let Some(mode) = d.map_post_processing { + stack.added.push(( + horizon_protocol::item::component::MAP_POST_PROCESSING, + horizon_protocol::item::Component::Int(i32::from(mode)), + )); + } + // The books a lectern shows and a guest reads. + if !d.writable_pages.is_empty() { + stack.added.push(( + horizon_protocol::item::component::WRITABLE_BOOK_CONTENT, + horizon_protocol::item::Component::WritableBook(d.writable_pages.clone()), + )); + } + if let Some(w) = &d.written { + stack.added.push(( + horizon_protocol::item::component::WRITTEN_BOOK_CONTENT, + horizon_protocol::item::Component::WrittenBook( + horizon_protocol::item::WrittenBook { + title: w.title.clone(), + author: w.author.clone(), + generation: i32::from(w.generation), + pages: w + .pages + .iter() + .map(|p| horizon_protocol::text::literal(p)) + .collect(), + resolved: true, + }, + ), + )); + } } if let Some(name) = s.custom_name() { stack.added.push(( diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index a961d57a4..bb24940f4 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -85,6 +85,8 @@ pub struct HostState { pub attributes: Vec, /// `LivingEntity.DATA_LIVING_ENTITY_FLAGS` (the item in use). pub living_flags: i8, + /// The bed the host sleeps in (`LivingEntity.SLEEPING_POS`). + pub bed: Option<[i32; 3]>, } /// Everything the hub needs from the game for one tick. @@ -240,6 +242,30 @@ fn tracked(cx: i32, cz: i32, r: i32, x: i32, z: i32) -> bool { dx * dx + dz * dz < i64::from(r) * i64::from(r) } +/// The view's queue around a new centre: the queued chunks still tracked, then +/// the tracked ones neither sent nor queued, closest first (a stable sort, so +/// equally close chunks keep their order). +fn requeue( + queue: &mut Vec<(i32, i32)>, + sent: &crate::fast_hash::FxHashSet<(i32, i32)>, + (cx, cz): (i32, i32), + r: i32, +) { + queue.retain(|&(x, z)| tracked(cx, cz, r, x, z)); + // A walking player changes chunk every few ticks with hundreds of chunks + // queued: a set, not a scan of the queue for each of the view's chunks. + let mut queued: crate::fast_hash::FxHashSet<(i32, i32)> = queue.iter().copied().collect(); + for dz in -r - 2..=r + 2 { + for dx in -r - 2..=r + 2 { + let key = (cx + dx, cz + dz); + if tracked(cx, cz, r, key.0, key.1) && !sent.contains(&key) && queued.insert(key) { + queue.push(key); + } + } + } + queue.sort_by_key(|&(x, z)| i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2)); +} + /// What a level's players were last told of its clock and weather. #[derive(Clone, Copy)] struct LevelSync { @@ -309,6 +335,11 @@ impl Hub { self.sync.id(registry, name) } + /// The name of a network id in a built-in registry. + pub fn registry_name(&self, registry: &str, id: i32) -> Option<&str> { + self.sync.builtin.get(registry)?.name(id) + } + pub fn item_id(&mut self, item: &Arc) -> i32 { if let Some(id) = self.item_ids.get(item) { return *id; @@ -1288,20 +1319,7 @@ impl Hub { g.sent_chunks.remove(&(x, z)); g.send(&C::ForgetLevelChunk(play::ForgetLevelChunk { pos: [x, z] })); } - g.chunk_queue.retain(|&(x, z)| tracked(cx, cz, r, x, z)); - for dz in -r - 2..=r + 2 { - for dx in -r - 2..=r + 2 { - let key = (cx + dx, cz + dz); - if tracked(cx, cz, r, key.0, key.1) - && !g.sent_chunks.contains(&key) - && !g.chunk_queue.contains(&key) - { - g.chunk_queue.push(key); - } - } - } - g.chunk_queue - .sort_by_key(|&(x, z)| i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2)); + requeue(&mut g.chunk_queue, &g.sent_chunks, (cx, cz), r); } /// PlayerChunkSender.sendNextChunks' choice: ready chunks, closest first, @@ -1467,6 +1485,7 @@ impl Hub { on_ground: bool, flags: (bool, bool, bool, bool), living_flags: i8, + bed: Option<[i32; 3]>, skin: u8, health: f32, equipment: Vec<(u8, Option)>, @@ -1502,6 +1521,11 @@ impl Hub { // Always there: the trackers send the entries that changed, and an // item no longer in use is a change back to 0. meta.push((8, serializer::BYTE, Value::Byte(living_flags))); + // LivingEntity.SLEEPING_POS: the others draw the player lying in it, + // a player paired later too. + if let Some(bed) = bed.filter(|_| sleeping) { + meta.push((14, serializer::OPTIONAL_BLOCK_POS, Value::OptPos(Some(bed)))); + } if (health - 1.0).abs() > f32::EPSILON && health != 20.0 { meta.push((9, serializer::FLOAT, Value::Float(health))); } @@ -1565,8 +1589,9 @@ impl Hub { h.position, (h.yaw, h.pitch, h.head_yaw), h.on_ground, - (h.sneaking, h.sprinting, false, false), + (h.sneaking, h.sprinting, false, h.bed.is_some()), h.living_flags, + h.bed, 0x7F, h.health, equipment, @@ -1598,6 +1623,7 @@ impl Hub { g.on_ground, (g.sneaking, g.sprinting, g.fall_flying, g.sleeping), g.living_flags, + g.bed, g.info.model_customisation, g.health, equipment, @@ -1862,6 +1888,7 @@ impl Hub { // (handlePlayerKnownMovement), PlayerInput once loaded. let acted = match &packet { S::AcceptTeleportation(_) + | S::PlayerAbilities(_) | S::MovePlayerStatus(_) | S::MovePlayerRot(_) | S::PlayerLoaded(_) @@ -1899,6 +1926,11 @@ impl Hub { self.position_change(i, [p.x, p.y, p.z], rot, 0, ctx, events); } } + // handlePlayerAbilities: the client flies only if it may. + S::PlayerAbilities(p) => { + let g = &mut self.guests[i]; + g.flying = p.flags & 2 != 0 && (g.creative() || g.spectator()); + } S::MovePlayerPos(p) => { self.move_player(i, Some([p.x, p.y, p.z]), None, p.flags, ctx, events); } @@ -2173,6 +2205,13 @@ impl Hub { return; }; g.game_mode = mode; + // GameType.updatePlayerAbilities: a spectator flies, survival and + // adventure don't, creative keeps what it had. + if g.spectator() { + g.flying = true; + } else if !g.creative() { + g.flying = false; + } let uuid = g.uuid; g.send(&C::GameEvent(play::GameEvent { event: game_event::CHANGE_GAME_MODE, @@ -2457,3 +2496,76 @@ fn ticking_state(rate: f32, frozen: bool) -> C { w.bool(frozen); raw(ids::TICKING_STATE, w.data) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::fast_hash::FxHashSet; + + /// `requeue` as it was, scanning the queue for each chunk of the view. + fn requeue_scan( + queue: &mut Vec<(i32, i32)>, + sent: &FxHashSet<(i32, i32)>, + (cx, cz): (i32, i32), + r: i32, + ) { + queue.retain(|&(x, z)| tracked(cx, cz, r, x, z)); + for dz in -r - 2..=r + 2 { + for dx in -r - 2..=r + 2 { + let key = (cx + dx, cz + dz); + if tracked(cx, cz, r, key.0, key.1) && !sent.contains(&key) && !queue.contains(&key) + { + queue.push(key); + } + } + } + queue.sort_by_key(|&(x, z)| i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2)); + } + + /// A player walking a loop, sending a few chunks a tick: the queue + /// after every move is the one the scan built. + #[test] + fn requeue_matches_the_scan() { + for r in [2, 5, 10, 12, 32] { + let (mut a, mut b) = (Vec::new(), Vec::new()); + let mut sent = FxHashSet::default(); + for step in 0..60i32 { + let center = ((step % 17) - 8, (step * 3 % 11) - 5); + requeue(&mut a, &sent, center, r); + requeue_scan(&mut b, &sent, center, r); + assert_eq!(a, b, "radius {r}, step {step}"); + for key in a.drain(..a.len().min(7)) { + sent.insert(key); + } + b.drain(..b.len().min(7)); + sent.retain(|&(x, z)| tracked(center.0, center.1, r, x, z)); + } + } + } + + /// cargo test --release -p horizon-client --lib lan::hub::tests::requeue_cost -- --ignored --nocapture + #[test] + #[ignore] + fn requeue_cost() { + for r in [10, 16, 32] { + for (name, f) in [ + ("scan", requeue_scan as fn(&mut _, &_, _, _)), + ("set", requeue as fn(&mut _, &_, _, _)), + ] { + let sent = FxHashSet::default(); + let mut queue = Vec::new(); + let start = std::time::Instant::now(); + let moves = 200; + for step in 0..moves { + // Nothing sent yet (an explorer waiting on generation). + f(&mut queue, &sent, (step, 0), r); + } + let per = start.elapsed().as_secs_f64() * 1e6 / f64::from(moves); + println!( + "view {r}: {name} {per:.1} us per chunk crossed, {} queued", + queue.len() + ); + } + } + } +} diff --git a/crates/horizon-client/src/lan/playerdata.rs b/crates/horizon-client/src/lan/playerdata.rs index d7dc097dd..8797f25a2 100644 --- a/crates/horizon-client/src/lan/playerdata.rs +++ b/crates/horizon-client/src/lan/playerdata.rs @@ -66,6 +66,7 @@ pub fn apply(guest: &mut Guest, level: &Level) { guest.xp_level = level.xp_level; guest.xp_progress = level.xp_progress; guest.xp_total = level.xp_total; + guest.xp_seed = level.xp_seed; guest.effects = crate::effects::PlayerEffects::from_saved(&level.active_effects); guest.game_mode = level.mode(); guest.flying = level.flying; @@ -127,6 +128,7 @@ pub fn store(guest: &Guest, level: &mut Level) { level.xp_level = guest.xp_level; level.xp_progress = guest.xp_progress; level.xp_total = guest.xp_total; + level.xp_seed = guest.xp_seed; level.active_effects = guest.effects.saved(); level.game_mode = guest.game_mode; level.creative = guest.game_mode == 1; diff --git a/crates/horizon-client/src/lan/waypoints.rs b/crates/horizon-client/src/lan/waypoints.rs index 852cfc4fb..3e92d820d 100644 --- a/crates/horizon-client/src/lan/waypoints.rs +++ b/crates/horizon-client/src/lan/waypoints.rs @@ -153,6 +153,9 @@ pub struct Waypoints { /// One tick's players, and the packets for their connections. struct Tick<'a> { players: HashMap, + /// The connections of the players in other levels: one who just left this level is + /// still told of the waypoints it loses (`removePlayer` disconnects them). + away: &'a [(u128, u32)], view: HashMap, /// Players a respawn replaced this tick: a new ServerPlayer, on its first tick. fresh: &'a [u128], @@ -169,7 +172,17 @@ impl<'a> Tick<'a> { icon: &Icon, target: WaypointTarget, ) { - let Some(conn) = self.players.get(&receiver).and_then(|p| p.conn) else { + let Some(conn) = self + .players + .get(&receiver) + .and_then(|p| p.conn) + .or_else(|| { + self.away + .iter() + .find(|(uuid, _)| *uuid == receiver) + .map(|&(_, conn)| conn) + }) + else { return; }; self.out @@ -449,9 +462,22 @@ impl Waypoints { players: &[Player], respawned: &[u128], locator_bar: bool, + ) -> Vec<(u32, C)> { + self.tick_level(players, &[], respawned, locator_bar) + } + + /// [`Self::tick`] for one level of several: `away` are the connections of the players + /// in the other levels, for the untracks owed to one who has just left this one. + pub fn tick_level( + &mut self, + players: &[Player], + away: &[(u128, u32)], + respawned: &[u128], + locator_bar: bool, ) -> Vec<(u32, C)> { let mut t = Tick { players: players.iter().map(|p| (p.uuid, p)).collect(), + away, view: HashMap::default(), fresh: respawned, enabled: locator_bar, @@ -632,6 +658,29 @@ mod tests { assert_eq!(to(&out, 20), [(1, WaypointTarget::Empty)]); } + #[test] + fn a_player_leaving_the_level_loses_its_waypoints() { + let (a, b) = ( + player(1, 10, [0.5, 64.0, 0.5]), + player(2, 20, [4.5, 64.0, 0.5]), + ); + let mut w = Waypoints::default(); + w.tick(&[a.clone(), b.clone()], &[], true); + let mut moved = b.clone(); + moved.position = [5.5, 64.0, 0.5]; + w.tick(&[a.clone(), moved], &[], true); + // B goes to another level: A loses B, and B (reached through `away`) loses A. + let out = w.tick_level(std::slice::from_ref(&a), &[(2, 20)], &[], true); + assert_eq!( + to(&out, 10), + vec![(waypoint_operation::UNTRACK, WaypointTarget::Empty)] + ); + assert_eq!( + to(&out, 20), + vec![(waypoint_operation::UNTRACK, WaypointTarget::Empty)] + ); + } + #[test] fn team_colours() { assert_eq!(team_rgb("red"), Some(0xFF5555)); diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 7a69de4aa..a71418f18 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -51,6 +51,7 @@ pub mod datapack; pub mod debug_chart; pub mod debug_keys; pub mod debug_overlay; +pub mod dynamic_light; pub mod effects; pub mod enchant; pub mod end_crystal; @@ -79,6 +80,7 @@ pub mod graphics; pub mod graphics_style; pub mod graphics_ui; pub mod health; +pub mod heartbeat; pub mod hotbar; pub mod hud; pub mod hud_layout; diff --git a/crates/horizon-client/src/logging.rs b/crates/horizon-client/src/logging.rs index cb7638f26..282831f67 100644 --- a/crates/horizon-client/src/logging.rs +++ b/crates/horizon-client/src/logging.rs @@ -12,7 +12,7 @@ use std::collections::VecDeque; use std::fs::{self, File, OpenOptions}; use std::io::{self, Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; -use std::sync::Mutex; +use std::sync::{Mutex, mpsc}; use chrono::{DateTime, Local, NaiveDate}; @@ -201,16 +201,74 @@ pub fn open_latest(dir: &Path) -> io::Result> { Ok(Some(Latest { file, _lock: lock })) } -struct State { +/// What the writer thread is told. +enum Out { + /// Lines for the file, dated, and the message for stderr (Horizon's own). + Write { + date: NaiveDate, + lines: Vec, + stderr: Option, + }, + /// Answer once everything before is written. + Flush(mpsc::SyncSender<()>), +} + +/// The file side of the log, on its own thread: a line costs the thread that logs it a +/// format and a channel send, never a write that can wait (a full stderr pipe, a slow disk): +/// written on the game thread, a line could hold the tick for milliseconds while the CPU sat +/// idle. +struct Writer { file: Option, dir: PathBuf, /// The day the open file's lines belong to. date: NaiveDate, - recent: VecDeque, +} + +impl Writer { + fn run(mut self, out: mpsc::Receiver) { + let stderr = io::stderr(); + for msg in out { + match msg { + Out::Write { + date, + lines, + stderr: message, + } => { + if let Some(message) = message { + let _ = writeln!(stderr.lock(), "{message}"); + } + if date != self.date { + if let Some(latest) = &mut self.file + && let Err(e) = roll(&mut latest.file, &self.dir, self.date) + { + let _ = writeln!( + stderr.lock(), + "Horizon: could not roll over the log: {e}" + ); + } + self.date = date; + } + if let Some(latest) = &mut self.file { + let mut text = lines.join("\n"); + text.push('\n'); + let _ = latest.file.write_all(text.as_bytes()); + } + } + Out::Flush(done) => { + if let Some(latest) = &mut self.file { + let _ = latest.file.flush(); + } + let _ = done.send(()); + } + } + } + } } struct Logger { - state: Mutex, + out: mpsc::Sender, + /// The last lines, kept here (not on the writer) so a crash report has them at once. + recent: Mutex>, /// What the main thread is called in the log: "Render thread", or "Server thread" for the /// dedicated server, as in vanilla. main_thread: &'static str, @@ -233,53 +291,66 @@ impl log::Log for Logger { return; } let message = record.args().to_string(); - if ours(record.target()) { - eprintln!("{message}"); - } let current = std::thread::current(); let thread = match current.name() { Some("main") => self.main_thread, Some(name) => name, None => "unnamed", }; - self.write(thread, record.level(), &message); + let stderr = ours(record.target()).then(|| message.clone()); + self.send(thread, record.level(), &message, stderr); } + /// Waits (a second at most) until every line logged before is in the file. fn flush(&self) { - if let Some(latest) = &mut self.state.lock().unwrap_or_else(|e| e.into_inner()).file { - let _ = latest.file.flush(); + let (done, wait) = mpsc::sync_channel(1); + if self.out.send(Out::Flush(done)).is_ok() { + let _ = wait.recv_timeout(std::time::Duration::from_secs(1)); } } } impl Logger { fn write(&self, thread: &str, level: log::Level, message: &str) { + self.send(thread, level, message, None); + } + + fn send(&self, thread: &str, level: log::Level, message: &str, stderr: Option) { let now = Local::now(); - let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); - let state = &mut *state; - if now.date_naive() != state.date { - if let Some(latest) = &mut state.file - && let Err(e) = roll(&mut latest.file, &state.dir, state.date) - { - eprintln!("Horizon: could not roll over the log: {e}"); - } - state.date = now.date_naive(); - } // As log4j writes a multi-line message: the pattern once, the rest as it is. - for (i, line) in message.lines().enumerate() { - let line = if i == 0 { - format_line(&now, thread, level, line) - } else { - line.to_owned() - }; - if let Some(latest) = &mut state.file { - let _ = writeln!(latest.file, "{line}"); - } - state.recent.push_back(line); - if state.recent.len() > RECENT { - state.recent.pop_front(); + let lines: Vec = message + .lines() + .enumerate() + .map(|(i, line)| { + if i == 0 { + format_line(&now, thread, level, line) + } else { + line.to_owned() + } + }) + .collect(); + { + let mut recent = self.recent.lock().unwrap_or_else(|e| e.into_inner()); + for line in &lines { + if recent.len() == RECENT { + recent.pop_front(); + } + recent.push_back(line.clone()); } } + let msg = Out::Write { + date: now.date_naive(), + lines, + stderr, + }; + if let Err(mpsc::SendError(Out::Write { + stderr: Some(message), + .. + })) = self.out.send(msg) + { + // No writer (it could not start): the terminal still gets Horizon's messages. + eprintln!("{message}"); + } } } @@ -304,14 +375,24 @@ pub fn init(home: &Path, main_thread: &'static str) { None } }; - let logger = LOGGER.get_or_init(|| Logger { - state: Mutex::new(State { + let logger = LOGGER.get_or_init(|| { + let (out, receive) = mpsc::channel(); + let writer = Writer { file, dir, date: Local::now().date_naive(), - recent: VecDeque::new(), - }), - main_thread, + }; + if let Err(e) = std::thread::Builder::new() + .name("Log writer".into()) + .spawn(move || writer.run(receive)) + { + eprintln!("Horizon: could not start the log writer: {e}"); + } + Logger { + out, + recent: Mutex::new(VecDeque::new()), + main_thread, + } }); if log::set_logger(logger).is_ok() { log::set_max_level(log::LevelFilter::Info); @@ -341,10 +422,9 @@ pub fn write_as(thread: &str, level: log::Level, message: &str) { /// The last lines written, oldest first (for crash reports). pub fn recent_lines() -> Vec { LOGGER.get().map_or_else(Vec::new, |l| { - l.state + l.recent .lock() .unwrap_or_else(|e| e.into_inner()) - .recent .iter() .cloned() .collect() diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index 6dc8d7b7f..cb804e15b 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -3,8 +3,8 @@ //! craft drags, pickup all) for the player inventory, the crafting table, the //! chest family, hoppers, dispensers, shulker boxes, the furnaces, the brewing //! stand, the crafter (its client menu and the block entity's server menu with -//! `setSlotState`), the loom (`clickMenuButton`, `slotsChanged`) and the -//! merchant (`MerchantMenu` over a `merchant::Session`: payment slots, the +//! `setSlotState`), the loom (`clickMenuButton`, `slotsChanged`), the +//! stonecutter (its recipe buttons and result) and the merchant (`MerchantMenu` over a `merchant::Session`: payment slots, the //! result slot's trade, `tryMoveItems`). //! `tools/test_menu_click_parity.py` compares every click with vanilla's menu //! classes. @@ -24,8 +24,29 @@ pub struct Env<'a> { pub recipes: &'a Recipes, pub brewing: &'a Brewing, pub banners: &'a Banners, + /// The stonecutter's recipes. + pub station_recipes: &'a crate::stations::StationRecipes, + /// The grindstone's and the anvil's enchantment rules. + pub enchantments: &'a crate::enchant::Enchantments, + /// Item display names: the anvil compares the rename box with the + /// input's hover name. + pub names: &'a crate::creative::Names, /// What a merchant menu needs for offers made while it is open (level-ups). pub trade: Option<&'a crate::merchant::TradeEnv<'a>>, + /// The level's maps (`ContainerLevelAccess`): the cartography table reads + /// and makes them. None is a client's menu (`ContainerLevelAccess.NULL`): + /// it makes no result, and a taken result keeps its map id. + pub maps: Option<&'a dyn Maps>, +} + +/// The maps of the level a menu is in. +pub trait Maps { + /// `MapItem.getSavedData`: whether map `id` is locked, and its scale; + /// None when the level has no such map. + fn state(&self, id: i32) -> Option<(bool, u8)>; + /// `MapItem.scaleMap` (`scale`) or `lockMap`: the copy of map `id` the + /// level makes under a new id (`getFreeMapId`), None without the map. + fn derive(&self, id: i32, scale: bool) -> Option; } #[derive(Clone, Copy, PartialEq, Eq, Debug)] @@ -71,6 +92,26 @@ pub enum Kind { /// result follows the grid, and filling a disabled slot enables it. CrafterBlock, Loom, + /// `StonecutterMenu`: the input, the result, then the inventory. + Stonecutter, + /// `GrindstoneMenu`: two inputs, the result, then the inventory. + Grindstone, + /// `AnvilMenu`: two inputs, the result, then the inventory. + Anvil, + /// `SmithingMenu`: template, base, addition, the result, then the inventory. + Smithing, + /// `EnchantmentMenu`: the item, the lapis, then the inventory; its data + /// slots are the three costs, the seed and the clues. + Enchanting, + /// `BeaconMenu`: the payment slot, then the inventory; its data slots are + /// the pyramid's levels and the two powers (`encodeEffect`: id + 1). + Beacon, + /// `CartographyTableMenu`: the map, the paper / map / glass pane, the + /// result, then the inventory. + Cartography, + /// `LecternMenu` over the `LecternBlockEntity`: the book's one slot (no + /// inventory slots); its data slot is the open page. + Lectern, /// `MerchantMenu`: two payment slots, the result, then the inventory. Merchant, /// `CreativeModeInventoryScreen.ItemPickerMenu`: an item tab's 45 @@ -96,6 +137,14 @@ impl Kind { "crafter" => Self::Crafter, "crafter_be" => Self::CrafterBlock, "loom" => Self::Loom, + "stonecutter" => Self::Stonecutter, + "grindstone" => Self::Grindstone, + "anvil" => Self::Anvil, + "smithing" => Self::Smithing, + "enchanting" => Self::Enchanting, + "beacon" => Self::Beacon, + "cartography" => Self::Cartography, + "lectern" => Self::Lectern, "merchant" => Self::Merchant, "item_picker" => Self::ItemPicker, _ => return None, @@ -133,6 +182,28 @@ enum Role { LoomResult, /// `MerchantResultSlot`. MerchantResult, + /// The stonecutter's result slot (`onTake` uses up one input). + StoneResult, + /// The grindstone's inputs: damageable or enchanted items. + GrindInput, + /// The grindstone's result slot (`onTake` clears both inputs). + GrindResult, + /// A smithing table input: its recipe property set (template, base, addition). + SmithInput(usize), + /// `ItemCombinerMenu`'s result slot (the anvil's and the smithing table's). + CombineResult, + /// The enchanting table's item slot (one item). + EnchantItem, + /// The enchanting table's lapis slot. + Lapis, + /// `BeaconMenu.PaymentSlot`: one beacon payment item. + BeaconPay, + /// The cartography table's map slot (anything with a map id). + CartoMap, + /// Its paper, empty map or glass pane slot. + CartoExtra, + /// Its result (`onTake`: one of each input, the map post-processed). + CartoResult, /// `CustomCreativeSlot`: a creative tab's display slot, which the /// screen clicks itself; drags and PICKUP_ALL pass it by. CreativeDisplay, @@ -145,6 +216,26 @@ struct Slot { role: Role, } +/// `BeaconBlockEntity.BEACON_EFFECTS`: the powers of each pyramid level. +pub const BEACON_EFFECTS: [&[&str]; 4] = [ + &["minecraft:speed", "minecraft:haste"], + &["minecraft:resistance", "minecraft:jump_boost"], + &["minecraft:strength"], + &["minecraft:regeneration"], +]; + +/// `BeaconBlockEntity.getRequiredLevelsFor`: 0 for no power, `i32::MAX` +/// for one no level gives. +pub fn beacon_required_levels(effect: Option<&str>) -> i32 { + let Some(effect) = effect else { + return 0; + }; + BEACON_EFFECTS + .iter() + .position(|tier| tier.contains(&effect)) + .map_or(i32::MAX, |i| i as i32 + 1) +} + /// The containers a menu spans. const PLAYER: usize = 0; const MAIN: usize = 1; @@ -182,6 +273,53 @@ pub struct Menu { pub equipped: Vec<(&'static str, Option)>, /// The merchant a merchant menu trades with. pub merchant: Option>, + /// The stonecutter's recipe list (`recipesForInput`). + pub stone: Stonecutter, + /// The grindstone result's `getExperienceAmount` sum before its roll, + /// set when the result was taken: the caller (with a level) awards the + /// orbs and plays level event 1042. + pub ground: Option, + /// `Player.experienceLevel`, which the anvil's result needs. + pub levels: i32, + /// The levels the menu gave the player (`giveExperienceLevels`), for the caller. + pub level_change: i32, + /// `AnvilMenu`'s state besides its slots and its cost data slot. + pub anvil: Anvil, + /// The anvil's or the smithing table's result was taken: the caller (with + /// a level) runs the rest of its `onTake` (the anvil's wear and level + /// event 1030 or 1029, the smithing table's 1044). + pub combined: bool, + /// The enchanting table's item changed to an enchantable one: the caller + /// (with a level) fills the costs and clues (`slotsChanged`'s + /// `access.execute`). + pub enchant_changed: bool, + /// An enchanting button the menu took (`clickMenuButton` passed its + /// checks): the caller (with a level) enchants. + pub enchant_button: Option, + /// `Player.mayBuild` (not adventure mode): the lectern's Take Book. + pub may_build: bool, +} + +/// `AnvilMenu`'s state besides its slots and `cost`. +#[derive(Clone, Default, Debug, PartialEq)] +pub struct Anvil { + /// `itemName`: the rename box's text (`ServerboundRenameItemPacket`). + pub name: Option, + /// `repairItemCountCost`. + pub repair_count: u32, + /// `onlyRenaming`. + pub only_renaming: bool, +} + +/// `StonecutterMenu`'s state besides its slots and `selectedRecipeIndex`. +#[derive(Clone, Default, Debug, PartialEq)] +pub struct Stonecutter { + /// `recipesForInput`: indices into `StationRecipes.stonecutting`. + pub recipes: Vec, + /// The item the list was made for (`input`; None for nothing). + pub input: Option>, + /// `ResultContainer.recipeUsed`. + pub used: Option, } fn same_item(a: &ItemStack, b: &ItemStack) -> bool { @@ -196,6 +334,15 @@ fn split(stack: &mut ItemStack, amount: u32) -> ItemStack { out } +/// `LecternBlockEntity.getPageCount`: a written book's pages, else a +/// writable book's. +pub fn book_pages(stack: &ItemStack) -> usize { + stack.data().map_or(0, |d| match &d.written { + Some(w) => w.pages.len(), + None => d.writable_pages.len(), + }) +} + fn tidy(slot: &mut Option) { if slot.as_ref().is_some_and(|s| s.count == 0) { *slot = None; @@ -318,6 +465,101 @@ impl Menu { player(&mut slots); data = 1; } + Kind::Stonecutter => { + containers[MAIN] = vec![None; 1]; + slots.extend(main(1, Role::Plain)); + slots.push(Slot { + container: RESULT, + index: 0, + role: Role::StoneResult, + }); + player(&mut slots); + // selectedRecipeIndex: DataSlot.standalone() starts at 0. + data = 1; + } + Kind::Grindstone => { + containers[MAIN] = vec![None; 2]; + slots.extend(main(2, Role::GrindInput)); + slots.push(Slot { + container: RESULT, + index: 0, + role: Role::GrindResult, + }); + player(&mut slots); + } + Kind::Anvil => { + containers[MAIN] = vec![None; 2]; + slots.extend(main(2, Role::Plain)); + slots.push(Slot { + container: RESULT, + index: 0, + role: Role::CombineResult, + }); + player(&mut slots); + // cost: DataSlot.standalone() starts at 0. + data = 1; + } + Kind::Smithing => { + containers[MAIN] = vec![None; 3]; + slots.extend((0..3).map(|index| Slot { + container: MAIN, + index, + role: Role::SmithInput(index), + })); + slots.push(Slot { + container: RESULT, + index: 0, + role: Role::CombineResult, + }); + player(&mut slots); + // hasRecipeError. + data = 1; + } + Kind::Enchanting => { + containers[MAIN] = vec![None; 2]; + slots.push(Slot { + container: MAIN, + index: 0, + role: Role::EnchantItem, + }); + slots.push(Slot { + container: MAIN, + index: 1, + role: Role::Lapis, + }); + player(&mut slots); + // costs[3], enchantmentSeed, enchantClue[3], levelClue[3]. + data = 10; + } + Kind::Beacon => { + containers[MAIN] = vec![None; 1]; + slots.extend(main(1, Role::BeaconPay)); + player(&mut slots); + // levels, primary, secondary. + data = 3; + } + Kind::Cartography => { + containers[MAIN] = vec![None; 2]; + for (index, role) in [Role::CartoMap, Role::CartoExtra].into_iter().enumerate() { + slots.push(Slot { + container: MAIN, + index, + role, + }); + } + slots.push(Slot { + container: RESULT, + index: 0, + role: Role::CartoResult, + }); + player(&mut slots); + } + Kind::Lectern => { + containers[MAIN] = vec![None; 1]; + slots.extend(main(1, Role::Plain)); + // The open page (LecternBlockEntity.dataAccess). + data = 1; + } Kind::ItemPicker => { containers[MAIN] = vec![None; 45]; slots.extend(main(45, Role::CreativeDisplay)); @@ -403,15 +645,51 @@ impl Menu { crafted: Vec::new(), equipped: Vec::new(), merchant: None, + stone: Stonecutter::default(), + ground: None, + levels: 0, + level_change: 0, + anvil: Anvil::default(), + combined: false, + enchant_changed: false, + enchant_button: None, + may_build: true, } + .with_initial_data() + } + + /// Data slots that do not start at 0: the enchanting table's clues are -1. + fn with_initial_data(mut self) -> Self { + if self.kind == Kind::Enchanting { + self.data[4..].fill(-1); + } + self } pub fn kind(&self) -> Kind { self.kind } - /// `clickMenuButton`: the loom's pattern buttons. False when refused. + /// `clickMenuButton`: the loom's pattern buttons and the stonecutter's + /// recipes. False when refused. pub fn button(&mut self, env: &Env, id: i32) -> bool { + if self.kind == Kind::Lectern { + return self.lectern_button(env, id); + } + if self.kind == Kind::Enchanting { + return self.enchant_click(id); + } + if self.kind == Kind::Stonecutter { + // StonecutterMenu.clickMenuButton: an invalid index is taken too. + if self.data[0] == id { + return false; + } + if id >= 0 && (id as usize) < self.stone.recipes.len() { + self.data[0] = id; + self.stone_setup_result(env, id); + } + return true; + } if self.kind != Kind::Loom || id < 0 || id as usize >= self.loom_patterns.len() { return false; } @@ -421,6 +699,41 @@ impl Menu { true } + /// `LecternMenu.clickMenuButton`: the page buttons (1 back, 2 forward, + /// 100 + n to page n) and Take Book (3), which puts the book in the + /// inventory or drops it. + fn lectern_button(&mut self, env: &Env, id: i32) -> bool { + match id { + 100.. => self.set_data(0, id - 100), + 1 => self.set_data(0, self.data[0] - 1), + 2 => self.set_data(0, self.data[0] + 1), + 3 if self.may_build => { + // removeItemNoUpdate: the whole book, and onBookItemRemove. + let book = self.containers[MAIN][0].take(); + self.data[0] = 0; + if let Some(mut book) = book + && !self.inventory_add(env, &mut book) + { + self.drop_stack(&book); + } + } + _ => return false, + } + true + } + + /// `AbstractContainerMenu.setData`: the lectern's is + /// `LecternBlockEntity.setPage`, kept within the book's pages. + pub fn set_data(&mut self, id: usize, value: i32) { + if self.kind == Kind::Lectern && id == 0 { + // Mth.clamp(page, 0, pageCount - 1). + let count = self.containers[MAIN][0].as_ref().map_or(0, book_pages) as i32; + self.data[0] = value.max(0).min(count - 1); + return; + } + self.data[id] = value; + } + /// `CrafterBlockEntity.setSlotState` (the slot state packet): only an /// empty slot can be disabled or enabled. pub fn set_slot_state(&mut self, slot: usize, enabled: bool) { @@ -510,24 +823,278 @@ impl Menu { } } + /// `StonecutterMenu.slotsChanged`: a new input item lists its recipes + /// (`setupRecipeList`), with none selected and no result. + fn stone_changed(&mut self, env: &Env) { + let input = self.containers[MAIN][0].as_ref().map(|s| s.item.clone()); + if input == self.stone.input { + return; + } + self.stone.input = input; + self.data[0] = -1; + self.containers[RESULT][0] = None; + self.stone.recipes = match &self.containers[MAIN][0] { + Some(stack) => env + .station_recipes + .stonecutting + .iter() + .enumerate() + .filter(|(_, r)| r.input.test(stack)) + .map(|(i, _)| i) + .collect(), + None => Vec::new(), + }; + } + + /// `StonecutterMenu.setupResultSlot`. + fn stone_setup_result(&mut self, env: &Env, index: i32) { + let recipe = usize::try_from(index) + .ok() + .and_then(|i| self.stone.recipes.get(i).copied()); + self.stone.used = recipe; + self.containers[RESULT][0] = + recipe.map(|r| env.station_recipes.stonecutting[r].result.clone()); + } + /// `Slot.setChanged` on slot `s`: the loom recomputes from its inputs, - /// the block crafter refreshes its result. + /// the stonecutter lists its recipes, the block crafter refreshes its + /// result. fn slot_changed(&mut self, env: &Env, s: usize) { // MerchantContainer.setChanged: every slot of it, the result too. if self.kind == Kind::Merchant && self.slots[s].container != PLAYER { self.merchant_update(env); return; } + // SmithingMenu.slotsChanged runs for its result container too. + if self.kind == Kind::Smithing && self.slots[s].container == RESULT { + self.smith_error(); + return; + } + // CartographyTableMenu: its result container calls slotsChanged too. + if self.kind == Kind::Cartography && self.slots[s].container != PLAYER { + self.carto_changed(env); + return; + } if self.slots[s].container != MAIN { return; } match self.kind { Kind::Loom => self.loom_changed(env), + Kind::Stonecutter => self.stone_changed(env), + // GrindstoneMenu.createResult. + Kind::Grindstone => { + self.containers[RESULT][0] = crate::stations::grindstone_result( + env.enchantments, + env.items, + self.containers[MAIN][0].as_ref(), + self.containers[MAIN][1].as_ref(), + ); + } Kind::CrafterBlock => self.crafter_result(env), + Kind::Anvil => self.anvil_result(env), + Kind::Enchanting => self.enchant_changed(env), + Kind::Smithing => { + self.smith_result(env); + self.smith_error(); + } _ => {} } } + /// `EnchantmentMenu.clickMenuButton`'s checks: the lapis, the cost and + /// the levels (creative pays nothing). The enchanting itself needs a + /// level and is the caller's (`enchant_button`). + fn enchant_click(&mut self, id: i32) -> bool { + let Some(i) = usize::try_from(id).ok().filter(|&i| i < 3) else { + return false; + }; + let need = id + 1; + let lapis = self.containers[MAIN][1] + .as_ref() + .map_or(0, |l| l.count as i32); + if lapis < need && !self.creative { + return false; + } + if self.data[i] <= 0 + || self.containers[MAIN][0].is_none() + || (self.levels < need || self.levels < self.data[i]) && !self.creative + { + return false; + } + self.enchant_button = Some(i); + true + } + + /// `EnchantmentMenu.slotsChanged`: no costs or clues without an + /// enchantable item; with one, a level fills them (`enchant_changed`). + fn enchant_changed(&mut self, env: &Env) { + let enchantable = self.containers[MAIN][0].as_ref().is_some_and(|s| { + env.enchantments.enchantable(&s.item) > 0 && s.enchantments().is_empty() + }); + if enchantable { + self.enchant_changed = true; + } else { + self.data[..3].fill(0); + self.data[4..].fill(-1); + } + } + + /// `AnvilMenu.createResult`. + fn anvil_result(&mut self, env: &Env) { + let hover = self.containers[MAIN][0] + .as_ref() + .map(|i| crate::stations::hover_name(&|id| env.names.item(id), i)) + .unwrap_or_default(); + let out = crate::stations::anvil_result( + env.enchantments, + env.items, + self.containers[MAIN][0].as_ref(), + self.containers[MAIN][1].as_ref(), + self.anvil.name.as_deref(), + &hover, + self.creative, + ); + // onlyRenaming is reset, repairItemCountCost only where an input is. + self.anvil.only_renaming = out.only_renaming; + if self.containers[MAIN][0].is_some() { + self.anvil.repair_count = out.repair_item_count_cost; + } + self.data[0] = out.cost; + self.containers[RESULT][0] = out.result; + } + + /// `AnvilMenu.setItemName` (`ServerboundRenameItemPacket`): false when + /// the name is refused or unchanged. + /// `BeaconMenu.updateEffects` (`ServerboundSetBeaconPacket`): with a + /// payment, powers `BeaconBlockEntity.validateEffects` allows for the + /// pyramid's levels (data 0) become data 1 and 2 and the payment is used. + /// Each power is its `mob_effect` id and name. False when refused. + pub fn beacon_update( + &mut self, + env: &Env, + primary: Option<(i32, &str)>, + secondary: Option<(i32, &str)>, + ) -> bool { + if self.kind != Kind::Beacon || self.containers[MAIN][0].is_none() { + return false; + } + let levels = self.data[0]; + let (p, s) = ( + beacon_required_levels(primary.map(|e| e.1)), + beacon_required_levels(secondary.map(|e| e.1)), + ); + let valid = !(secondary.is_some() && levels < 4) + && p <= levels + && s <= levels + && p < 4 + && !(s != 0 && s < 4 && primary.map(|e| e.0) != secondary.map(|e| e.0)); + if !valid { + return false; + } + self.data[1] = primary.map_or(0, |e| e.0 + 1); + self.data[2] = secondary.map_or(0, |e| e.0 + 1); + self.remove(env, 0, 1); + true + } + + pub fn rename(&mut self, env: &Env, name: &str) -> bool { + // StringUtil.filterText, then validateName's length limit. + let name: String = name + .chars() + .filter(|&c| c != '\u{a7}' && c >= ' ' && c != '\u{7f}') + .collect(); + if self.kind != Kind::Anvil + || name.encode_utf16().count() > 50 + || self.anvil.name.as_deref() == Some(&name) + { + return false; + } + if let Some(result) = self.containers[RESULT][0].as_mut() { + result.data_mut().custom_name = (!name.trim().is_empty()).then(|| name.clone()); + result.tidy(); + } + self.anvil.name = Some(name); + self.anvil_result(env); + true + } + + /// `SmithingMenu.createResult`. + fn smith_result(&mut self, env: &Env) { + let [a, b, c] = [0, 1, 2].map(|i| self.containers[MAIN][i].as_ref()); + self.containers[RESULT][0] = env + .station_recipes + .smithing_result(env.enchantments, a, b, c); + } + + /// `SmithingMenu.slotsChanged`'s `hasRecipeError`: every input filled and no result. + fn smith_error(&mut self) { + let error = self.containers[MAIN].iter().all(Option::is_some) + && self.containers[RESULT][0].is_none(); + self.data[0] = i32::from(error); + } + + /// `CartographyTableMenu.slotsChanged` and `setupResultSlot`: a result + /// only where the level has the map (`access.execute`), with the post + /// processing its take runs (`MAP_POST_PROCESSING`: 0 lock, 1 scale). + fn carto_changed(&mut self, env: &Env) { + let [map, extra] = [0, 1].map(|i| self.containers[MAIN][i].clone()); + if self.containers[RESULT][0].is_some() && (map.is_none() || extra.is_none()) { + self.containers[RESULT][0] = None; + return; + } + let (Some(map), Some(extra), Some(maps)) = (map, extra, env.maps) else { + return; + }; + let Some((locked, scale)) = map + .data() + .and_then(|d| d.map_id) + .and_then(|id| maps.state(id)) + else { + return; + }; + let extendable = env + .items + .item_tags + .get("minecraft:extendable_maps") + .is_some_and(|t| t.contains(&*map.item)); + let copy = |count: u32, post: Option| { + let mut out = ItemStack { + count, + ..map.clone() + }; + if post.is_some() { + out.data_mut().map_post_processing = post; + } + out + }; + self.containers[RESULT][0] = match &*extra.item { + "minecraft:paper" if extendable && !locked && scale < 4 => Some(copy(1, Some(1))), + "minecraft:glass_pane" if !locked => Some(copy(1, Some(0))), + "minecraft:map" => Some(copy(2, None)), + _ => None, + }; + } + + /// `Item.onCraftedBy` of a taken cartography result + /// (`MapItem.onCraftedPostProcess`): the post processing goes, and on a + /// level with maps the stack names the scaled or locked copy. + fn map_crafted(env: &Env, stack: &mut ItemStack) { + if &*stack.item != "minecraft:filled_map" { + return; + } + let Some(post) = stack.data().and_then(|d| d.map_post_processing) else { + return; + }; + stack.data_mut().map_post_processing = None; + let id = stack.data().and_then(|d| d.map_id); + if let (Some(maps), Some(id)) = (env.maps, id) + && let Some(new) = maps.derive(id, post == 1) + { + stack.data_mut().map_id = Some(new); + } + stack.tidy(); + } + pub fn slot_count(&self) -> usize { self.slots.len() } @@ -539,6 +1106,11 @@ impl Menu { /// Sets a slot as a test fixture does (`Slot.set`). pub fn set_slot(&mut self, env: &Env, i: usize, stack: Option) { + if self.kind == Kind::Lectern { + // LecternBlockEntity.setBook: the book its slot can't set. + self.containers[MAIN][0] = stack; + return; + } self.put(env, i, stack); } @@ -634,10 +1206,34 @@ impl Menu { Role::LoomBanner => Self::is_banner(stack), Role::LoomDye => env.banners.loom_dye(env.items, stack).is_some(), Role::LoomPattern => env.banners.is_pattern_item(env.items, stack), - Role::LoomResult | Role::MerchantResult => false, + Role::GrindInput => crate::stations::grindstone_accepts(env.items, stack), + Role::SmithInput(i) => env.station_recipes.smithing_accepts(i, stack), + Role::EnchantItem => true, + Role::Lapis => &*stack.item == "minecraft:lapis_lazuli", + Role::BeaconPay => env + .items + .item_tags + .get("minecraft:beacon_payment_items") + .is_some_and(|t| t.contains(&*stack.item)), + Role::CartoMap => stack.data().is_some_and(|d| d.map_id.is_some()), + Role::CartoExtra => Self::is_carto_extra(stack), + Role::LoomResult + | Role::MerchantResult + | Role::StoneResult + | Role::GrindResult + | Role::CombineResult + | Role::CartoResult => false, } } + /// What the cartography table's second slot takes. + fn is_carto_extra(stack: &ItemStack) -> bool { + matches!( + &*stack.item, + "minecraft:paper" | "minecraft:map" | "minecraft:glass_pane" + ) + } + /// `BannerItem`. fn is_banner(stack: &ItemStack) -> bool { stack.item.ends_with("_banner") @@ -646,6 +1242,10 @@ impl Menu { fn may_pickup(&self, env: &Env, s: usize) -> bool { match self.slots[s].role { Role::Inert => false, + // AnvilMenu.mayPickup: the levels to pay, and a price. + Role::CombineResult if self.kind == Kind::Anvil => { + (self.creative || self.levels >= self.data[0]) && self.data[0] > 0 + } Role::MerchantResult => self .merchant .as_ref() @@ -670,7 +1270,9 @@ impl Menu { /// `Slot.getMaxStackSize(stack)`. fn slot_max(&self, env: &Env, s: usize, stack: &ItemStack) -> u32 { let own = match self.slots[s].role { - Role::Armor(_) | Role::Potion => 1, + Role::Armor(_) | Role::Potion | Role::EnchantItem | Role::BeaconPay => 1, + // The lectern's bookAccess holds one. + Role::Plain if self.kind == Kind::Lectern && self.slots[s].container == MAIN => 1, Role::Fuel if Self::is_bucket(stack) => return 1, _ => CONTAINER_MAX, }; @@ -681,12 +1283,20 @@ impl Menu { fn put(&mut self, env: &Env, s: usize, mut stack: Option) { tidy(&mut stack); let slot = self.slots[s]; + // LecternBlockEntity's bookAccess.setItem does nothing. + if self.kind == Kind::Lectern && slot.container == MAIN { + return; + } // SimpleContainer / BaseContainerBlockEntity.setItem: limitSize to // getMaxStackSize(stack). The loom's result is a SimpleContainer too. if (slot.container == MAIN || slot.role == Role::LoomResult) && let Some(st) = stack.as_mut() { st.count = st.count.min(CONTAINER_MAX.min(Self::max_stack(env, st))); + // The beacon's container holds one item (getMaxStackSize 1). + if self.kind == Kind::Beacon { + st.count = st.count.min(1); + } } // CrafterBlockEntity.setItem: filling a disabled (empty) slot enables it. if self.kind == Kind::CrafterBlock @@ -758,17 +1368,63 @@ impl Menu { .filter(|c| c.count > 0) .map(|c| split(c, amount)); tidy(cell); + // LecternBlockEntity: an emptied book slot is onBookItemRemove (page 0). + if self.kind == Kind::Lectern && slot.container == MAIN && cell.is_none() { + self.data[0] = 0; + } if out.is_some() && slot.container == GRID { self.recompute(env); } // SimpleContainer.removeItem calls setChanged when it took something; // MerchantContainer.removeItem updates the result after a payment slot. - if out.is_some() && matches!(self.kind, Kind::Loom | Kind::Merchant) { + if out.is_some() + && matches!( + self.kind, + Kind::Loom + | Kind::Merchant + | Kind::Stonecutter + | Kind::Grindstone + | Kind::Anvil + | Kind::Smithing + | Kind::Enchanting + | Kind::Cartography + ) + { self.slot_changed(env, s); } out } + /// `AnvilMenu.onTake`: the levels, the material used up, then the input. + fn anvil_take(&mut self, env: &Env) { + let cost = self.data[0]; + if !self.creative { + // Player.giveExperienceLevels(-cost). + self.level_change -= cost; + self.drops.push(format!( + "levels{}{}", + if cost <= 0 { "+" } else { "" }, + -cost + )); + } + let repair = self.anvil.repair_count; + if repair > 0 { + let addition = self.containers[MAIN][1] + .clone() + .filter(|a| a.count > repair) + .map(|mut a| { + a.count -= repair; + a + }); + self.put(env, 1, addition); + } else if !self.anvil.only_renaming { + self.put(env, 1, None); + } + self.data[0] = 0; + self.put(env, 0, None); + self.combined = true; + } + /// `CraftingMenu.slotChangedCraftingGrid`. fn recompute(&mut self, env: &Env) { if self.grid_size == 0 { @@ -787,6 +1443,57 @@ impl Menu { self.merchant_take(env); return; } + if self.slots[s].role == Role::StoneResult { + // StonecutterMenu's result onTake: awardUsedRecipes, one input + // used up, the result again for the selected recipe. + if let Some(r) = self.stone.used { + self.crafted + .push(env.station_recipes.stonecutting[r].id.clone()); + } + if self.remove(env, 0, 1).is_some() { + self.stone_setup_result(env, self.data[0]); + } + self.sounds.push("minecraft:ui.stonecutter.take_result"); + return; + } + if self.slots[s].role == Role::GrindResult { + // GrindstoneMenu's result onTake: the experience (from the inputs + // before they go), then both inputs cleared. + self.ground = Some(crate::stations::grindstone_xp_base( + env.enchantments, + self.containers[MAIN][0].as_ref(), + self.containers[MAIN][1].as_ref(), + )); + self.put(env, 0, None); + self.put(env, 1, None); + return; + } + if self.slots[s].role == Role::CombineResult && self.kind == Kind::Anvil { + self.anvil_take(env); + return; + } + if self.slots[s].role == Role::CombineResult { + // SmithingMenu.onTake: awardUsedRecipes, then one of each input. + for i in 0..3 { + if let Some(mut stack) = self.containers[MAIN][i].clone() { + stack.count -= 1; + self.put(env, i, Some(stack)); + } + } + self.combined = true; + return; + } + if self.slots[s].role == Role::CartoResult { + // CartographyTableMenu's result onTake: one of each input, the + // take sound, then Slot.onTake's setChanged. The taken stack's + // onCraftedBy is the caller's (map_crafted). + self.remove(env, 0, 1); + self.remove(env, 1, 1); + self.sounds + .push("minecraft:ui.cartography_table.take_result"); + self.slot_changed(env, s); + return; + } if self.slots[s].role == Role::LoomResult { // LoomMenu's result onTake: one banner and one dye are used up. self.remove(env, 0, 1); @@ -897,8 +1604,11 @@ impl Menu { amount: u32, max_amount: u32, ) -> Option { - let result = self.try_remove(env, s, amount, max_amount)?; + let mut result = self.try_remove(env, s, amount, max_amount)?; self.on_take(env, s); + if self.slots[s].role == Role::CartoResult { + Self::map_crafted(env, &mut result); + } Some(result) } @@ -1231,6 +1941,177 @@ impl Menu { return None; } } + Kind::Stonecutter => { + after_take = true; + if index == 1 { + if !self.move_to(env, &mut stack, 2, 38, true) { + return None; + } + } else if index == 0 { + if !self.move_to(env, &mut stack, 2, 38, false) { + return None; + } + } else if env + .station_recipes + .stonecutting + .iter() + .any(|r| r.input.test(&stack)) + { + if !self.move_to(env, &mut stack, 0, 1, false) { + return None; + } + } else if (2..29).contains(&index) { + if !self.move_to(env, &mut stack, 29, 38, false) { + return None; + } + } else if (29..38).contains(&index) && !self.move_to(env, &mut stack, 2, 29, false) + { + return None; + } + } + Kind::Grindstone => { + after_take = true; + let full = self.containers[MAIN].iter().all(Option::is_some); + if index == 2 { + if !self.move_to(env, &mut stack, 3, 39, true) { + return None; + } + } else if index == 0 || index == 1 { + if !self.move_to(env, &mut stack, 3, 39, false) { + return None; + } + } else if full { + if (3..30).contains(&index) { + if !self.move_to(env, &mut stack, 30, 39, false) { + return None; + } + } else if (30..39).contains(&index) + && !self.move_to(env, &mut stack, 3, 30, false) + { + return None; + } + } else if !self.move_to(env, &mut stack, 0, 2, false) { + return None; + } + } + Kind::Cartography => { + after_take = true; + if index == 2 { + // onCraftedBy edits the result in its slot first. + Self::map_crafted(env, &mut stack); + self.containers[RESULT][0] = Some(stack.clone()); + if !self.move_to(env, &mut stack, 3, 39, true) { + return None; + } + } else if index == 0 || index == 1 { + if !self.move_to(env, &mut stack, 3, 39, false) { + return None; + } + } else if stack.data().is_some_and(|d| d.map_id.is_some()) { + if !self.move_to(env, &mut stack, 0, 1, false) { + return None; + } + } else if Self::is_carto_extra(&stack) { + if !self.move_to(env, &mut stack, 1, 2, false) { + return None; + } + } else if (3..30).contains(&index) { + if !self.move_to(env, &mut stack, 30, 39, false) { + return None; + } + } else if (30..39).contains(&index) && !self.move_to(env, &mut stack, 3, 30, false) + { + return None; + } + } + // LecternMenu.quickMoveStack moves nothing. + Kind::Lectern => return None, + Kind::Beacon => { + // BeaconMenu.quickMoveStack. + after_take = true; + if index == 0 { + if !self.move_to(env, &mut stack, 1, 37, true) { + return None; + } + } else if self.containers[MAIN][0].is_none() + && self.may_place(env, 0, &stack) + && stack.count == 1 + { + if !self.move_to(env, &mut stack, 0, 1, false) { + return None; + } + } else if (1..28).contains(&index) { + if !self.move_to(env, &mut stack, 28, 37, false) { + return None; + } + } else if (28..37).contains(&index) { + if !self.move_to(env, &mut stack, 1, 28, false) { + return None; + } + } else if !self.move_to(env, &mut stack, 1, 37, false) { + return None; + } + } + Kind::Enchanting => { + after_take = true; + if index < 2 { + if !self.move_to(env, &mut stack, 2, 38, true) { + return None; + } + } else if &*stack.item == "minecraft:lapis_lazuli" { + if !self.move_to(env, &mut stack, 1, 2, true) { + return None; + } + } else { + // One item into the empty item slot (setByPlayer). + if self.containers[MAIN][0].is_some() { + return None; + } + let single = ItemStack { + count: 1, + ..stack.clone() + }; + stack.count -= 1; + // The source slot keeps the rest while the item slot changes. + let slot = self.slots[index]; + self.containers[slot.container][slot.index] = + (stack.count > 0).then(|| stack.clone()); + self.set_by_player(env, 0, Some(single)); + } + } + Kind::Anvil | Kind::Smithing => { + // ItemCombinerMenu.quickMoveStack. + after_take = true; + let result = if self.kind == Kind::Anvil { 2 } else { 3 }; + let (start, use_row) = (result + 1, result + 28); + let end = result + 37; + let into_inputs = self.kind == Kind::Anvil + || (0..3).any(|i| { + self.containers[MAIN][i].is_none() + && env.station_recipes.smithing_accepts(i, &stack) + }); + if index == result { + if !self.move_to(env, &mut stack, start, end, true) { + return None; + } + } else if index < result { + if !self.move_to(env, &mut stack, start, end, false) { + return None; + } + } else if into_inputs && (start..end).contains(&index) { + if !self.move_to(env, &mut stack, 0, result, false) { + return None; + } + } else if (start..use_row).contains(&index) { + if !self.move_to(env, &mut stack, use_row, end, false) { + return None; + } + } else if (use_row..end).contains(&index) + && !self.move_to(env, &mut stack, start, use_row, false) + { + return None; + } + } Kind::Merchant => { after_take = true; if index == 2 { @@ -1369,7 +2250,10 @@ impl Menu { if after_take || matches!(self.kind, Kind::Inventory | Kind::Crafting) { self.on_take(env, index); } - if index == 0 && matches!(self.kind, Kind::Inventory | Kind::Crafting) { + // What the result slot's move left over is dropped. + if (index == 0 && matches!(self.kind, Kind::Inventory | Kind::Crafting)) + || (index == 1 && self.kind == Kind::Stonecutter) + { self.drop_stack(&stack); } Some(clicked) @@ -1537,6 +2421,10 @@ impl Menu { if let Some(stack) = self.slot(slot_index as usize) { let mut copy = stack.clone(); copy.count = Self::max_stack(env, stack); + // The cartography result's safeClone runs onCraftedBy. + if self.slots[slot_index as usize].role == Role::CartoResult { + Self::map_crafted(env, &mut copy); + } self.carried = Some(copy); } } else if input == Input::Throw && self.carried.is_none() && slot_index >= 0 { @@ -1604,9 +2492,14 @@ impl Menu { } else { clicked.count.div_ceil(2) }; - if let Some(taken) = self.try_remove(env, s, amount, u32::MAX) { - self.carried = Some(taken); + if let Some(mut taken) = self.try_remove(env, s, amount, u32::MAX) { + self.carried = Some(taken.clone()); self.on_take(env, s); + if self.slots[s].role == Role::CartoResult { + // onTake's onCraftedBy edits the carried stack. + Self::map_crafted(env, &mut taken); + self.carried = Some(taken); + } } } Some(mut carried) => { @@ -1631,11 +2524,15 @@ impl Menu { } else if clicked.same_item_same_components(&carried) { let room = Self::max_stack(env, &carried).saturating_sub(carried.count); self.carried = Some(carried.clone()); - if let Some(taken) = self.try_remove(env, s, clicked.count, room) { + if let Some(mut taken) = self.try_remove(env, s, clicked.count, room) { if let Some(c) = self.carried.as_mut() { c.count += taken.count; } self.on_take(env, s); + if self.slots[s].role == Role::CartoResult { + // onCraftedBy edits the taken stack, not the carried one. + Self::map_crafted(env, &mut taken); + } } } else { self.carried = Some(carried); @@ -1660,6 +2557,11 @@ impl Menu { self.containers[PLAYER][inv_slot] = Some(taken.clone()); self.set_by_player(env, target, None); self.on_take(env, target); + if self.slots[target].role == Role::CartoResult + && let Some(stack) = self.containers[PLAYER][inv_slot].as_mut() + { + Self::map_crafted(env, stack); + } } } (Some(mut source), None) => { @@ -1698,12 +2600,14 @@ impl Menu { } /// The PICKUP_ALL branch (double click). - /// `canTakeItemForPickAll`: never the result slots (the loom's is a - /// plain slot), MerchantMenu's or an item tab's display slots. + /// `canTakeItemForPickAll`: never the result slots of the menus that + /// override it (crafting, smithing, stonecutter, cartography), MerchantMenu's + /// or an item tab's display slots. fn can_take_for_pick_all(&self, t: usize) -> bool { self.kind != Kind::Merchant && self.slots[t].role != Role::CreativeDisplay - && (self.slots[t].container != RESULT || self.kind == Kind::Loom) + && (self.slots[t].container != RESULT + || matches!(self.kind, Kind::Loom | Kind::Grindstone | Kind::Anvil)) } /// `AbstractContainerScreen.mouseReleased` on a Shift double click: @@ -2023,12 +2927,19 @@ pub(crate) mod tests { let recipes = Recipes::load(&root, &items).unwrap(); let brewing = Brewing::load(&root, &items); let banners = Banners::load(&root); + let station_recipes = crate::stations::StationRecipes::load(&root, &items); + let enchantments = crate::enchant::Enchantments::default(); + let names = crate::creative::Names::default(); let env = Env { items: &items, recipes: &recipes, brewing: &brewing, banners: &banners, + station_recipes: &station_recipes, + enchantments: &enchantments, + names: &names, trade: None, + maps: None, }; let mut menu = Menu::new(kind); menu.creative = true; diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 2c19b9251..b87b23ceb 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -690,6 +690,8 @@ pub struct Extra { pub blocking: bool, pub fall_flying: bool, pub fall_fly_ticks: i32, + /// `LivingEntity.isAutoSpinAttack` (Riptide). + pub auto_spin_attack: bool, pub main_hand_left: bool, pub elytra: ElytraAnimation, pub swim: SwimAnimation, @@ -1440,6 +1442,7 @@ pub struct PlayerView { /// (`EntitySelector.pushableBy` on the client). pub remote: bool, } +#[derive(Clone)] pub struct MobWorld<'a> { pub world: &'a World, pub registry: &'a horizon_world::registry::BlockRegistry, @@ -1454,6 +1457,8 @@ pub struct MobWorld<'a> { pub others: &'a [Seen], /// `others` by position, when the caller keeps one (the mob ticks). pub others_grid: Option<&'a seen_grid::SeenGrid>, + /// Where each id stands in `others`, when the caller keeps one. + pub others_index: Option<&'a crate::fast_hash::FxHashMap>, pub daylight: bool, pub game_time: i64, pub day_time: i64, @@ -1472,22 +1477,23 @@ pub struct MobWorld<'a> { pub world_seed: i64, /// `Level.getSeaLevel` (63 in the overworld, -63 in a flat world). pub sea_level: i32, - /// The scoreboard teams of the player and the mobs (collision rules). - pub teams: Teams, + /// The scoreboard teams of the player and the mobs (collision rules), + /// shared: the mob ticks build them once a tick, not once a mob. + pub teams: std::sync::Arc>, /// Item data (max stack sizes), when the host has it. pub items: Option<&'a crate::items::Items>, } /// `Entity.getTeam` of the player and of the mobs on a team. #[derive(Clone, Debug, Default)] -pub struct Teams { - pub player: Option, - pub mobs: HashMap, +pub struct Teams<'a> { + pub player: Option<&'a crate::scoreboard::Team>, + pub mobs: HashMap, } -impl Teams { - pub fn of(&self, who: Who) -> Option<&crate::scoreboard::Team> { +impl<'a> Teams<'a> { + pub fn of(&self, who: Who) -> Option<&'a crate::scoreboard::Team> { match who { - Who::Player => self.player.as_ref(), - Who::Mob(id) => self.mobs.get(&id), + Who::Player => self.player, + Who::Mob(id) => self.mobs.get(&id).copied(), } } } @@ -1659,13 +1665,18 @@ impl Mob { if !self.alive() || self.removed || self.invulnerable_flag { return false; } - if source.is_fire() && (self.kind.flags.fire_immune) { + // Ghast.isReflectedFireball: a fireball a player turned back is + // no fire to it, and kills it (Ghast.hurtServer: 1000 damage). + let reflected = &*self.kind.id == "minecraft:ghast" + && source.kind == DamageKind::Fireball + && source.attacker == Some(Who::Player); + if source.is_fire() && (self.kind.flags.fire_immune) && !reflected { return false; } if !ai::accepts_damage(self, &source, amount) { return false; } - let mut amount = amount; + let mut amount = if reflected { 1000.0 } else { amount }; if source.kind == DamageKind::FallingBlock && !species::body_slot(self.species()) && self.extra.head.is_some() @@ -2169,6 +2180,289 @@ mod elytra_tests { } } #[cfg(test)] +mod teams_tests { + use super::*; + use crate::save::uuid_text; + use crate::scoreboard::{Scoreboard, Team}; + + /// A board where every other mob is on the player's team, as with a + /// datapack that colours its mobs' names. + fn board(mobs: u32) -> (Scoreboard, HashMap) { + let mut board = Scoreboard::default(); + board.add_team("red"); + board.add_to_team("Steve", "red"); + let uuids: HashMap = (0..mobs) + .map(|id| (id, [id as i32, 7, -(id as i32), 11])) + .collect(); + for (id, uuid) in &uuids { + if id % 2 == 0 { + board.add_to_team(&uuid_text(*uuid), "red"); + } + } + (board, uuids) + } + /// `Game::mob_teams` as built for each mob before: owned clones of the teams. + fn owned(board: &Scoreboard, uuids: &HashMap) -> HashMap { + uuids + .iter() + .filter_map(|(id, u)| Some((*id, board.players_team(&uuid_text(*u))?.clone()))) + .collect() + } + fn borrowed<'a>(board: &'a Scoreboard, uuids: &HashMap) -> Teams<'a> { + Teams { + player: board.players_team("Steve"), + mobs: uuids + .iter() + .filter_map(|(id, u)| Some((*id, board.players_team(&uuid_text(*u))?))) + .collect(), + } + } + + #[test] + fn borrowed_teams_answer_as_the_clones() { + let (board, uuids) = board(40); + let teams = borrowed(&board, &uuids); + let old = owned(&board, &uuids); + for id in 0..41 { + assert_eq!(teams.of(Who::Mob(id)), old.get(&id), "mob {id}"); + } + assert_eq!(teams.of(Who::Player).map(|t| t.name.as_str()), Some("red")); + } + + /// One tick's worth of team building: once per mob (before) against once. + #[test] + #[ignore] + fn teams_cost() { + for mobs in [100u32, 250, 500] { + let (board, uuids) = board(mobs); + let t = std::time::Instant::now(); + for _ in 0..mobs { + std::hint::black_box(owned(&board, &uuids)); + } + let before = t.elapsed(); + let t = std::time::Instant::now(); + let reps = 20; + for _ in 0..reps { + std::hint::black_box(borrowed(&board, &uuids)); + } + let after = t.elapsed() / reps; + println!( + "{mobs} mobs, half on a team: per tick {:.3} ms -> {:.3} ms", + before.as_secs_f64() * 1e3, + after.as_secs_f64() * 1e3 + ); + } + } +} +#[cfg(test)] +mod sensor_scan_tests { + use super::*; + use horizon_core::geometry::Vec3; + use serde_json::json; + + fn kind() -> Arc { + Arc::new(MobType { + id: "minecraft:cow".into(), + species: Species::Cow, + width: 0.9, + height: 1.4, + eye_height: 1.3, + category: "creature".into(), + max_health: 10.0, + speed: 0.2, + flying_speed: 0.4, + attack_damage: 0.0, + attack_knockback: 0.0, + follow_range: 16.0, + step_height: 0.6, + armor: 0.0, + armor_toughness: 0.0, + knockback_resistance: 0.0, + jump_strength: 0.42, + attributes: Arc::default(), + gravity: 0.08, + safe_fall_distance: 3.0, + fall_damage_multiplier: 1.0, + water_efficiency: 0.0, + water_slowdown: 0.8, + air_speed: 0.02, + baby_scale: 0.5, + head_rot_speed: 10.0, + max_head_x_rot: 40.0, + max_head_y_rot: 75.0, + ambient_interval: 120, + flags: Flags { + animal: true, + ..Default::default() + }, + model: Arc::new(Part::parse("root", &json!({}))), + layers: HashMap::new(), + texture: String::new(), + brain: Brain::Passive, + anim: Anim::Rabbit, + sounds: [""; 3], + step_sound: None, + food: Arc::default(), + tempt: Arc::default(), + }) + } + /// `n` mobs in pens of 20 spread over a square of `side` blocks, as on a + /// server's farms; their snapshot and its grid. + fn herd(n: u32, side: f64) -> (Vec, seen_grid::SeenGrid) { + let kind = kind(); + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut next = |range: f64| { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1); + (seed >> 11) as f64 / (1u64 << 53) as f64 * range + }; + let mut pen = Vec3::ZERO; + let seen: Vec = (0..n) + .map(|id| { + if id % 20 == 0 { + pen = Vec3::new(next(side), 64.0, next(side)); + } + let at = Vec3::new(pen.x + next(8.0), 64.0, pen.z + next(8.0)); + Mob::new(id, kind.clone(), at, 0.0).seen(None) + }) + .collect(); + let grid = seen_grid::SeenGrid::new(seen.iter().map(|s| s.bounds)); + (seen, grid) + } + /// `NearestLivingEntitySensor` over every mob, as the brains ran it. + fn scan(seen: &[Seen], me: &Seen, area: Aabb) -> Vec { + seen.iter() + .filter(|o| o.id != me.id && o.alive && o.bounds.intersects(area)) + .map(|o| o.id) + .collect() + } + fn indexed(seen: &[Seen], grid: &seen_grid::SeenGrid, me: &Seen, area: Aabb) -> Vec { + let mut near = Vec::new(); + assert!(grid.candidates(area, &mut near)); + near.iter() + .map(|&i| &seen[i as usize]) + .filter(|o| o.id != me.id && o.alive && o.bounds.intersects(area)) + .map(|o| o.id) + .collect() + } + + #[test] + fn the_grid_finds_what_the_scan_finds() { + let (seen, grid) = herd(600, 160.0); + for me in &seen { + let area = me.bounds.inflate(Vec3::new(16.0, 16.0, 16.0)); + assert_eq!(indexed(&seen, &grid, me, area), scan(&seen, me, area)); + } + } + + /// `MobWorld::seen` once per mob (a target, a breeding partner...), by + /// scan as before and by the tick's id index. + #[test] + #[ignore] + fn lookup_cost() { + for n in [500u32, 1000, 2000] { + let (seen, _) = herd(n, 256.0); + let index: crate::fast_hash::FxHashMap = seen + .iter() + .enumerate() + .map(|(i, s)| (s.id, i as u32)) + .collect(); + let wanted: Vec = (0..n).map(|i| (i * 7919) % n).collect(); + let t = std::time::Instant::now(); + let a: usize = wanted + .iter() + .filter_map(|&id| seen.iter().find(|s| s.id == id)) + .map(|s| s.id as usize) + .sum(); + let before = t.elapsed().as_secs_f64() * 1e3; + let t = std::time::Instant::now(); + let b: usize = wanted + .iter() + .filter_map(|&id| index.get(&id).map(|&i| &seen[i as usize])) + .map(|s| s.id as usize) + .sum(); + let after = t.elapsed().as_secs_f64() * 1e3; + assert_eq!(a, b); + println!( + "{n} lookups over {n} mobs ({} B each): {before:.3} ms -> {after:.3} ms", + std::mem::size_of::() + ); + } + } + + /// Natural spawning's `isUnobstructed` box test against every mob (real + /// `Mob`s), by scan and by a grid built once for the pass. + #[test] + #[ignore] + fn spawn_box_cost() { + let kind = kind(); + for n in [500u32, 1000, 2000] { + let (seen, _) = herd(n, 384.0); + let mobs: Vec = seen + .iter() + .map(|s| Mob::new(s.id, kind.clone(), s.position, 0.0)) + .collect(); + let mut seed = 7u64; + let mut next = |range: f64| { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1); + (seed >> 11) as f64 / (1u64 << 53) as f64 * range + }; + let queries: Vec = (0..100) + .map(|_| { + let (x, z) = (next(384.0), next(384.0)); + Aabb::new(Vec3::new(x, 64.0, z), Vec3::new(x + 0.9, 65.4, z + 0.9)) + }) + .collect(); + let t = std::time::Instant::now(); + let a: Vec = queries + .iter() + .map(|&q| { + mobs.iter() + .any(|m| m.alive() && !m.removed && m.bounds().intersects(q)) + }) + .collect(); + let before = t.elapsed().as_secs_f64() * 1e3; + let t = std::time::Instant::now(); + let boxes: Vec = mobs.iter().map(|m| m.bounds()).collect(); + let grid = seen_grid::SeenGrid::new(boxes.iter().copied()); + let build = t.elapsed().as_secs_f64() * 1e3; + let mut near = Vec::new(); + let b: Vec = queries + .iter() + .map(|&q| { + assert!(grid.candidates(q, &mut near)); + near.iter().any(|&i| boxes[i as usize].intersects(q)) + }) + .collect(); + let after = t.elapsed().as_secs_f64() * 1e3; + assert_eq!(a, b); + println!( + "{n} mobs, 100 spawn box tests: {before:.3} ms -> {after:.3} ms (grid build {build:.3} ms included)" + ); + } + } + + /// One tick of sensing: a twentieth of the mobs fire their sensor. + #[test] + #[ignore] + fn sensor_cost() { + for (n, side) in [(500u32, 256.0), (1000, 384.0), (2000, 512.0)] { + let (seen, grid) = herd(n, side); + let time = |f: &dyn Fn(&Seen, Aabb) -> usize| { + let t = std::time::Instant::now(); + let mut found = 0; + for me in &seen { + found += f(me, me.bounds.inflate(Vec3::new(16.0, 16.0, 16.0))); + } + (t.elapsed().as_secs_f64() * 1e3 / 20.0, found) + }; + let (before, a) = time(&|me, area| scan(&seen, me, area).len()); + let (after, b) = time(&|me, area| indexed(&seen, &grid, me, area).len()); + assert_eq!(a, b); + println!("{n} mobs: per tick {before:.3} ms -> {after:.3} ms"); + } + } +} +#[cfg(test)] mod push_tests { use super::*; use horizon_core::geometry::Vec3; diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 34276ddda..ae4aa91a6 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -1240,10 +1240,10 @@ pub fn walk_target_value(m: &Mob, w: &MobWorld, p: [i32; 3]) -> f32 { 0.0 }; } - // AbstractNautilus and Creaking.getWalkTargetValue: everywhere alike. + // AbstractNautilus, Axolotl and Creaking.getWalkTargetValue: everywhere alike. if matches!( m.species(), - Species::Nautilus | Species::ZombieNautilus | Species::Creaking + Species::Nautilus | Species::ZombieNautilus | Species::Axolotl | Species::Creaking ) { return 0.0; } @@ -1406,6 +1406,12 @@ pub fn do_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) { if super::creaking::is_creaking(m) { m.voice("entity.creaking.attack", cx.events); } + // Axolotl.playAttackSound: playSound(AXOLOTL_ATTACK, 1.0, 1.0). + if m.species() == Species::Axolotl { + let at = [m.position.x, m.position.y, m.position.z]; + cx.events + .push(MobEvent::Sound("entity.axolotl.attack", at, 1.0, 1.0)); + } let _ = Fluid::None; } /// Mob.ate (sheep regrow wool, babies grow). diff --git a/crates/horizon-client/src/mobs/animal_brain.rs b/crates/horizon-client/src/mobs/animal_brain.rs index 9920235a9..331870b4a 100644 --- a/crates/horizon-client/src/mobs/animal_brain.rs +++ b/crates/horizon-client/src/mobs/animal_brain.rs @@ -606,7 +606,7 @@ fn sense_living(m: &mut Mob, w: &MobWorld) { let r = m.attrs.follow_range; let area = m.bounds().inflate(Vec3::new(r, r, r)); let mut found: Vec<(Who, f64)> = Vec::new(); - for o in w.others { + for o in w.others_near(area) { if o.id != m.id && o.alive && o.bounds.intersects(area) { found.push((Who::Mob(o.id), m.distance_sqr(o.position))); } diff --git a/crates/horizon-client/src/mobs/aquatic.rs b/crates/horizon-client/src/mobs/aquatic.rs index 702e3740d..dc80c6ea4 100644 --- a/crates/horizon-client/src/mobs/aquatic.rs +++ b/crates/horizon-client/src/mobs/aquatic.rs @@ -46,6 +46,9 @@ pub fn register(m: &mut Mob) { }; m.ai.look.kind = super::control::LookKind::SmoothSwimming(20.0); m.ai.nav.kind = NavKind::Amphibious; + // `Axolotl()`: water costs nothing, so swim targets in water pass + // DefaultRandomPos's malus check. + m.set_malus(super::path::PathType::Water, 0.0); super::animal_brain::init(m, i64::from(m.id)); } S::Tadpole => { @@ -438,7 +441,7 @@ impl Goal for PufferfishPuff { .as_ref() .is_some_and(|p| p.alive && !p.creative && area.intersects(p.bounds)); // TARGETING_CONDITIONS: not other fish (not_scary_for_pufferfish) and alive. - let mob = cx.w.others.iter().any(|s| { + let mob = cx.w.others_near(area).any(|s| { s.id != m.id && s.alive && !matches!( diff --git a/crates/horizon-client/src/mobs/enderman.rs b/crates/horizon-client/src/mobs/enderman.rs index 13e6c8a44..fcfba832e 100644 --- a/crates/horizon-client/src/mobs/enderman.rs +++ b/crates/horizon-client/src/mobs/enderman.rs @@ -391,12 +391,11 @@ impl Goal for LeaveBlock { let target = cx.w.world.block(x, y, z); let below = cx.w.world.block(x, y - 1, z); let bf = cx.w.facts.get(below); - let free = !cx.w.others.iter().any(|s| { - s.bounds.intersects(Aabb::new( - Vec3::new(f64::from(x), f64::from(y), f64::from(z)), - Vec3::new(f64::from(x + 1), f64::from(y + 1), f64::from(z + 1)), - )) - }); + let block = Aabb::new( + Vec3::new(f64::from(x), f64::from(y), f64::from(z)), + Vec3::new(f64::from(x + 1), f64::from(y + 1), f64::from(z + 1)), + ); + let free = !cx.w.others_near(block).any(|s| s.bounds.intersects(block)); if cx.w.facts.is_air(target) && !cx.w.facts.is_air(below) && &*bf.name != "minecraft:bedrock" diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index 9419a23ba..c12f9e7ee 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -1,7 +1,11 @@ //! Vanilla's `GoalSelector` (priorities, MOVE/LOOK/JUMP/TARGET control flags, //! interruption) and the shared goals of `net.minecraft.world.entity.ai.goal`. use super::{Mob, MobEvent, MobWorld, Seen, Species, Who, world::TargetInfo}; -use horizon_core::{geometry::Vec3, jmath, random::RandomSource}; +use horizon_core::{ + geometry::{Aabb, Vec3}, + jmath, + random::RandomSource, +}; use std::sync::Arc; pub const MOVE: u8 = 1; @@ -970,8 +974,7 @@ impl Goal for LookAtPlayer { let (id, only) = (m.id, self.only); let at = Vec3::new(m.position.x, m.eye_y(), m.position.z); let candidates: Vec<(u32, Vec3)> = - cx.w.others - .iter() + cx.w.others_near(area) .filter(|s| s.id != id && s.alive && s.bounds.intersects(area)) .filter(|s| only.is_none_or(|o| s.species == o)) .map(|s| (s.id, s.position)) @@ -1902,7 +1905,12 @@ impl Goal for FollowParent { let species = m.species(); let pos = m.position; let mut best: Option<(u32, f64)> = None; - for s in cx.w.others.iter().filter(|s| { + // Every position in range puts the box's bottom face in this area. + let area = Aabb::new( + Vec3::new(pos.x - 9.0, pos.y - 5.0, pos.z - 9.0), + Vec3::new(pos.x + 9.0, pos.y + 5.0, pos.z + 9.0), + ); + for s in cx.w.others_near(area).filter(|s| { s.alive && s.species == species && !s.baby diff --git a/crates/horizon-client/src/mobs/golem.rs b/crates/horizon-client/src/mobs/golem.rs index d4d67660b..c41c34f11 100644 --- a/crates/horizon-client/src/mobs/golem.rs +++ b/crates/horizon-client/src/mobs/golem.rs @@ -68,7 +68,10 @@ impl Goal for DefendVillage { if !b.intersects(p.bounds) || m.position.distance_squared(p.position) > 64.0 * 64.0 { return false; } - let bad = cx.w.others.iter().any(|s| { + // A position inside `b` puts the box's bottom face there (one block + // wider, as the box test is strict). + let near = b.inflate(Vec3::new(1.0, 1.0, 1.0)); + let bad = cx.w.others_near(near).any(|s| { s.species == Species::Villager && s.alive && s.player_rep <= -100 diff --git a/crates/horizon-client/src/mobs/monster_brain.rs b/crates/horizon-client/src/mobs/monster_brain.rs index 238653dad..eeb2c42f2 100644 --- a/crates/horizon-client/src/mobs/monster_brain.rs +++ b/crates/horizon-client/src/mobs/monster_brain.rs @@ -299,7 +299,7 @@ fn sense_living(m: &mut Mob, w: &MobWorld) { let r = m.attrs.follow_range; let area = m.bounds().inflate(Vec3::new(r, r, r)); let mut found: Vec<(Who, f64)> = Vec::new(); - for o in w.others { + for o in w.others_near(area) { if o.id != m.id && o.alive && o.bounds.intersects(area) { found.push((Who::Mob(o.id), m.distance_sqr(o.position))); } diff --git a/crates/horizon-client/src/mobs/ravager.rs b/crates/horizon-client/src/mobs/ravager.rs index ef71b8f77..49bac4d9f 100644 --- a/crates/horizon-client/src/mobs/ravager.rs +++ b/crates/horizon-client/src/mobs/ravager.rs @@ -177,7 +177,7 @@ fn roar(m: &mut Mob, w: &MobWorld, events: &mut Vec) { velocity: fling(p.position), }); } - for s in w.others.iter() { + for s in w.others_near(area) { if s.id == m.id || !s.alive || s.species == Species::Ravager || !s.bounds.intersects(area) { continue; } diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index a0dce0e08..4248f22c6 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -749,7 +749,8 @@ pub fn base_transform_at(m: &Mob, alpha: f32, origin: glam::Mat4) -> glam::Mat4 let ticks = (m.age as f32 + alpha).floor(); body += (f64::from(ticks * 3.25).cos() * std::f64::consts::PI * 0.4) as f32; } - let sleep = (m.species() == Species::Villager) + // A sleeping villager, or another player lying in their bed. + let sleep = (m.species() == Species::Villager || m.kind.id == "minecraft:player") .then(|| super::villager::sleep_pose(m)) .flatten(); let rotation = match sleep { @@ -770,6 +771,11 @@ pub fn base_transform_at(m: &Mob, alpha: f32, origin: glam::Mat4) -> glam::Mat4 .sqrt() .min(1.0); base *= glam::Mat4::from_rotation_z(f * flip_degrees(m).to_radians()); + } else if m.extra.auto_spin_attack { + // Riptide: lying along the look direction, spinning 75 degrees a tick. + let pitch = m.previous_head_pitch + (m.head_pitch - m.previous_head_pitch) * alpha; + base *= glam::Mat4::from_rotation_x((-90.0 - pitch).to_radians()) + * glam::Mat4::from_rotation_y(((m.age as f32 + alpha) * -75.0).to_radians()); } else if matches!(m.custom_name.as_deref(), Some("Dinnerbone" | "Grumm")) { // isEntityUpsideDown base *= glam::Mat4::from_translation(glam::Vec3::new(0.0, m.height() + 0.1, 0.0)) @@ -780,7 +786,9 @@ pub fn base_transform_at(m: &Mob, alpha: f32, origin: glam::Mat4) -> glam::Mat4 let ticks = m.extra.fall_fly_ticks as f32 + alpha; let scale = (ticks * ticks / 100.0).min(1.0); let pitch = m.previous_head_pitch + (m.head_pitch - m.previous_head_pitch) * alpha; - base *= glam::Mat4::from_rotation_x((scale * (-90.0 - pitch)).to_radians()); + if !m.extra.auto_spin_attack { + base *= glam::Mat4::from_rotation_x((scale * (-90.0 - pitch)).to_radians()); + } let yaw = m.previous_head_yaw + wrap(m.head_yaw - m.previous_head_yaw) * alpha; let (look_x, look_z) = (-(yaw.to_radians()).msin(), (yaw.to_radians()).mcos()); let v = m.velocity; diff --git a/crates/horizon-client/src/mobs/spawn_selection.rs b/crates/horizon-client/src/mobs/spawn_selection.rs index c87c3d97a..614a2b2b5 100644 --- a/crates/horizon-client/src/mobs/spawn_selection.rs +++ b/crates/horizon-client/src/mobs/spawn_selection.rs @@ -691,33 +691,37 @@ pub struct StructureAt { } /// `NetherFortressStructure.FORTRESS_ENEMIES`. -pub fn fortress_enemies() -> Vec { - let e = |entity: &str, weight, min, max, constant| SpawnEntry { - entity: entity.to_owned(), - weight, - min, - max, - constant, - }; - vec![ - e("minecraft:blaze", 10, 2, 3, false), - e("minecraft:zombified_piglin", 5, 4, 4, true), - e("minecraft:wither_skeleton", 8, 5, 5, true), - e("minecraft:skeleton", 2, 5, 5, true), - e("minecraft:magma_cube", 3, 4, 4, true), - ] +pub fn fortress_enemies() -> &'static [SpawnEntry] { + static ENEMIES: std::sync::LazyLock> = std::sync::LazyLock::new(|| { + let e = |entity: &str, weight, min, max, constant| SpawnEntry { + entity: entity.to_owned(), + weight, + min, + max, + constant, + }; + vec![ + e("minecraft:blaze", 10, 2, 3, false), + e("minecraft:zombified_piglin", 5, 4, 4, true), + e("minecraft:wither_skeleton", 8, 5, 5, true), + e("minecraft:skeleton", 2, 5, 5, true), + e("minecraft:magma_cube", 3, 4, 4, true), + ] + }); + &ENEMIES } /// `NaturalSpawner.mobsAt`: the fortress bounds on nether bricks, then /// `ChunkGenerator.getMobsAt` (the first referenced structure whose override -/// for the category holds the position), else the biome's list. +/// for the category holds the position), else the biome's list. Borrowed from +/// the level: a spawn attempt looks it up up to twice. pub fn mobs_at( l: &L, category: Category, x: i32, y: i32, z: i32, -) -> Vec { +) -> &[SpawnEntry] { // Only a fortress or a structure overriding this category's spawns can // change the list, so only theirs are looked up (the references reaching // most chunks are mineshafts, which override nothing). @@ -738,13 +742,12 @@ pub fn mobs_at( if let Some(o) = overrides.get(&s.id, category.name()) && (if o.piece { s.in_piece } else { s.in_bounds }) { - return o.spawns.clone(); + return &o.spawns; } } l.biome_spawns(x, y, z) .and_then(|b| b.get(category.name())) - .cloned() - .unwrap_or_default() + .map_or(&[], Vec::as_slice) } /// `WeightedList.getRandom`. @@ -1103,7 +1106,7 @@ pub fn spawn_category_for_position( { None } else { - weighted_pick(&mobs_at(l, category, x, y, z), random) + weighted_pick(mobs_at(l, category, x, y, z), random) }; let Some(entry) = list else { break; diff --git a/crates/horizon-client/src/mobs/villager.rs b/crates/horizon-client/src/mobs/villager.rs index f568cb47b..84c607933 100644 --- a/crates/horizon-client/src/mobs/villager.rs +++ b/crates/horizon-client/src/mobs/villager.rs @@ -98,12 +98,7 @@ pub fn start_sleeping(m: &mut Mob, p: [i32; 3], w: &MobWorld) -> bool { if w.prop(p[0], p[1], p[2], "occupied") == Some("true") { return false; } - m.extra.ints[1] = match w.prop(p[0], p[1], p[2], "facing") { - Some("north") => 1, - Some("south") => 2, - Some("west") => 3, - _ => 4, - }; + m.extra.ints[1] = bed_facing_code(w.prop(p[0], p[1], p[2], "facing")); m.nav_stop(); ext_mut(m).last_slept = Some(w.game_time); m.velocity = horizon_core::geometry::Vec3::ZERO; @@ -144,6 +139,15 @@ pub fn stop_sleeping(m: &mut Mob, w: &MobWorld) { } /// `LivingEntityRenderer.sleepDirectionToRotation` and the bed's direction /// (the body is shifted back from the pillow by the standing eye height). +/// A bed's `facing` as `sleep_pose` keeps it in `ints[1]`. +pub fn bed_facing_code(facing: Option<&str>) -> i32 { + match facing { + Some("north") => 1, + Some("south") => 2, + Some("west") => 3, + _ => 4, + } +} pub fn sleep_pose(m: &Mob) -> Option<(f32, [f32; 2])> { Some(match m.extra.ints[1] { 1 => (270.0, [0.0, -1.0]), diff --git a/crates/horizon-client/src/mobs/villager_brain.rs b/crates/horizon-client/src/mobs/villager_brain.rs index 5b8500c0d..e02cfa176 100644 --- a/crates/horizon-client/src/mobs/villager_brain.rs +++ b/crates/horizon-client/src/mobs/villager_brain.rs @@ -568,7 +568,7 @@ fn sense_living(m: &mut Mob, w: &MobWorld) { let r = m.attrs.follow_range; let area = m.bounds().inflate(Vec3::new(r, r, r)); let mut found: Vec<(Who, f64)> = Vec::new(); - for o in w.others { + for o in w.others_near(area) { if o.id != m.id && o.alive && o.bounds.intersects(area) { found.push((Who::Mob(o.id), m.distance_sqr(o.position))); } @@ -898,8 +898,9 @@ fn poi_matches(m: &Mob, f: PoiFilter, p: Poi) -> bool { _ => false, } } -/// Tickets taken on a POI: by this villager's memories and by others'. -fn tickets(m: &Mob, w: &MobWorld, p: [i32; 3]) -> usize { +/// Tickets taken on a POI: by this villager's memories and by others' +/// (counted once per search by [`others_tickets`]). +fn tickets(m: &Mob, others: &crate::fast_hash::FxHashMap<[i32; 3], usize>, p: [i32; 3]) -> usize { let mut n = 0; if let Some(mm) = mem_ref(m) { for s in [ @@ -913,16 +914,22 @@ fn tickets(m: &Mob, w: &MobWorld, p: [i32; 3]) -> usize { } } } + n + others.get(&p).copied().unwrap_or(0) +} +/// The tickets the other living villagers' POIs take, by POI. +fn others_tickets(m: &Mob, w: &MobWorld) -> crate::fast_hash::FxHashMap<[i32; 3], usize> { + let mut taken = crate::fast_hash::FxHashMap::default(); for o in w.others { if o.id != m.id && o.alive && o.species == Species::Villager { - for q in [o.job, o.bed, o.potential_job, o.meeting] { - if q == Some(p) { - n += 1; - } + for q in [o.job, o.bed, o.potential_job, o.meeting] + .into_iter() + .flatten() + { + *taken.entry(q).or_insert(0) += 1; } } } - n + taken } /// The POIs of chunk `(qx, qz)` from `y0` to `y1` (within the world), in /// scan order: y, then z, then x. Only the indexed POI blocks of the sections @@ -962,6 +969,8 @@ fn pois_in_range( ) -> Vec<(Poi, [i32; 3])> { let c = block_of(m.position); let mut found = Vec::new(); + // Every candidate asks how taken it is: count the others' once. + let mut taken = None; let r2 = i64::from(radius) * i64::from(radius); let (cx, cz) = (c[0] >> 4, c[2] >> 4); let chunks = radius.div_euclid(16) + 1; @@ -974,7 +983,8 @@ fn pois_in_range( || (p[2] - c[2]).abs() > radius || dist_sqr(p, c) > r2 || !poi_matches(m, f, poi) - || tickets(m, w, p) >= poi.max_tickets() + || tickets(m, taken.get_or_insert_with(|| others_tickets(m, w)), p) + >= poi.max_tickets() { return; } diff --git a/crates/horizon-client/src/mobs/warden_brain.rs b/crates/horizon-client/src/mobs/warden_brain.rs index 41353fc83..518347e77 100644 --- a/crates/horizon-client/src/mobs/warden_brain.rs +++ b/crates/horizon-client/src/mobs/warden_brain.rs @@ -492,7 +492,7 @@ fn sense_entities(m: &mut Mob, w: &MobWorld) { let r = m.attrs.follow_range; let area = m.bounds().inflate(Vec3::new(r, r, r)); let mut found: Vec<(Who, f64)> = Vec::new(); - for o in w.others { + for o in w.others_near(area) { if o.id != m.id && o.alive && o.bounds.intersects(area) { found.push((Who::Mob(o.id), m.distance_sqr(o.position))); } diff --git a/crates/horizon-client/src/mobs/world.rs b/crates/horizon-client/src/mobs/world.rs index cc4110dd7..79bbaa30c 100644 --- a/crates/horizon-client/src/mobs/world.rs +++ b/crates/horizon-client/src/mobs/world.rs @@ -226,7 +226,13 @@ impl MobWorld<'_> { .chain(all.into_iter().flatten()) } pub fn seen(&self, id: u32) -> Option<&Seen> { - self.others.iter().find(|s| s.id == id) + match self.others_index { + Some(index) => index + .get(&id) + .and_then(|&i| self.others.get(i as usize)) + .filter(|s| s.id == id), + None => self.others.iter().find(|s| s.id == id), + } } /// Living mobs of the given species within `range` of `from`, nearest first. pub fn nearby<'s>( @@ -235,9 +241,15 @@ impl MobWorld<'_> { range: f64, pred: impl Fn(&Seen) -> bool + 's, ) -> impl Iterator + 's { + // A position within `range` puts the box's bottom face in this area + // (one block wider, as the box test is strict). + let r = range + 1.0; + let area = Aabb::new( + Vec3::new(from.x - r, from.y - r, from.z - r), + Vec3::new(from.x + r, from.y + r, from.z + r), + ); let mut v: Vec<&Seen> = self - .others - .iter() + .others_near(area) .filter(|s| { s.alive && (s.position.x - from.x).abs() <= range diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index a2fbd47ba..b1088188c 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -247,6 +247,14 @@ pub struct PlayerMotion { pub glide_ending: bool, /// Glider durability to take this tick (updateFallFlying). pub glider_wear: u32, + /// `LivingEntity.autoSpinAttackTicks` and `autoSpinAttackDmg`: Riptide's + /// spin. The damage stays until the game has dealt the hit. + pub auto_spin_attack_ticks: i32, + pub auto_spin_attack_dmg: f32, + /// The living entities the game put near a spinning player (id, box). + pub spin_targets: Vec<(u32, Aabb)>, + /// The entity the spin touched this tick (`doAutoAttackOnTouch`). + pub spin_hit: Option, pub sprinting: bool, pub sprint_input: crate::sprint::SprintState, pub shift_key_down: bool, @@ -262,6 +270,10 @@ pub struct PlayerMotion { pub steps: MovementDistances, pub needs_sync: bool, pub sync_position: bool, + /// Moved by an ender pearl (`ServerPlayer.teleport`): a server sends the + /// position packet even when the player lands where they stood. The + /// server takes it at the end of a guest's turn. + pub teleported: bool, pub events: Vec, pub attributes: LiveAttributes i32>>, pub impulse: ImpulseContext, @@ -290,6 +302,11 @@ pub struct PlayerMotion { /// The powder snow blocks this tick's movement went into: the game /// destroys them if the player is burning, then puts the fire out. pub powder_snow_entered: Vec, + /// The last hurts taken (`hurt_blocking`), newest last, for tests and + /// the control socket's `hurtlog`. + pub hurt_log: Vec, + /// The last melee attacks made on mobs, newest last. + pub attack_log: Vec, } fn attribute_error(error: impl std::fmt::Debug) -> io::Error { io::Error::other(format!("movement attribute: {error:?}")) @@ -404,6 +421,10 @@ impl PlayerMotion { fall_fly_ticks: 0, glide_ending: false, glider_wear: 0, + auto_spin_attack_ticks: 0, + auto_spin_attack_dmg: 0.0, + spin_targets: Vec::new(), + spin_hit: None, sprinting: false, sprint_input: crate::sprint::SprintState::default(), shift_key_down: false, @@ -423,6 +444,7 @@ impl PlayerMotion { }, needs_sync: false, sync_position: false, + teleported: false, events: Vec::new(), attributes, fluids: PlayerFluids::default(), @@ -434,6 +456,8 @@ impl PlayerMotion { old_position: position, block_effects: true, powder_snow_entered: Vec::new(), + hurt_log: Vec::new(), + attack_log: Vec::new(), }) } /// `Entity.getTicksRequiredToFreeze`. @@ -912,6 +936,7 @@ impl MotionWorld<'_, '_, '_> { input.z = 0.0; } self.jump_phase()?; + let before_travel = self.player.bounds(); // Player.travel: swim steering, then LivingEntity.travel (fluids // first, then gliding, then air), keeping 0.6 of the vertical speed // while flying. @@ -966,8 +991,26 @@ impl MotionWorld<'_, '_, '_> { { self.freeze_damage()?; } + if self.player.auto_spin_attack_ticks > 0 { + self.player.auto_spin_attack_ticks -= 1; + self.check_auto_spin_attack(before_travel); + } Ok(()) } + /// `LivingEntity.checkAutoSpinAttack`: the first living entity in the + /// box swept this tick takes the hit and ends the spin, bouncing the + /// player back at a fifth of its speed; a wall ends it too. + fn check_auto_spin_attack(&mut self, before: Aabb) { + let swept = before.union_bounds(self.player.bounds()); + let p = &mut self.player; + if let Some(&(id, _)) = p.spin_targets.iter().find(|(_, b)| b.intersects(swept)) { + p.spin_hit = Some(id); + p.auto_spin_attack_ticks = 0; + p.velocity = p.velocity.scale(-0.2); + } else if p.collision.horizontal { + p.auto_spin_attack_ticks = 0; + } + } /// `hurtServer(damageSources().freeze(), 1)` for a fully frozen player. fn freeze_damage(&mut self) -> Result<()> { let id = self @@ -2145,6 +2188,68 @@ mod tests { assert!(player.position.y < 84.0); } + /// `MovingPistonBlock.getCollisionShape`: a block halfway through a push + /// up is solid at its moving position, so a player lands on it. + #[test] + fn a_player_lands_on_a_block_a_piston_is_moving() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION); + if !root.join("movement-properties.nbt").exists() { + return; + } + let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); + let binding = crate::collisions::load(&root, assets.registry).unwrap(); + let resources = MotionResources::load(&root, &assets).unwrap(); + let mut scene = World::test_scene(&assets, &render, 1).unwrap(); + let registry = assets.registry; + let moving = registry.default_state("minecraft:moving_piston").unwrap(); + let stone = registry.default_state("minecraft:stone").unwrap(); + scene.set(20, 4, 20, moving).unwrap(); + scene.moving_pistons.push(( + [20, 4, 20], + horizon_world::piston_shape::MovingPistonState { + moved_state: stone, + direction: horizon_core::geometry::Direction::Up, + extending: true, + source: false, + progress: 0.5, + previous_progress: 0.0, + }, + )); + let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 6.0, 20.5)).unwrap(); + for _ in 0..30 { + MotionWorld { + entities: &[], + player: &mut player, + scene: &mut scene, + assets: &assets, + collision_binding: &binding, + resources: &resources, + } + .controlled_simulation_tick(Default::default()) + .unwrap(); + } + assert!(player.ground.on_ground); + assert_eq!(player.position.y, 4.5); + // Once the block entity is gone, the moving_piston block has no shape. + scene.moving_pistons.clear(); + for _ in 0..10 { + MotionWorld { + entities: &[], + player: &mut player, + scene: &mut scene, + assets: &assets, + collision_binding: &binding, + resources: &resources, + } + .controlled_simulation_tick(Default::default()) + .unwrap(); + } + assert_eq!(player.position.y, 4.0); + } + #[test] fn spectator_scroll_speed_controls_horizontal_and_vertical_flight() { let root = Path::new(env!("CARGO_MANIFEST_DIR")) @@ -2590,6 +2695,49 @@ mod tests { } } #[test] + fn a_riptide_spin_lies_flat_and_ends_on_the_first_entity_it_touches() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION); + if !root.join("movement-properties.nbt").exists() { + return; + } + let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); + let binding = crate::collisions::load(&root, assets.registry).unwrap(); + let resources = MotionResources::load(&root, &assets).unwrap(); + let mut scene = World::test_scene(&assets, &render, 2).unwrap(); + let ahead = Aabb::new(Vec3::new(20.2, 9.0, 21.5), Vec3::new(20.8, 11.0, 22.1)); + for target in [None, Some(ahead)] { + let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 10.0, 20.5)).unwrap(); + player.auto_spin_attack_ticks = 20; + player.auto_spin_attack_dmg = 8.0; + player.velocity = Vec3::new(0.0, 0.0, 1.0); + player.spin_targets = target.map(|b| (7, b)).into_iter().collect(); + let mut w = MotionWorld { + entities: &[], + player: &mut player, + scene: &mut scene, + assets: &assets, + collision_binding: &binding, + resources: &resources, + }; + w.simulation_tick([0.0, 0.0], false).unwrap(); + if target.is_some() { + // Touched: the hit, no more spin, bounced back at a fifth. + assert_eq!(w.player.spin_hit, Some(7)); + assert_eq!(w.player.auto_spin_attack_ticks, 0); + assert!(w.player.velocity.z < 0.0, "{:?}", w.player.velocity); + assert_eq!(w.player.pose, crate::pose::Pose::Standing); + } else { + assert_eq!(w.player.spin_hit, None); + assert_eq!(w.player.auto_spin_attack_ticks, 19); + assert_eq!(w.player.pose, crate::pose::Pose::SpinAttack); + assert_eq!(w.player.dimensions.height, 0.6); + } + } + } + #[test] fn a_landing_glide_lasts_a_tick_so_a_jump_keeps_its_speed() { let root = Path::new(env!("CARGO_MANIFEST_DIR")) .join("../../.local/horizon-client") diff --git a/crates/horizon-client/src/options_horizon.rs b/crates/horizon-client/src/options_horizon.rs index 75458ae40..50a42f337 100644 --- a/crates/horizon-client/src/options_horizon.rs +++ b/crates/horizon-client/src/options_horizon.rs @@ -38,7 +38,14 @@ pub enum HRow { Mod(usize), /// Opens the directory where Horizon mods are installed. OpenModFolder, + /// `shaderpacks/`'s path and a button opening it. + ShaderPackFolder, + /// Shader pack `i` of `OptionsUi::shader_packs` and its switch. + ShaderPack(usize), } + +/// The sidebar section listing the shader packs. +pub const SHADER_PACKS: &str = "Shader Packs"; /// A sidebar section: name, description, rows. pub struct Section { pub name: &'static str, @@ -172,6 +179,12 @@ pub const SECTIONS: &[Section] = &[ .to_vec() }, }, + Section { + name: SHADER_PACKS, + blurb: "Packs that redraw the world. Off is the vanilla look.", + // The packs follow, from the folder (`horizon_rows`). + rows: |_| vec![HRow::ShaderPackFolder], + }, Section { name: "Interface", blurb: "Menus and resource packs.", @@ -309,7 +322,15 @@ fn horizon_batch(framebuffer: [i32; 2]) -> HudBatch { } impl OptionsUi { fn horizon_rows(&self, s: &Settings, section: usize) -> Vec { - let rows = (SECTIONS[section].rows)(s); + let mut rows = (SECTIONS[section].rows)(s); + if SECTIONS[section].name == SHADER_PACKS { + if self.shader_packs.packs.is_empty() { + rows.push(HRow::Header( + "No shader packs: put a pack's folder or .zip in this folder", + )); + } + rows.extend((0..self.shader_packs.packs.len()).map(HRow::ShaderPack)); + } let query = self.settings_search.value.to_lowercase(); if query.is_empty() || !searchable_section(section) { return rows; @@ -511,6 +532,38 @@ impl OptionsUi { ui.described_row(x, y, &installed.title, "", 0.0, cost, text, cw - 60.0); ui.switch(ROW + i as u64, control_x, y + ROW_H / 2.0, s.mods.is_on(m)); } + HRow::ShaderPackFolder => { + let label = "Open Folder"; + let bw = ui.button_width(label, false).max(96.0); + let dir = self.shader_packs.dir.display().to_string(); + ui.described_row(x, y, "Folder", "", 0.0, (0, ""), &dir, cw - bw - 24.0); + ui.button( + ROW + i as u64, + [control_x - bw, y + 12.0, bw, CONTROL], + label, + Button::Secondary, + true, + ); + } + HRow::ShaderPack(p) => { + let (id, info) = &self.shader_packs.packs[p]; + let error = match info { + Err(e) => Some(e.as_str()), + Ok(_) => self + .shader_pack_error + .as_ref() + .filter(|(failed, _)| failed == id) + .map(|(_, e)| e.as_str()), + }; + let (cost, text) = match (error, info) { + (Some(e), _) => ((3, "Failed"), e), + (None, Ok(info)) => ((0, ""), info.description.as_str()), + (None, Err(_)) => unreachable!(), + }; + ui.described_row(x, y, id, "", 0.0, cost, text, cw - 60.0); + let on = s.horizon.shader_pack == *id; + ui.switch(ROW + i as u64, control_x, y + ROW_H / 2.0, on); + } HRow::OpenModFolder => { ui.row(x, y, "Mod folder", "", 0.0); let label = "Open Folder"; @@ -756,13 +809,7 @@ impl OptionsUi { return events; } match target { - Some(Target::Nav(i)) => { - if searchable_section(self.section) || searchable_section(i) { - self.settings_search.set_value(""); - } - self.section = i; - self.hscroll = 0.0; - } + Some(Target::Nav(i)) => self.select_section(i), Some(Target::Search) => { self.settings_search.focused = true; self.settings_search.move_cursor_to_end(false); @@ -798,6 +845,10 @@ impl OptionsUi { } events.push(Event::Changed); } + Some(HRow::Graphics(Item::Horizon(graphics_ui::H::ShaderPack), ..)) => { + events.push(Event::ButtonClick); + self.open_section(SHADER_PACKS); + } Some(HRow::Graphics(item, ..)) => { item.cycle(s, right, framebuffer); events.push(Event::Changed); @@ -818,6 +869,14 @@ impl OptionsUi { events.push(Event::ButtonClick); events.push(Event::OpenModFolder); } + Some(HRow::ShaderPackFolder) if !right => { + events.push(Event::ButtonClick); + events.push(Event::OpenShaderPackFolder); + } + Some(HRow::ShaderPack(p)) => { + self.toggle_shader_pack(s, *p); + events.push(Event::Changed); + } _ => {} } } @@ -825,6 +884,19 @@ impl OptionsUi { } events } + fn select_section(&mut self, i: usize) { + if searchable_section(self.section) || searchable_section(i) { + self.settings_search.set_value(""); + } + self.section = i; + self.hscroll = 0.0; + } + /// Show the sidebar section called `name`. + fn open_section(&mut self, name: &str) { + if let Some(i) = SECTIONS.iter().position(|s| s.name == name) { + self.select_section(i); + } + } pub(crate) fn scroll_horizon(&mut self, amount: f32) { self.hscroll -= amount * 40.0; } @@ -1057,6 +1129,85 @@ mod tests { assert_eq!(ui.hscroll, 0.0); } + /// The Shader Packs section: the folder's path and Open Folder, a switch + /// per pack; the Video section's Shader Pack row leads here (#941, #925). + #[test] + fn shader_packs_section_opens_the_folder_and_picks_a_pack() { + let atlas = atlas(); + let framebuffer = [2560, 1440]; + let dir = + std::env::temp_dir().join(format!("horizon-shader-section-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut options = section_ui(SHADER_PACKS); + let mut settings = Settings::default(); + options.shader_packs.poll(dir.clone()); + assert!(matches!( + options.horizon_rows(&settings, options.section)[..], + [HRow::ShaderPackFolder, HRow::Header(_)] + )); + std::fs::write(dir.join("Pack.zip"), b"").unwrap(); + options.shader_packs = Default::default(); + options.shader_packs.poll(dir.clone()); + // Click the control with hit id `id`, scrolling until it shows. + let click = |options: &mut OptionsUi, settings: &mut Settings, id: u64| { + for _ in 0..40 { + let mut batch = horizon_batch(framebuffer); + let mut ui = Ui::dry(&atlas, &mut batch, (0.0, 0.0)); + options.horizon_layout(settings, &mut ui, 1.0); + if let Some(hit) = ui.hits.iter().find(|hit| hit.id == id) { + let r = hit.rect; + let scale = ui.density / ui.batch.scale; + let at = ((r[0] + r[2]) * 0.5 * scale, (r[1] + r[3]) * 0.5 * scale); + drop(ui); + return options.click_horizon( + settings, + &atlas, + at.0, + at.1, + framebuffer, + false, + false, + ); + } + drop(ui); + options.hscroll += 200.0; + } + panic!("no control {id}"); + }; + assert_eq!( + click(&mut options, &mut settings, ROW), + [Event::ButtonClick, Event::OpenShaderPackFolder] + ); + assert_eq!( + click(&mut options, &mut settings, ROW + 1), + [Event::Changed] + ); + assert_eq!(settings.horizon.shader_pack, "Pack.zip"); + click(&mut options, &mut settings, ROW + 1); + assert_eq!(settings.horizon.shader_pack, ""); + + let mut options = section_ui("Video"); + settings.horizon.advanced = true; + let video = SECTIONS.iter().position(|s| s.name == "Video").unwrap(); + let row = options + .horizon_rows(&settings, video) + .iter() + .position(|r| { + matches!( + r, + HRow::Graphics(Item::Horizon(graphics_ui::H::ShaderPack), ..) + ) + }) + .unwrap(); + assert_eq!( + click(&mut options, &mut settings, ROW + row as u64), + [Event::ButtonClick] + ); + assert_eq!(SECTIONS[options.section].name, SHADER_PACKS); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn mods_section_opens_folder_from_its_button() { let atlas = atlas(); diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 0ea49cb72..7d86263df 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -862,6 +862,8 @@ pub enum Page { Font, Packs, Mods, + /// The shader packs in `shaderpacks/`: pick one, open the folder. + ShaderPacks, /// Horizon's graphics settings (`graphics_ui`). Graphics, GraphicsAdvanced, @@ -888,6 +890,9 @@ enum Act { HorizonMenus, ToggleMod(usize), OpenModFolder, + /// Pick shader pack `i` of `OptionsUi::shader_packs` (again: off). + ToggleShaderPack(usize), + OpenShaderPackFolder, } enum WKind { Button { @@ -935,6 +940,8 @@ pub enum Event { Packs(Vec), OpenPackFolder, OpenModFolder, + /// Create `shaderpacks/` if needed and open it. + OpenShaderPackFolder, } /// `SliderableValueSet.applyValueImmediately`: these apply 600 ms after /// the last change (`OptionInstanceSliderButton.delayedApplyAt`). @@ -993,6 +1000,10 @@ pub struct OptionsUi { /// Scroll the selected language into the middle on the next layout. center_language: bool, pub graphics: crate::graphics_ui::GraphicsUi, + /// `shaderpacks/` and its packs, read while the Shader Packs page shows. + pub shader_packs: crate::shader_pack::Folder, + /// The pack that failed to load last and why (set by the game). + pub shader_pack_error: Option<(String, String)>, } impl Default for OptionsUi { fn default() -> Self { @@ -1025,6 +1036,8 @@ impl Default for OptionsUi { in_world: false, center_language: false, graphics: Default::default(), + shader_packs: Default::default(), + shader_pack_error: None, } } } @@ -1073,6 +1086,8 @@ enum Row { Big(Opt), Pair(Opt, Option), Header(&'static str), + /// A line of grey text (a path). + Note(String), Buttons(Widget, Option), } fn pairs(opts: &[Opt]) -> Vec { @@ -1131,6 +1146,33 @@ impl OptionsUi { self.graphics.reset(); } } + /// Pick shader pack `i` of the folder, or turn it off when it is the + /// one running. + pub(crate) fn toggle_shader_pack(&self, s: &mut Settings, i: usize) { + let Some((id, Ok(_))) = self.shader_packs.packs.get(i) else { + return; + }; + let g = &mut s.horizon; + g.shader_pack = if g.shader_pack == *id { + String::new() + } else { + id.clone() + }; + } + pub(crate) fn shader_pack_failed(&self, id: &str) -> bool { + self.shader_pack_error + .as_ref() + .is_some_and(|(e, _)| e == id) + } + /// Whether the Shader Packs page (or the Horizon menus' section) shows. + fn shader_packs_shown(&self) -> bool { + self.page() == Page::ShaderPacks + || crate::ui_theme::horizon() + && self.page() == Page::Main + && crate::options_horizon::SECTIONS + .get(self.section) + .is_some_and(|s| s.name == crate::options_horizon::SHADER_PACKS) + } /// The graphics screen level of `page`, if it is one. fn graphics_level(page: Page) -> Option { match page { @@ -1153,6 +1195,7 @@ impl OptionsUi { Page::Font => "options.font.title", Page::Packs => "resourcePack.title", Page::Mods => "Mods", + Page::ShaderPacks => "Shader Packs", Page::Graphics | Page::GraphicsAdvanced => "options.videoTitle", Page::Controller => "Controller Settings", Page::PadBinds => "Controller Binds", @@ -1262,6 +1305,16 @@ impl OptionsUi { Act::Push(Page::GraphicsAdvanced), )), )]; + rows.push(Row::Buttons( + button( + 0.0, + 0.0, + 310.0, + Text::literal("Shader Packs..."), + Act::Push(Page::ShaderPacks), + ), + None, + )); // The way back from Classic menus. Horizon-only like the row // above, here rather than on the main Options screen so that // one keeps vanilla's exact layout; vanilla's interface @@ -1450,6 +1503,32 @@ impl OptionsUi { }) .collect() } + Page::ShaderPacks => { + let folder = &self.shader_packs; + let mut rows = vec![Row::Note(folder.dir.display().to_string())]; + if folder.packs.is_empty() { + rows.push(Row::Header( + "No shader packs: put a pack's folder or .zip in this folder", + )); + } + for (i, (id, info)) in folder.packs.iter().enumerate() { + let on = s.horizon.shader_pack == *id; + let mut label = Text::literal(format!("{id}: ")).append(on_off(on)); + if info.is_err() || self.shader_pack_failed(id) { + label = label.append(" (Failed)"); + } + let widget = button(0.0, 0.0, 310.0, label, Act::ToggleShaderPack(i)); + rows.push(Row::Buttons( + if info.is_ok() { + widget + } else { + inactive(widget) + }, + None, + )); + } + rows + } _ => { let _ = s; Vec::new() @@ -1849,6 +1928,21 @@ impl OptionsUi { }); y += padding + 18.0; } + Row::Note(text) => { + out.push(Widget { + x: 0.0, + y: y + 4.0, + w, + h: 9.0, + kind: WKind::Text { + text: Text::literal(text), + color: 0xFFA0A0A0, + centered: true, + }, + list: false, + }); + y += 16.0; + } Row::Big(opt) => { out.push(option_widget(s, opt, cx - 155.0, y + 2.0, 310.0)); y += 25.0; @@ -1875,13 +1969,20 @@ impl OptionsUi { } content = y + self.scroll - top + 2.0; out[list_start..].iter_mut().for_each(|w| w.list = true); - if page == Page::Mods { + let folder = match page { + Page::Mods => Some(("Open Mod Folder", Act::OpenModFolder)), + Page::ShaderPacks => { + Some(("Open Shader Pack Folder", Act::OpenShaderPackFolder)) + } + _ => None, + }; + if let Some((label, act)) = folder { out.push(button( cx - 154.0, h - 27.0, 150.0, - Text::literal("Open Mod Folder"), - Act::OpenModFolder, + Text::literal(label), + act, )); out.push(button(cx + 4.0, h - 27.0, 150.0, tr("gui.done"), Act::Done)); } else { @@ -1911,6 +2012,9 @@ impl OptionsUi { atlas: &HudAtlas, cursor: (f32, f32), ) { + if self.shader_packs_shown() { + self.shader_packs.poll(crate::shader_pack::folder()); + } let (w, h) = (batch.width, batch.height); if let Some(error) = &self.resource_error { ui::menu_background(batch, atlas, 0.0, 0.0, w, h, self.in_world); @@ -2210,6 +2314,7 @@ impl OptionsUi { Action::ButtonClick => events.push(Event::ButtonClick), Action::Changed => events.push(Event::Changed), Action::OpenAdvanced => self.push(Page::GraphicsAdvanced), + Action::OpenShaderPacks => self.push(Page::ShaderPacks), Action::OpenSimple => { if self.stack.len() >= 2 && self.stack[self.stack.len() - 2] == Page::Graphics @@ -2377,6 +2482,11 @@ impl OptionsUi { events.push(Event::Changed); } Act::OpenModFolder => events.push(Event::OpenModFolder), + Act::ToggleShaderPack(i) => { + self.toggle_shader_pack(s, i); + events.push(Event::Changed); + } + Act::OpenShaderPackFolder => events.push(Event::OpenShaderPackFolder), Act::None => {} } } @@ -2831,6 +2941,109 @@ mod tests { assert!(ui.resource_error.is_none()); } + /// The Shader Packs page (Video Settings > Shader Packs..., or the + /// Shader Pack row of Advanced graphics): the folder's path, Open Shader + /// Pack Folder, and a switch per pack (#941, #925). + #[test] + fn classic_shader_packs_page_shows_the_folder_and_picks_a_pack() { + let atlas = atlas(); + let mut s = Settings::default(); + let mut ui = OptionsUi::default(); + let size = (480.0, 240.0); + let dir = std::env::temp_dir().join(format!("horizon-shaderpacks-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let find = |ui: &mut OptionsUi, s: &Settings, act: &dyn Fn(&Act) -> bool| { + ui.layout(s, size.0, size.1) + .0 + .into_iter() + .find(|w| matches!(&w.kind, WKind::Button { act: a, active: true, .. } if act(a))) + }; + ui.show(Page::Video); + let open = find(&mut ui, &s, &|a| *a == Act::Push(Page::ShaderPacks)).unwrap(); + ui.click( + &mut s, + &atlas, + open.x + 1.0, + open.y + 1.0, + size, + [480, 240], + false, + false, + ); + assert_eq!(ui.page(), Page::ShaderPacks); + + ui.shader_packs.poll(dir.clone()); + let empty = ui.layout(&s, size.0, size.1).0; + let path = dir.display().to_string(); + for line in [path.as_str(), "No shader packs"] { + assert!( + empty.iter().any( + |w| matches!(&w.kind, WKind::Text { text, .. } if text.plain().contains(line)) + ), + "{line}" + ); + } + let folder = find(&mut ui, &s, &|a| *a == Act::OpenShaderPackFolder).unwrap(); + assert_eq!( + ui.click( + &mut s, + &atlas, + folder.x + 1.0, + folder.y + 1.0, + size, + [480, 240], + false, + false + ), + vec![Event::ButtonClick, Event::OpenShaderPackFolder] + ); + + std::fs::write(dir.join("Pack.zip"), b"").unwrap(); + ui.shader_packs = Default::default(); + ui.shader_packs.poll(dir.clone()); + let pack = find(&mut ui, &s, &|a| *a == Act::ToggleShaderPack(0)).unwrap(); + let events = ui.click( + &mut s, + &atlas, + pack.x + 1.0, + pack.y + 1.0, + size, + [480, 240], + false, + false, + ); + assert!(events.contains(&Event::Changed)); + assert_eq!(s.horizon.shader_pack, "Pack.zip"); + ui.shader_pack_error = Some(("Pack.zip".into(), "broken".into())); + let label = |ui: &mut OptionsUi, s: &Settings| match find(ui, s, &|a| { + *a == Act::ToggleShaderPack(0) + }) + .unwrap() + .kind + { + WKind::Button { label, .. } => label.plain(), + _ => unreachable!(), + }; + assert!( + label(&mut ui, &s).ends_with("(Failed)"), + "{}", + label(&mut ui, &s) + ); + ui.click( + &mut s, + &atlas, + pack.x + 1.0, + pack.y + 1.0, + size, + [480, 240], + false, + false, + ); + assert_eq!(s.horizon.shader_pack, "", "a second click turns it off"); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn classic_mods_page_toggles_mods_and_keeps_dev_and_invalid_entries_inactive() { let atlas = atlas(); diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index 29bf5b030..55a7a5120 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -73,6 +73,7 @@ particle_types! { Splash = "splash", Rain = "rain", Bubble = "bubble", + SulfurBubbles = "sulfur_bubbles", BubblePop = "bubble_pop", BubbleColumnUp = "bubble_column_up", CurrentDown = "current_down", @@ -352,6 +353,14 @@ enum Behaviour { }, WaterDrop, Bubble, + /// `SulfurBubbleParticle`: rises three blocks through still water, + /// growing to 0.15. + SulfurBubble { + y_start: f64, + y_end: f64, + size_start: f32, + y_prev: f64, + }, BubblePop, BubbleColumnUp, CurrentDown { @@ -1099,6 +1108,11 @@ impl ParticleLevel<'_> { }; (s.fluid, height) } + /// The fluid at a block and whether it is a source (`FluidState.isSource`). + fn fluid_source(&self, b: [i32; 3]) -> (Fluid, bool) { + let s = self.facts.get(self.world.block(b[0], b[1], b[2])); + (s.fluid, s.fluid_level == 8 && !s.fluid_falling) + } /// `getCollisionShape(...).max(Y, x, z)` for cached shapes. fn collision_top(&self, b: [i32; 3], fx: f64, fz: f64) -> f64 { let state = self.world.block(b[0], b[1], b[2]); @@ -1933,6 +1947,27 @@ impl ParticleEngine { } q } + T::SulfurBubbles => { + let mut q = Particle::at(r, ty, p); + q.gravity = -0.04; + q.friction = 0.85; + q.set_size(0.02, 0.02); + q.velocity[0] = + v[0] * f64::from(0.2f32) + f64::from((r.next_float() * 2.0 - 1.0) * 0.02); + // The provider passes `yAux` as `za`, so the Z speed comes from Y. + q.velocity[2] = + v[1] * f64::from(0.2f32) + f64::from((r.next_float() * 2.0 - 1.0) * 0.02); + let size_start = 0.02 + 0.02 * r.next_float(); + q.size = size_start; + q.lifetime = i32::MAX; + q.behaviour = Behaviour::SulfurBubble { + y_start: p[1], + y_end: p[1] + 4.0 - 1.0, + size_start, + y_prev: p[1], + }; + q + } T::BubblePop => { let mut q = Particle::at(r, ty, p); q.lifetime = 4; @@ -3172,6 +3207,40 @@ impl ParticleEngine { p.removed = true; } } + Behaviour::SulfurBubble { + y_start, + y_end, + size_start, + y_prev, + } => { + p.base_tick(level); + let (fluid, source) = level.fluid_source(ParticleLevel::block_at(p.position)); + if !p.removed && !(fluid == Fluid::Water && source) { + p.removed = true; + } + if !p.removed && p.position[1] >= y_end { + p.removed = true; + } + if !p.removed && p.position[1] <= y_prev { + p.removed = true; + } + // randomHorizontalWiggling, then a second, horizontal move. + let wiggle = |r: &mut LegacyRandom| { + let f = r.next_float() * 0.003; + f64::from(if r.next_boolean() { f } else { -f }) * 0.5 + }; + p.velocity[0] += wiggle(&mut p.random); + p.velocity[2] += wiggle(&mut p.random); + p.move_by(level, [p.velocity[0], 0.0, p.velocity[2]]); + let progress = ((p.position[1] - y_start) / (y_end - y_start)) as f32; + p.size = size_start + progress * (0.15 - size_start); + p.behaviour = Behaviour::SulfurBubble { + y_start, + y_end, + size_start, + y_prev: p.position[1], + }; + } Behaviour::BubbleColumnUp => { p.base_tick(level); if !p.removed && level.fluid(ParticleLevel::block_at(p.position)).0 != Fluid::Water diff --git a/crates/horizon-client/src/pose.rs b/crates/horizon-client/src/pose.rs index 9c8124b0e..e34b1f1fc 100644 --- a/crates/horizon-client/src/pose.rs +++ b/crates/horizon-client/src/pose.rs @@ -14,6 +14,7 @@ pub enum Pose { Crouching, Swimming, FallFlying, + SpinAttack, } impl Pose { pub fn name(self) -> &'static str { @@ -22,13 +23,14 @@ impl Pose { Self::Crouching => "CROUCHING", Self::Swimming => "SWIMMING", Self::FallFlying => "FALL_FLYING", + Self::SpinAttack => "SPIN_ATTACK", } } pub fn dimensions(self, scale: f32) -> Dimensions { let (height, eye_height) = match self { Self::Standing => (1.8, 1.62), Self::Crouching => (1.5, 1.27), - Self::Swimming | Self::FallFlying => (0.6, 0.4), + Self::Swimming | Self::FallFlying | Self::SpinAttack => (0.6, 0.4), }; Dimensions { width: 0.6 * scale, @@ -98,11 +100,13 @@ impl MotionWorld<'_, '_, '_> { if !self.can_fit_pose(Pose::Swimming)? { return Ok(()); } - // Player.getDesiredPose: swimming before gliding. + // Player.getDesiredPose: swimming, gliding, Riptide's spin. let desired = if self.player.swimming { Pose::Swimming } else if self.player.fall_flying { Pose::FallFlying + } else if self.player.auto_spin_attack_ticks > 0 { + Pose::SpinAttack } else if self.player.shift_key_down && !self.player.flying { Pose::Crouching } else { diff --git a/crates/horizon-client/src/projectiles.rs b/crates/horizon-client/src/projectiles.rs index cc44e7511..093482a08 100644 --- a/crates/horizon-client/src/projectiles.rs +++ b/crates/horizon-client/src/projectiles.rs @@ -689,6 +689,19 @@ impl Projectile { } damage as f32 } + /// The item a thrown potion is drawn as (`ThrownItemRenderer`): the + /// splash potion `Witch.performRangedAttack` makes for the effect. + pub fn potion_item(&self) -> Option { + let ProjectileKind::Potion { effect, .. } = self.kind else { + return None; + }; + let potion = match effect { + "minecraft:instant_health" => "minecraft:healing", + "minecraft:instant_damage" => "minecraft:harming", + other => other, + }; + Some(crate::items::ItemStack::new("minecraft:splash_potion", 1).with_potion(potion)) + } /// The item sprite drawn for thrown projectiles (ThrownItemRenderer). pub fn item_sprite(&self) -> Option<&'static str> { Some(match self.kind { diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index 34b945626..1fadacf57 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -48,7 +48,10 @@ pub fn sound_source(event: &str) -> usize { "zombified_piglin", "wither_skeleton", ]; - if e.starts_with("music_disc.") { + if e == "block.potent_sulfur.noxious_gas" { + // PotentSulfurBlock.animateTick, its only caller, plays it as AMBIENT. + index("ambient") + } else if e.starts_with("music_disc.") { index("record") } else if e.starts_with("music.") { index("music") diff --git a/crates/horizon-client/src/shader_pack.rs b/crates/horizon-client/src/shader_pack.rs index ec86edc77..f3cf46028 100644 --- a/crates/horizon-client/src/shader_pack.rs +++ b/crates/horizon-client/src/shader_pack.rs @@ -171,11 +171,41 @@ pub fn list(dir: &Path) -> Vec<(String, Result)> { packs } +/// `shaderpacks/` beside `options.txt` (the game's working folder: the game +/// home, not the launcher's version folder). +pub fn folder() -> PathBuf { + std::env::current_dir().unwrap_or_default().join(DIR) +} + +/// `shaderpacks/` and its packs as the Shader Packs page lists them, read +/// again at most once a second while the page is open, so a pack dropped +/// into the folder shows up. +#[derive(Debug, Default)] +pub struct Folder { + pub dir: PathBuf, + pub packs: Vec<(String, Result)>, + read: Option, +} + +impl Folder { + pub fn poll(&mut self, dir: PathBuf) { + let fresh = self + .read + .is_some_and(|t| t.elapsed() < std::time::Duration::from_secs(1)); + if fresh && self.dir == dir { + return; + } + self.packs = list(&dir); + self.dir = dir; + self.read = Some(std::time::Instant::now()); + } +} + /// A Java pack has no manifest: its name is its file name. fn java_info(name: String) -> Info { Info { name, - description: String::new(), + description: "Iris/OptiFine pack: its full-screen passes run.".into(), authors: Vec::new(), version: String::new(), license: String::new(), diff --git a/crates/horizon-client/src/spans.rs b/crates/horizon-client/src/spans.rs index 5c37f2bfc..ce69be8ce 100644 --- a/crates/horizon-client/src/spans.rs +++ b/crates/horizon-client/src/spans.rs @@ -1,8 +1,10 @@ //! Named timings within a frame, for finding what makes a frame slow: //! `HORIZON_SPIKES=MS` prints the spans of every frame whose CPU time //! exceeds MS milliseconds, and of every server tick (dedicated or -//! integrated) longer than MS. Costs one clock read per span when enabled -//! and a relaxed load otherwise. +//! integrated) longer than MS. Each span keeps its wall time and the +//! thread's CPU time inside it, so a span that waited (for a lock, the GPU +//! or a core on a busy machine) shows apart from one that worked. Costs two +//! clock reads per span when enabled and a relaxed load otherwise. use std::{ cell::RefCell, sync::atomic::{AtomicBool, Ordering}, @@ -11,7 +13,15 @@ use std::{ static ENABLED: AtomicBool = AtomicBool::new(false); thread_local! { - static SPANS: RefCell> = const { RefCell::new(Vec::new()) }; + static SPANS: RefCell> = const { RefCell::new(Vec::new()) }; +} + +/// A named timing: wall milliseconds and the thread's CPU milliseconds in it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Span { + pub name: &'static str, + pub ms: f32, + pub cpu_ms: f32, } pub fn enable(on: bool) { @@ -23,10 +33,13 @@ pub fn time(name: &'static str, f: impl FnOnce() -> T) -> T { if !ENABLED.load(Ordering::Relaxed) { return f(); } - let started = Instant::now(); + let (started, cpu) = (Instant::now(), thread_cpu()); let out = f(); let ms = started.elapsed().as_secs_f32() * 1000.0; - SPANS.with(|s| s.borrow_mut().push((name, ms))); + let cpu_ms = thread_cpu() + .zip(cpu) + .map_or(ms, |(end, start)| (end - start).as_secs_f32() * 1000.0); + SPANS.with(|s| s.borrow_mut().push(Span { name, ms, cpu_ms })); out } /// The CPU time this thread has used, where the platform tells it: a tick @@ -42,21 +55,84 @@ pub fn thread_cpu() -> Option { None } /// The frame's spans, summed by name, slowest first; clears them. -pub fn take() -> Vec<(&'static str, f32)> { +pub fn take() -> Vec { let spans = SPANS.with(|s| std::mem::take(&mut *s.borrow_mut())); - let mut sums: Vec<(&'static str, f32)> = Vec::new(); - for (name, ms) in spans { - match sums.iter_mut().find(|(n, _)| *n == name) { - Some(entry) => entry.1 += ms, - None => sums.push((name, ms)), + let mut sums: Vec = Vec::new(); + for span in spans { + match sums.iter_mut().find(|s| s.name == span.name) { + Some(sum) => { + sum.ms += span.ms; + sum.cpu_ms += span.cpu_ms; + } + None => sums.push(span), } } - sums.sort_by(|a, b| b.1.total_cmp(&a.1)); + sums.sort_by(|a, b| b.ms.total_cmp(&a.ms)); sums } +/// `name wall` for spans of at least 0.5 ms, with `/cpu` when the thread +/// worked for less than nine tenths of it: the slow-frame and slow-tick lines. +pub fn describe(spans: &[Span]) -> String { + let list: Vec = spans + .iter() + .filter(|s| s.ms >= 0.5) + .map(|s| { + if s.cpu_ms < s.ms * 0.9 { + format!("{} {:.1}/{:.1}", s.name, s.ms, s.cpu_ms) + } else { + format!("{} {:.1}", s.name, s.ms) + } + }) + .collect(); + list.join(", ") +} #[cfg(test)] mod tests { + use super::Span; + + /// Spans of one name add up; a span the thread spent mostly waiting + /// shows its CPU time after the wall time, short ones are left out. + #[test] + fn spans_sum_by_name_and_show_waits() { + super::SPANS.with(|s| { + s.borrow_mut().extend([ + Span { + name: "tick", + ms: 2.0, + cpu_ms: 2.0, + }, + Span { + name: "submit", + ms: 30.0, + cpu_ms: 0.2, + }, + Span { + name: "tick", + ms: 3.0, + cpu_ms: 2.9, + }, + Span { + name: "hud", + ms: 0.3, + cpu_ms: 0.3, + }, + ]); + }); + let spans = super::take(); + assert_eq!( + spans[0], + Span { + name: "submit", + ms: 30.0, + cpu_ms: 0.2 + } + ); + assert_eq!((spans[1].name, spans[1].ms), ("tick", 5.0)); + assert_eq!(super::describe(&spans), "submit 30.0/0.2, tick 5.0"); + assert!(super::take().is_empty()); + } + /// The thread's CPU clock moves with work done on it, not with time /// spent asleep. #[cfg(unix)] diff --git a/crates/horizon-client/src/stations.rs b/crates/horizon-client/src/stations.rs index 20750d6fe..715c2663e 100644 --- a/crates/horizon-client/src/stations.rs +++ b/crates/horizon-client/src/stations.rs @@ -198,8 +198,10 @@ pub fn anvil_result( let mut repair_item_count_cost = 0; let mut naming_cost = 0; if let Some(addition) = addition { - // addition.has(STORED_ENCHANTMENTS): only enchanted books carry that component. - let using_book = &*addition.item == "minecraft:enchanted_book"; + // addition.has(STORED_ENCHANTMENTS): an enchanted book (its default + // component), or any item given stored enchantments. + let using_book = &*addition.item == "minecraft:enchanted_book" + || !addition.stored_enchantments().is_empty(); if is_damageable(items, &result) && is_valid_repair_item(e, items, input, addition) { let max = max_damage(items, &result); let mut repair = (result.damage as i32).min(max / 4); @@ -401,13 +403,13 @@ pub fn grindstone_result( (None, None) => None, } } -/// Experience from the grindstone result slot's `getExperienceAmount`. -pub fn grindstone_experience( +/// The grindstone result slot's `getExperienceAmount` before its roll: the +/// minimum costs of the inputs' non-curse enchantments. +pub fn grindstone_xp_base( e: &Enchantments, - random: &mut LegacyRandom, input: Option<&ItemStack>, additional: Option<&ItemStack>, -) -> u32 { +) -> i32 { let from = |s: Option<&ItemStack>| -> i32 { s.map_or(0, |s| { s.crafting_enchantments() @@ -417,7 +419,10 @@ pub fn grindstone_experience( .sum() }) }; - let amount = from(input) + from(additional); + from(input) + from(additional) +} +/// `getExperienceAmount`'s roll of the sum: `half + nextInt(half)`. +pub fn grindstone_xp_roll(amount: i32, random: &mut LegacyRandom) -> u32 { if amount > 0 { let half = (f64::from(amount) / 2.0).ceil() as i32; (half + random.next_int_bound(half).unwrap_or(0)) as u32 @@ -425,6 +430,15 @@ pub fn grindstone_experience( 0 } } +/// Experience from the grindstone result slot's `getExperienceAmount`. +pub fn grindstone_experience( + e: &Enchantments, + random: &mut LegacyRandom, + input: Option<&ItemStack>, + additional: Option<&ItemStack>, +) -> u32 { + grindstone_xp_roll(grindstone_xp_base(e, input, additional), random) +} // ---------------------------------------------------------------- smithing & stonecutting @@ -450,6 +464,7 @@ pub struct Stonecutting { pub input: Ingredient, pub result: ItemStack, } +#[derive(Default)] pub struct StationRecipes { pub smithing: Vec, /// Sorted by recipe id, the registry order vanilla lists them in. diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 858d05d30..15ed1674e 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -276,6 +276,8 @@ pub struct Streaming { /// chunks finish out to `radius + 1` (Chebyshev) and generation reaches /// past that as around the player. They are generated and kept but not meshed. pub extra: Vec<((i32, i32), i32)>, + /// `extra`'s squares as a grid, made again when `extra` changes. + cover: Option, /// Mesh the sections for drawing (false on a server thread). pub mesh: bool, } @@ -391,6 +393,7 @@ impl GenerationScan { radius: input.ranges.radius, extra: input.ranges.extra, forced: input.ranges.forced, + cover: input.ranges.cover, }; self.remember(ranges, input.world); } else { @@ -436,7 +439,7 @@ impl Streaming { thread::Builder::new() .name(format!("horizon-worker-{i}")) .spawn(move || { - // A dedicated server's tick comes first (horizon_threads). + // Ticks and frames come first (horizon_threads). horizon_threads::behind_server(); let mut worker = generator.worker(); // The face visibility table and its occlusion cache stay with @@ -562,6 +565,7 @@ impl Streaming { meshed_total: 0, remote: false, extra: Vec::new(), + cover: None, mesh: true, } } @@ -808,6 +812,7 @@ impl Streaming { if self.paused { return (uploads, Vec::new()); } + ExtraCover::refresh(&mut self.cover, &self.extra); self.relight_edits(world); let deferred = std::mem::take(&mut self.deferred); let received = std::iter::from_fn(|| self.results.try_recv().ok()); @@ -982,6 +987,7 @@ impl Streaming { radius: self.radius, extra: &self.extra, forced: &self.forced, + cover: ExtraCover::matching(&self.cover, &self.extra), }; let (protos, generating) = (&self.protos, &self.generating); self.decoration_order.retain(|x, z| { @@ -1109,6 +1115,7 @@ impl Streaming { radius: self.radius, extra: &self.extra, forced: &self.forced, + cover: ExtraCover::matching(&self.cover, &self.extra), }; self.waiting.retain(|&(x, sy, z)| { let back = ranges.in_view(x, z); @@ -1185,6 +1192,7 @@ impl Streaming { radius: self.radius, extra: &self.extra, forced: &self.forced, + cover: ExtraCover::matching(&self.cover, &self.extra), }, world, generating: &self.generating, @@ -1280,6 +1288,7 @@ impl Streaming { radius: self.radius, extra: &self.extra, forced: &self.forced, + cover: ExtraCover::matching(&self.cover, &self.extra), } } fn near_finished(&self, x: i32, z: i32, reach: i32) -> bool { @@ -1365,6 +1374,100 @@ struct Ranges<'a> { radius: i32, extra: &'a [((i32, i32), i32)], forced: &'a HashSet<(i32, i32)>, + /// `extra` as a grid, when one was made for it: `in_extra` without a + /// scan of every area. + cover: Option<&'a ExtraCover>, +} +/// For every column near the extra areas, how far it lies outside the +/// nearest one's square (Chebyshev distance less its radius; 0 inside). A server has an area per player, and streaming asks of every +/// loaded and wanted column whether one reaches it, several times a tick: +/// with fifty players, a scan of fifty squares per question. +struct ExtraCover { + extra: Vec<((i32, i32), i32)>, + x0: i32, + z0: i32, + width: u32, + depth: u32, + cells: Box<[i8]>, +} +impl ExtraCover { + /// The largest margin the grid answers for; beyond it (and outside the + /// grid) a column is further than that from every square. + const REACH: i32 = 4; + /// The largest grid, in columns (a mebibyte). + const CELLS: u64 = 1 << 20; + fn matching<'a>( + cover: &'a Option, + extra: &[((i32, i32), i32)], + ) -> Option<&'a ExtraCover> { + cover.as_ref().filter(|c| c.extra == extra) + } + /// Make the grid again if `extra` changed; none for one area or none + /// (a scan is as quick), or areas too far apart. + fn refresh(cover: &mut Option, extra: &[((i32, i32), i32)]) { + if cover.as_ref().is_some_and(|c| c.extra == extra) { + return; + } + *cover = Self::new(extra); + } + fn new(extra: &[((i32, i32), i32)]) -> Option { + if extra.len() < 2 || extra.iter().any(|&(_, r)| !(0..=64).contains(&r)) { + return None; + } + let k = i64::from(Self::REACH); + let (mut x0, mut z0, mut x1, mut z1) = (i64::MAX, i64::MAX, i64::MIN, i64::MIN); + for &((x, z), r) in extra { + let (x, z, r) = (i64::from(x), i64::from(z), i64::from(r) + k); + (x0, z0, x1, z1) = (x0.min(x - r), z0.min(z - r), x1.max(x + r), z1.max(z + r)); + } + let (width, depth) = ((x1 - x0 + 1) as u64, (z1 - z0 + 1) as u64); + let fits = |lo: i64, hi: i64| lo >= i64::from(i32::MIN) && hi <= i64::from(i32::MAX); + if width * depth > Self::CELLS || !fits(x0, x1) || !fits(z0, z1) { + return None; + } + let (x0, z0, width, depth) = (x0 as i32, z0 as i32, width as u32, depth as u32); + let mut cells = vec![(Self::REACH + 1) as i8; (width * depth) as usize].into_boxed_slice(); + // Inside a square counts as 0: no margin asked for is below it. Each + // row of a square is a run of one value with a slope at either end. + let lower = |run: &mut [i8], v: i8| run.iter_mut().for_each(|c| *c = (*c).min(v)); + for &((cx, cz), r) in extra { + let reach = r + Self::REACH; + for dz in -reach..=reach { + let start = (cz + dz - z0) as usize * width as usize + (cx - x0) as usize; + let row = &mut cells[start - reach as usize..=start + reach as usize]; + let flat = dz.abs().max(r); + let centre = reach as usize; + lower( + &mut row[centre - flat as usize..=centre + flat as usize], + (flat - r) as i8, + ); + for d in flat + 1..=reach { + let v = (d - r) as i8; + lower(&mut row[centre - d as usize..=centre - d as usize], v); + lower(&mut row[centre + d as usize..=centre + d as usize], v); + } + } + } + Some(Self { + extra: extra.to_vec(), + x0, + z0, + width, + depth, + cells, + }) + } + /// Whether (x, z) is within `margin` of an area's square, for a + /// `margin` up to `REACH`. + fn within(&self, x: i32, z: i32, margin: i32) -> bool { + let (dx, dz) = ( + x.wrapping_sub(self.x0) as u32, + z.wrapping_sub(self.z0) as u32, + ); + dx < self.width + && dz < self.depth + && i32::from(self.cells[(dz * self.width + dx) as usize]) <= margin + } } impl Ranges<'_> { /// `distance`, or `rings` while the level loading screen is up. @@ -1441,6 +1544,11 @@ impl Ranges<'_> { /// Within `margin` of an extra area's square (Chebyshev distance, as /// vanilla's ticket levels spread). fn in_extra(&self, x: i32, z: i32, margin: i32) -> bool { + if let Some(cover) = self.cover + && (0..=ExtraCover::REACH).contains(&margin) + { + return cover.within(x, z, margin); + } self.extra .iter() .any(|&(c, radius)| (x - c.0).abs().max((z - c.1).abs()) <= radius + margin) @@ -1554,6 +1662,7 @@ mod tests { radius: self.radius, extra: &self.extra, forced: &self.forced, + cover: None, }, world: &self.world, generating: &self.generating, @@ -1866,6 +1975,7 @@ mod tests { radius, extra: &[], forced: &forced, + cover: None, }; let square = |x: i32, z: i32, n: i32| { (-n..=n).flat_map(move |dz| (-n..=n).map(move |dx| (x + dx, z + dz))) @@ -1920,6 +2030,7 @@ mod tests { radius: 12, extra: &[], forced: &forced, + cover: None, }; let at = |dx: i32, dz: i32| (2 + dx, -1 + dz); let key = |(x, z): (i32, i32), loading| r.priority(x, z, loading); @@ -1945,6 +2056,7 @@ mod tests { radius, extra: &[((radius * 2 + 9, 3), 4)], forced: &forced, + cover: None, }; let span = radius * 3 + 20; for x in -span..=span { @@ -1984,6 +2096,7 @@ mod tests { radius: 2, extra: &extra, forced: &forced, + cover: None, }; let level = |x: i32, z: i32| 31 + ((x - 40).abs().max((z + 9).abs()) - view).max(0); for x in 40 - view - 8..=40 + view + 8 { @@ -2021,3 +2134,128 @@ mod tests { } } } + +#[cfg(test)] +mod cover_tests { + use super::*; + + fn areas(seed: &mut u64, n: usize, spread: i32) -> Vec<((i32, i32), i32)> { + let mut next = |m: i32| { + *seed ^= *seed << 13; + *seed ^= *seed >> 7; + *seed ^= *seed << 17; + (*seed % (2 * m as u64 + 1)) as i32 - m + }; + (0..n) + .map(|_| ((next(spread), next(spread)), 2 + next(14).abs())) + .collect() + } + + /// Every question streaming asks gets the same answer with the grid. + #[test] + fn the_grid_answers_as_the_scan() { + let mut seed = 0x9E37_79B9_7F4A_7C15u64; + let forced: HashSet<(i32, i32)> = [(40, -40)].into(); + for case in 0..60 { + let extra = areas(&mut seed, 2 + case % 20, [4, 30, 120][case % 3]); + let cover = ExtraCover::new(&extra).expect("a grid"); + let ranges = |cover| Ranges { + center: (3, -2), + radius: 10, + extra: &extra, + forced: &forced, + cover, + }; + let (scan, grid) = (ranges(None), ranges(Some(&cover))); + let span = [4, 30, 120][case % 3] + 40; + for z in -span..=span { + for x in -span..=span { + for m in 0..=ExtraCover::REACH + 2 { + assert_eq!( + scan.in_extra(x, z, m), + grid.in_extra(x, z, m), + "case {case} ({x}, {z}) {m}" + ); + } + for d in [false, true] { + assert_eq!(scan.unloaded(x, z, d), grid.unloaded(x, z, d)); + assert_eq!(scan.requested(x, z, d), grid.requested(x, z, d)); + assert_eq!(scan.chunk_kept(x, z, d), grid.chunk_kept(x, z, d)); + } + } + } + } + } + + #[test] + fn a_stale_or_impossible_grid_is_not_used() { + let mut cover = None; + ExtraCover::refresh(&mut cover, &[((0, 0), 11), ((5, 5), 11)]); + assert!(ExtraCover::matching(&cover, &[((0, 0), 11), ((5, 5), 11)]).is_some()); + assert!(ExtraCover::matching(&cover, &[((0, 0), 11), ((5, 6), 11)]).is_none()); + // Too far apart for a mebibyte of grid, and one area alone: scans. + assert!(ExtraCover::new(&[((0, 0), 11), ((100_000, 0), 11)]).is_none()); + assert!(ExtraCover::new(&[((0, 0), 11)]).is_none()); + assert!(ExtraCover::new(&[((i32::MAX - 1, 0), 11), ((i32::MAX - 3, 0), 11)]).is_none()); + assert!(ExtraCover::new(&[((0, i32::MAX - 1), 11), ((0, i32::MAX - 3), 11)]).is_none()); + assert!(ExtraCover::new(&[((0, i32::MIN + 1), 11), ((0, i32::MIN + 3), 11)]).is_none()); + } + + /// cargo test --release -p horizon-client --lib cover_tests::cover_cost -- --ignored --nocapture + #[test] + #[ignore] + fn cover_cost() { + let forced = HashSet::new(); + for players in [10usize, 25, 50] { + // The benchmark's bots: most near spawn, a fifth flying outwards. + let extra: Vec<_> = (0..players) + .map(|i| { + let a = i as f64 * 2.399; + let d = if i % 5 == 0 { 30.0 } else { 3.0 }; + (((a.cos() * d) as i32, (a.sin() * d) as i32), 11) + }) + .collect(); + let cover = ExtraCover::new(&extra).unwrap(); + let ranges = |cover| Ranges { + center: (0, 0), + radius: 10, + extra: &extra, + forced: &forced, + cover, + }; + // The columns streaming asks about: everything kept, and the + // generation scan's ring past it. + let columns: Vec<(i32, i32)> = (-60..=60) + .flat_map(|z| (-60..=60).map(move |x| (x, z))) + .filter(|&(x, z)| { + ranges(None).requested(x, z, true) || !ranges(None).unloaded(x, z, true) + }) + .collect(); + let rounds = 100; + let time = |r: &Ranges| { + let t = std::time::Instant::now(); + let mut n = 0usize; + for _ in 0..rounds { + for &(x, z) in &columns { + n += usize::from(r.unloaded(x, z, true)); + n += usize::from(r.requested(x, z, true)); + n += usize::from(r.in_range(x, z, 1)); + } + } + std::hint::black_box(n); + t.elapsed().as_secs_f64() * 1e3 / f64::from(rounds) + }; + let t = std::time::Instant::now(); + for _ in 0..rounds { + std::hint::black_box(ExtraCover::new(std::hint::black_box(&extra))); + } + let build = t.elapsed().as_secs_f64() * 1e3 / f64::from(rounds); + println!( + "{players} players, {} columns, 3 questions each: scan {:.3} ms, grid {:.3} ms (+ {build:.3} ms to build)", + columns.len(), + time(&ranges(None)), + time(&ranges(Some(&cover))), + ); + } + } +} diff --git a/crates/horizon-client/src/telemetry.rs b/crates/horizon-client/src/telemetry.rs index d0140f941..ec67fe7f7 100644 --- a/crates/horizon-client/src/telemetry.rs +++ b/crates/horizon-client/src/telemetry.rs @@ -1,6 +1,7 @@ //! The game's part in opt-in data collection (`horizon_telemetry`, docs/telemetry.md). When the //! player allows it, the game keeps a scrubbed crash report, or a play session's performance -//! summary, in the outbox. It never sends anything itself: the launcher does, at its next start. +//! summary, in the outbox. It never sends those itself: the launcher does, at its next start (the +//! game's only sending is the anonymous "I'm playing" ping, `heartbeat.rs`). //! Without the player's yes for that kind nothing is kept, and crash-reports/ stays local. use std::path::Path; use std::sync::atomic::{AtomicU32, Ordering}; @@ -75,7 +76,7 @@ pub fn system() -> System { system } -/// The release (`v2026.10.15`), or the client's crate version for a build from source. +/// The release (`v0.2.3`), or the client's crate version for a build from source. pub fn version() -> String { crate::crash::release_tag().unwrap_or_else(|| format!("dev {}", env!("CARGO_PKG_VERSION"))) } diff --git a/crates/horizon-client/src/terrain.wgsl b/crates/horizon-client/src/terrain.wgsl index be3405b23..c0a2fc6fd 100644 --- a/crates/horizon-client/src/terrain.wgsl +++ b/crates/horizon-client/src/terrain.wgsl @@ -16,11 +16,14 @@ struct Globals { fog_ends: vec4, // Atlas rects (u0, v0, width, height) of end_sky.png and end_portal.png. end_portal_sprites: array, 2>, - // x: vanilla's GameTime ((game time % 24000 + partial tick) / 24000) + // x: vanilla's GameTime ((game time % 24000 + partial tick) / 24000), z: how many + // dynamic_lights are set time: vec4, // Atlas rect of the current destroy stage (read by entity.wgsl). crumbling_sprite: vec4, outline_params: vec4, + // Horizon Extras' dynamic lights: camera-relative position and level (dynamic_light.rs). + dynamic_lights: array, 16>, } @group(0) @binding(0) var globals: Globals; @group(0) @binding(1) var sprites: texture_2d_array; @@ -67,6 +70,18 @@ struct TerrainOut { @location(3) spherical: f32, @location(4) cylindrical: f32, } +// Horizon Extras' dynamic lights (dynamic_light.rs): the block light, in the vertex's units +// (16 per level), a vertex at camera-relative `pos` gets from the frame's light sources, one +// level less per block. time.z of them are set: none when the extra is off, so no loop runs. +fn dynamic_block_light(pos: vec3) -> f32 { + let count = min(u32(globals.time.z), 16u); + var level = 0.0; + for (var i = 0u; i < count; i++) { + let l = globals.dynamic_lights[i]; + level = max(level, l.w - distance(pos, l.xyz)); + } + return level * 16.0; +} fn sample_lightmap(sky: f32, block: f32) -> vec4 { let uv = vec2(block, sky) * 16.0; return textureSampleLevel(lightmap, lightmap_sampler, @@ -105,7 +120,8 @@ fn terrain_vertex(position: vec3, uv: vec2, layer: u32, color: vec4>>); +pub struct Levels(Option>); + +/// The levels by chunk: a grid over the tickets' bounding box while it is +/// small (players near each other, the usual case), a map otherwise. Every +/// block entity, mob and ticking chunk asks each tick, so an index beats a +/// hash; and a player crossing into another chunk rebuilds it all. +enum Map { + Grid { + x0: i32, + z0: i32, + width: u32, + depth: u32, + cells: Box<[(u8, u8)]>, + }, + Sparse(FxHashMap<(i32, i32), (u8, u8)>), +} + +/// The largest grid, in chunks: 1 MiB of levels, a box 724 chunks wide. +const GRID_CELLS: u64 = 1 << 19; + +impl Map { + fn get(&self, x: i32, z: i32) -> (u8, u8) { + match self { + Self::Grid { + x0, + z0, + width, + depth, + cells, + } => { + let (dx, dz) = (x.wrapping_sub(*x0) as u32, z.wrapping_sub(*z0) as u32); + if dx < *width && dz < *depth { + cells[(dz * width + dx) as usize] + } else { + NONE + } + } + Self::Sparse(map) => map.get(&(x, z)).copied().unwrap_or(NONE), + } + } +} impl Levels { /// Chunk coordinates. fn get(&self, x: i32, z: i32) -> Option<(u8, u8)> { - let map = self.0.as_ref()?; - Some(map.get(&(x, z)).copied().unwrap_or(NONE)) + Some(self.0.as_ref()?.get(x, z)) } /// `DistanceManager.inEntityTickingRange`, in an entity-ticking chunk: /// where entities tick. @@ -112,19 +151,89 @@ impl ChunkTickets { } } -fn compute(s: &Sources) -> FxHashMap<(i32, i32), (u8, u8)> { +/// How far a player's tickets reach, and the simulation ticket's level. +fn reach(s: &Sources) -> (i32, i32, i32) { let view = s.view_distance.clamp(0, 32); let simulation = s.simulation_distance.clamp(0, 32); + // PLAYER_LOADING within the view distance, PLAYER_SIMULATION at the + // player's chunk (`getPlayerTicketLevel`: never below 0). + let player_sim = (i32::from(ENTITY_TICKING) - simulation).max(0); + let reach = (view + 1).max(i32::from(BLOCK_TICKING) - player_sim); + (view, player_sim, reach) +} + +fn compute(s: &Sources) -> Map { + let (view, player_sim, reach) = reach(s); + let boxes = s + .players + .iter() + .map(|&p| (p, reach)) + .chain(s.forced.iter().map(|&f| (f, 1))); + let Some((x0, z0, x1, z1)) = boxes.fold(None, |b, ((x, z), r)| { + let (lo_x, lo_z, hi_x, hi_z) = ( + i64::from(x) - i64::from(r), + i64::from(z) - i64::from(r), + i64::from(x) + i64::from(r), + i64::from(z) + i64::from(r), + ); + Some(match b { + None => (lo_x, lo_z, hi_x, hi_z), + Some((a, b, c, d)) => (lo_x.min(a), lo_z.min(b), hi_x.max(c), hi_z.max(d)), + }) + }) else { + return Map::Sparse(FxHashMap::default()); + }; + let (width, depth) = ((x1 - x0 + 1) as u64, (z1 - z0 + 1) as u64); + if width * depth > GRID_CELLS { + return Map::Sparse(compute_sparse(s)); + } + let (x0, z0, width, depth) = (x0 as i32, z0 as i32, width as u32, depth as u32); + let mut cells = vec![NONE; (width * depth) as usize].into_boxed_slice(); + let mut lower = |x: i32, z: i32, loading: i32, sim: i32| { + let i = ((z - z0) as u32 * width + (x - x0) as u32) as usize; + let e = &mut cells[i]; + e.0 = e.0.min(loading.min(i32::from(NONE.0)) as u8); + e.1 = e.1.min(sim.min(i32::from(NONE.1)) as u8); + }; + for &(px, pz) in &s.players { + for dz in -reach..=reach { + for dx in -reach..=reach { + let d = dx.abs().max(dz.abs()); + lower( + px + dx, + pz + dz, + i32::from(ENTITY_TICKING) + (d - view).max(0), + player_sim + d, + ); + } + } + } + for &(fx, fz) in &s.forced { + for dz in -1i32..=1 { + for dx in -1i32..=1 { + let level = i32::from(ENTITY_TICKING) + dx.abs().max(dz.abs()); + lower(fx + dx, fz + dz, level, level); + } + } + } + Map::Grid { + x0, + z0, + width, + depth, + cells, + } +} + +/// The levels as a map, for tickets spread too far apart for a grid. +fn compute_sparse(s: &Sources) -> FxHashMap<(i32, i32), (u8, u8)> { + let (view, player_sim, reach) = reach(s); let mut levels: FxHashMap<(i32, i32), (u8, u8)> = FxHashMap::default(); let mut lower = |key, loading: i32, sim: i32| { let e = levels.entry(key).or_insert(NONE); e.0 = e.0.min(loading.min(i32::from(NONE.0)) as u8); e.1 = e.1.min(sim.min(i32::from(NONE.1)) as u8); }; - // PLAYER_LOADING within the view distance, PLAYER_SIMULATION at the - // player's chunk (`getPlayerTicketLevel`: never below 0). - let player_sim = (i32::from(ENTITY_TICKING) - simulation).max(0); - let reach = (view + 1).max(i32::from(BLOCK_TICKING) - player_sim); for &(px, pz) in &s.players { for dz in -reach..=reach { for dx in -reach..=reach { @@ -229,4 +338,111 @@ mod tests { t.update(None); assert!(t.levels().0.is_none()); } + + /// The grid answers as the map does, everywhere around the tickets. + #[test] + fn grid_matches_the_map() { + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut next = |n: i32| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % (2 * n as u64 + 1)) as i32 - n + }; + for case in 0..200 { + let spread = [3, 20, 80][case % 3]; + let players: Vec<_> = (0..1 + case % 12) + .map(|_| (next(spread), next(spread))) + .collect(); + let forced: Vec<_> = (0..case % 4) + .map(|_| (next(spread), next(spread))) + .collect(); + let s = Sources { + players, + forced, + view_distance: 2 + next(12).abs(), + simulation_distance: 2 + next(12).abs(), + }; + let Map::Grid { .. } = compute(&s) else { + panic!("case {case} fell back to the map"); + }; + let (grid, map) = (compute(&s), Map::Sparse(compute_sparse(&s))); + let r = spread + 50; + for z in -r..=r { + for x in -r..=r { + assert_eq!(grid.get(x, z), map.get(x, z), "case {case} at ({x}, {z})"); + } + } + } + } + + #[test] + fn far_apart_tickets_use_the_map() { + let l = levels( + &[(0, 0), (100_000, -100_000)], + &[(i32::MAX - 2, i32::MIN + 2)], + 10, + 10, + ); + assert!(matches!(**l.0.as_ref().unwrap(), Map::Sparse(_))); + assert!(l.entity_ticking(100_010, -100_010) && !l.block_ticking(50_000, 0)); + assert!(l.entity_ticking(i32::MAX - 2, i32::MIN + 2)); + } + + /// cargo test --release -p horizon-client --lib ticket_levels::tests::levels_cost -- --ignored --nocapture + #[test] + #[ignore] + fn levels_cost() { + for players in [1usize, 10, 25, 50] { + // The benchmark's bots: most near spawn, a fifth flying outwards. + let at: Vec<_> = (0..players) + .map(|i| { + let a = i as f64 * 2.399; + let d = if i % 5 == 0 { 30.0 } else { 3.0 }; + ((a.cos() * d) as i32, (a.sin() * d) as i32) + }) + .collect(); + let s = Sources { + players: at.clone(), + forced: Vec::new(), + view_distance: 10, + simulation_distance: 10, + }; + let rounds = 200; + let t = std::time::Instant::now(); + for _ in 0..rounds { + std::hint::black_box(compute_sparse(std::hint::black_box(&s))); + } + let map_build = t.elapsed().as_secs_f64() * 1e3 / rounds as f64; + let t = std::time::Instant::now(); + for _ in 0..rounds { + std::hint::black_box(compute(std::hint::black_box(&s))); + } + let grid_build = t.elapsed().as_secs_f64() * 1e3 / rounds as f64; + // A tick's questions: every chunk within 12 of every player. + let (map, grid) = (Map::Sparse(compute_sparse(&s)), compute(&s)); + let ask = |m: &Map| { + let t = std::time::Instant::now(); + let mut n = 0u32; + for _ in 0..rounds { + for &(px, pz) in &at { + for z in pz - 12..=pz + 12 { + for x in px - 12..=px + 12 { + n += + u32::from(std::hint::black_box(m.get(x, z)).0 <= BLOCK_TICKING); + } + } + } + } + std::hint::black_box(n); + t.elapsed().as_secs_f64() * 1e3 / rounds as f64 + }; + println!( + "{players} players: build {map_build:.3} -> {grid_build:.3} ms, {} lookups {:.3} -> {:.3} ms", + players * 625, + ask(&map), + ask(&grid) + ); + } + } } diff --git a/crates/horizon-client/src/world.rs b/crates/horizon-client/src/world.rs index 4a80a7fcd..3b2920ade 100644 --- a/crates/horizon-client/src/world.rs +++ b/crates/horizon-client/src/world.rs @@ -93,6 +93,9 @@ pub struct World { pub light_log: Option>, /// The villager POIs of each section (`PoiManager`'s sections). pub pois: crate::poi_sections::PoiSections, + /// The moving-piston block entities of the level, by position, copied + /// from the block ticks after each tick: collision and rendering read them. + pub moving_pistons: Vec<([i32; 3], horizon_world::piston_shape::MovingPistonState)>, } /// ServerLevel weather state (advanceWeatherCycle). #[derive(Clone, Copy, Debug, Default)] @@ -178,6 +181,7 @@ impl World { weather: Weather::default(), block_log: None, light_log: None, + moving_pistons: Vec::new(), pois: Default::default(), } } diff --git a/crates/horizon-client/tests/lan_bot.rs b/crates/horizon-client/tests/lan_bot.rs index ae70cccb8..bd22d6e0a 100644 --- a/crates/horizon-client/tests/lan_bot.rs +++ b/crates/horizon-client/tests/lan_bot.rs @@ -184,6 +184,7 @@ impl Server { equipment: Default::default(), health: 20.0, attributes: Vec::new(), + bed: None, living_flags: 0, }; let mut ctx = TickCtx { diff --git a/crates/horizon-core/src/geometry/mod.rs b/crates/horizon-core/src/geometry/mod.rs index 950403ee8..3081f66be 100644 --- a/crates/horizon-core/src/geometry/mod.rs +++ b/crates/horizon-core/src/geometry/mod.rs @@ -602,8 +602,18 @@ pub(crate) fn clamp(value: f64, min: f64, max: f64) -> f64 { java_min(value, max) } } +/// `Mth.floor`, which is `(int) Math.floor(v)`: truncate, then step down for +/// negative fractions. A truncating conversion and a compare, where +/// `f64::floor` is a libm call on baseline x86-64. Both casts saturate (NaN is +/// 0), so the step down saturates too: below `i32::MIN` stays `i32::MIN`. +#[inline] pub(crate) fn floor_i32(value: f64) -> i32 { - value.floor() as i32 + let truncated = value as i32; + if value < f64::from(truncated) { + truncated.saturating_sub(1) + } else { + truncated + } } fn lerp(amount: f64, start: f64, end: f64) -> f64 { start + amount * (end - start) @@ -635,6 +645,42 @@ fn next_down(value: f64) -> f64 { #[cfg(test)] mod tests { use super::*; + + #[test] + fn floor_i32_is_mths_floor() { + for v in [ + 0.0, + -0.0, + 0.5, + -0.5, + 1.0, + -1.0, + 2.999, + -2.999, + 1e-300, + -1e-300, + 16_777_215.5, + -16_777_215.5, + // Past the i32 range `(int) Math.floor` saturates (vanilla 26.3's + // BlockCollisions and BlockPos.containing rely on it). + 2_147_483_647.5, + 2_147_483_648.0, + -2_147_483_648.0, + -2_147_483_648.5, + -2_147_483_649.0, + 3e9, + -3e9, + f64::MAX, + f64::MIN, + f64::INFINITY, + f64::NEG_INFINITY, + ] { + assert_eq!(floor_i32(v), v.floor() as i32, "{v}"); + } + assert_eq!(floor_i32(f64::NAN), 0); + assert_eq!(floor_i32(-3e9), i32::MIN); + assert_eq!(floor_i32(-2_147_483_648.5), i32::MIN); + } #[test] fn ray_faces_and_half_open_bounds() { let b = Aabb::block(BlockPos::new(0, 0, 0)); diff --git a/crates/horizon-core/src/lib.rs b/crates/horizon-core/src/lib.rs index c8077b327..9034ef2eb 100644 --- a/crates/horizon-core/src/lib.rs +++ b/crates/horizon-core/src/lib.rs @@ -17,6 +17,7 @@ pub mod storage; pub mod text; pub mod ticks; +pub mod release; pub mod version; pub use version::VANILLA_VERSION; diff --git a/crates/horizon-core/src/noise/mod.rs b/crates/horizon-core/src/noise/mod.rs index cb255fbe5..e715b10f0 100644 --- a/crates/horizon-core/src/noise/mod.rs +++ b/crates/horizon-core/src/noise/mod.rs @@ -61,8 +61,8 @@ impl GradientTable { i32::from(self.permutations[(index & 255) as usize]) } - fn gradient(&self, index: i32) -> [i32; 3] { - GRADIENTS[(self.permute(index) & 15) as usize] + fn gradient(&self, index: i32) -> [f32; 3] { + PERLIN_GRADIENTS[(self.permute(index) & 15) as usize] } } @@ -87,8 +87,24 @@ const GRADIENTS: [[i32; 3]; 16] = [ [0, -1, -1], ]; -fn dot(gradient: [i32; 3], point: [f32; 3]) -> f32 { - gradient[0] as f32 * point[0] + gradient[1] as f32 * point[1] + gradient[2] as f32 * point[2] +/// [`GRADIENTS`] as floats, so a dot product needs no conversions: every +/// component is -1, 0 or 1, which a float holds exactly. +const PERLIN_GRADIENTS: [[f32; 3]; 16] = { + let mut out = [[0.0; 3]; 16]; + let mut i = 0; + while i < 16 { + out[i] = [ + GRADIENTS[i][0] as f32, + GRADIENTS[i][1] as f32, + GRADIENTS[i][2] as f32, + ]; + i += 1; + } + out +}; + +fn dot(gradient: [f32; 3], point: [f32; 3]) -> f32 { + gradient[0] * point[0] + gradient[1] * point[1] + gradient[2] * point[2] } /// Vanilla's periodic coordinate reduction with the normal Far Lands flag off. diff --git a/crates/horizon-core/src/noise/perlin.rs b/crates/horizon-core/src/noise/perlin.rs index 725373eff..ddcccfe9f 100644 --- a/crates/horizon-core/src/noise/perlin.rs +++ b/crates/horizon-core/src/noise/perlin.rs @@ -39,7 +39,7 @@ impl PerlinNoise { ) } - fn gradients(&self, cell: [i32; 3]) -> [[i32; 3]; 8] { + fn gradients(&self, cell: [i32; 3]) -> [[f32; 3]; 8] { self.gradients_at( self.table.permute(cell[0]), self.table.permute(cell[0].wrapping_add(1)), @@ -52,7 +52,7 @@ impl PerlinNoise { /// resolved. `add_volume` reuses one X column across every Y, so hoisting /// the two X permutes out of that loop avoids repeating them per Y. #[inline] - fn gradients_at(&self, p: i32, q: i32, cell_y: i32, cell_z: i32) -> [[i32; 3]; 8] { + fn gradients_at(&self, p: i32, q: i32, cell_y: i32, cell_z: i32) -> [[f32; 3]; 8] { let lower = self.table.permute(p.wrapping_add(cell_y)); let upper = self.table.permute(p.wrapping_add(cell_y).wrapping_add(1)); let lower_x = self.table.permute(q.wrapping_add(cell_y)); @@ -66,7 +66,7 @@ impl PerlinNoise { }) } - fn corner_values(gradients: [[i32; 3]; 8], point: [f32; 3]) -> [f32; 8] { + fn corner_values(gradients: [[f32; 3]; 8], point: [f32; 3]) -> [f32; 8] { std::array::from_fn(|i| { dot( gradients[i], @@ -99,7 +99,7 @@ impl PerlinNoise { let values = Self::corner_values(gradients, point); let fade = point.map(smoothstep); let gradient = - std::array::from_fn::<_, 3, _>(|axis| lerp3(fade, gradients.map(|g| g[axis] as f32))); + std::array::from_fn::<_, 3, _>(|axis| lerp3(fade, gradients.map(|g| g[axis]))); let changes = [ lerp2( fade[1], @@ -164,6 +164,31 @@ impl PerlinNoise { return Err(DensityError::BufferTooShort); } let [size_x, size_y, size_z] = volume.sizes(); + // Every X/Z column walks the same Y coordinates, so their cells, offsets + // and fades are computed once per volume instead of once per column. + let mut stack = [YSample::default(); STACK_Y]; + let mut heap = Vec::new(); + let ys = if size_y <= STACK_Y { + &mut stack[..size_y] + } else { + heap.resize(size_y, YSample::default()); + &mut heap[..] + }; + for (y, sample) in ys.iter_mut().enumerate() { + let input_y = f64::from(volume.coordinate(1, y)) * y_scale; + let shifted_y = wrap(input_y) + self.table.offsets[1]; + let cell = floor_i32(shifted_y); + let dy = shifted_y - f64::from(cell); + *sample = YSample { + cell, + fade: smoothstep(dy as f32), + offset: match fudge_y_scale { + Some(scale) => (dy - compute_fudge_y(input_y, dy, scale)) as f32, + None => dy as f32, + }, + }; + } + let ys = &*ys; let mut index = 0; for z in 0..size_z { let shifted_z = @@ -182,37 +207,40 @@ impl PerlinNoise { let mut previous_y = i32::MIN; let mut xz_dots = [0.0_f32; 8]; let mut y_gradients = [0.0_f32; 8]; - for y in 0..size_y { - let input_y = f64::from(volume.coordinate(1, y)) * y_scale; - let shifted_y = wrap(input_y) + self.table.offsets[1]; - let cell_y = floor_i32(shifted_y); - let dy = shifted_y - f64::from(cell_y); - let fade_y = smoothstep(dy as f32); - if previous_y != cell_y { - let gradients = self.gradients_at(p, q, cell_y, cell_z); + for (sample, out) in ys.iter().zip(&mut buffer[index..index + size_y]) { + if previous_y != sample.cell { + let gradients = self.gradients_at(p, q, sample.cell, cell_z); for i in 0..8 { - xz_dots[i] = gradients[i][0] as f32 * (dx - (i & 1) as f32) - + gradients[i][2] as f32 * (dz - ((i >> 2) & 1) as f32); - y_gradients[i] = gradients[i][1] as f32; + xz_dots[i] = gradients[i][0] * (dx - (i & 1) as f32) + + gradients[i][2] * (dz - ((i >> 2) & 1) as f32); + y_gradients[i] = gradients[i][1]; } - previous_y = cell_y; + previous_y = sample.cell; } - let dy = match fudge_y_scale { - Some(scale) => (dy - compute_fudge_y(input_y, dy, scale)) as f32, - None => dy as f32, - }; + let dy = sample.offset; let values = std::array::from_fn(|i| { xz_dots[i] + y_gradients[i] * (dy - ((i >> 1) & 1) as f32) }); - buffer[index] += amplitude * lerp3([fade_x, fade_y, fade_z], values); - index += 1; + *out += amplitude * lerp3([fade_x, sample.fade, fade_z], values); } + index += size_y; } } Ok(()) } } +/// Y columns up to this height keep their per-Y samples on the stack. +const STACK_Y: usize = 64; + +#[derive(Clone, Copy, Default)] +struct YSample { + cell: i32, + fade: f32, + /// The Y offset inside the cell used for the corner values, after any fudge. + offset: f32, +} + #[derive(Clone, Debug)] pub struct SmearedPerlinNoise { base: PerlinNoise, diff --git a/crates/horizon-core/src/release.rs b/crates/horizon-core/src/release.rs new file mode 100644 index 000000000..54a3cb94e --- /dev/null +++ b/crates/horizon-core/src/release.rs @@ -0,0 +1,32 @@ +//! Which Horizon release this build is (docs/versioning.md). Not Minecraft's version: that is +//! [`crate::version`], generated from the game's own files. + +/// The release's version (`0.2.3`, no `v`): release.yml builds every release with `HORIZON_VERSION` +/// set from its tag, so there are no version-bump commits. None for a build from source. +pub const RELEASE: Option<&str> = match option_env!("HORIZON_VERSION") { + Some(version) if !version.is_empty() => Some(version), + _ => None, +}; + +/// [`RELEASE`], or this crate's Cargo.toml version for a build from source: what `--version`, user +/// agents and reports say. +pub const VERSION: &str = match RELEASE { + Some(version) => version, + None => env!("CARGO_PKG_VERSION"), +}; + +#[cfg(test)] +mod tests { + #[test] + fn the_version_is_the_release_or_the_crate() { + assert_eq!( + super::RELEASE, + option_env!("HORIZON_VERSION").filter(|v| !v.is_empty()) + ); + assert_eq!( + super::VERSION, + super::RELEASE.unwrap_or(env!("CARGO_PKG_VERSION")) + ); + assert!(!super::VERSION.starts_with('v')); + } +} diff --git a/crates/horizon-port-pack/src/carry.rs b/crates/horizon-port-pack/src/carry.rs index dd6b148f3..e6056e519 100644 --- a/crates/horizon-port-pack/src/carry.rs +++ b/crates/horizon-port-pack/src/carry.rs @@ -707,7 +707,8 @@ pub fn carry( let mut biome_conventions = BTreeSet::new(); let set_tags = crate::worldgen::structure_set_tags(&mut zip); let piece_counts = crate::worldgen::piece_counts(&mut zip); - let processor_data = crate::processors::ProcessorData::read(&mut zip); + let mut processor_data = crate::processors::ProcessorData::read(&mut zip); + processor_data.mark_loaded(loaded); report.namespaces = extra_namespaces(&mut zip, id, pack.mods); let owned: Vec<&str> = std::iter::once(id.as_str()) .chain(report.namespaces.iter().map(String::as_str)) diff --git a/crates/horizon-port-pack/src/processors.rs b/crates/horizon-port-pack/src/processors.rs index 7f26282bf..e6c0fe7d8 100644 --- a/crates/horizon-port-pack/src/processors.rs +++ b/crates/horizon-port-pack/src/processors.rs @@ -16,6 +16,12 @@ //! `condition` become the game's `horizon:apply_random` and //! `horizon:condition`, with the lists inside them carried the same way, //! and its `set_block` (simple or weighted states) `horizon:set_block`. +//! - Repurposed Structures' mineshaft sky view becomes the game's +//! `horizon:mineshaft_sky_view`. +//! - Choice Theorem's Overhauled Village's `modular_compat` runs another +//! list only when the mod it names is loaded: that list is written in its +//! place when the mod is ported along, and it is taken out (a no-op, as in +//! the mod) when it is not. //! //! What is not here is taken out of its list later and counted //! (`worldgen::upgrade`). The entity NBT is written in 26.3's shape (an @@ -37,9 +43,37 @@ pub struct ProcessorData { pub replace_vanilla: BTreeSet<(String, String)>, /// The mod's processor lists by id, for Lithostitched's references. pub lists: BTreeMap, + /// The mods named by its `ctov:modular_compat` processors that are + /// ported along ([`Self::mark_loaded`]). + pub compat_loaded: BTreeSet, } +/// Choice Theorem's Overhauled Village's processor that runs the list +/// `reference` when mod `modid` is loaded (ModularCompatProcessor). +const MODULAR_COMPAT: &str = "ctov:modular_compat"; + impl ProcessorData { + /// Notes which mods its compat processors name are `loaded`. + pub fn mark_loaded(&mut self, loaded: &dyn Fn(&str) -> bool) { + fn walk(v: &Value, out: &mut BTreeSet) { + match v { + Value::Object(o) => { + if o.get("processor_type").and_then(Value::as_str) == Some(MODULAR_COMPAT) { + if let Some(id) = o.get("modid").and_then(Value::as_str) { + out.insert(id.to_owned()); + } + } + o.values().for_each(|v| walk(v, out)); + } + Value::Array(a) => a.iter().for_each(|v| walk(v, out)), + _ => {} + } + } + let mut named = BTreeSet::new(); + self.lists.values().for_each(|l| walk(l, &mut named)); + self.compat_loaded = named.into_iter().filter(|m| loaded(m)).collect(); + } + pub fn read(zip: &mut zip::ZipArchive) -> Self { let mut out = Self::default(); for i in 0..zip.len() { @@ -408,6 +442,17 @@ fn references( let mut out = Vec::with_capacity(list.len()); let mut changed = false; for p in list { + if p["processor_type"] == MODULAR_COMPAT && depth < 8 { + *carried.entry(MODULAR_COMPAT.into()).or_default() += 1; + changed = true; + let loaded = p["modid"] + .as_str() + .is_some_and(|m| data.compat_loaded.contains(m)); + if let Some(inner) = loaded.then(|| referenced(&p["reference"], data)).flatten() { + out.extend(references(inner, data, carried, depth + 1).0); + } + continue; + } let named = (p["processor_type"] == "lithostitched:reference" && depth < 8) .then(|| referenced(&p["processor_lists"], data)) .flatten(); @@ -491,6 +536,10 @@ fn as_data(kind: &str, p: &Value, data: &ProcessorData) -> Option> { "repurposed_structures:waterlogging_when_replacing_water_processor" => { vec![json!({"processor_type": "horizon:waterlog_in_world_water"})] } + // Its mineshafts: nothing above the ocean floor but grounded rails. + "repurposed_structures:mineshaft_sky_view_processor" => { + vec![json!({"processor_type": "horizon:mineshaft_sky_view"})] + } "moogs_structures:vanilla_loot_swap_processor" => { let key = ( p["modid"].as_str()?.to_owned(), @@ -1344,7 +1393,8 @@ mod tests { #[test] fn repurposed_waterlogging_follows_the_world() { let mut list = json!({"processors": [{"processor_type": - "repurposed_structures:waterlogging_when_replacing_water_processor"}]}); + "repurposed_structures:waterlogging_when_replacing_water_processor"}, + {"processor_type": "repurposed_structures:mineshaft_sky_view_processor"}]}); let mut carried = BTreeMap::new(); assert!(carry( "processor_list", @@ -1354,7 +1404,8 @@ mod tests { )); assert_eq!( list["processors"], - json!([{"processor_type": "horizon:waterlog_in_world_water"}]) + json!([{"processor_type": "horizon:waterlog_in_world_water"}, + {"processor_type": "horizon:mineshaft_sky_view"}]) ); } @@ -1391,6 +1442,27 @@ mod tests { assert_eq!(p[1]["processor_type"], "lithostitched:block_swap"); } + #[test] + fn modular_compat_runs_its_list_only_with_its_mod() { + let mut data = ProcessorData::default(); + let swap = json!({"processor_type": "minecraft:rule", "rules": []}); + data.lists + .insert("v:house_ns".into(), json!({"processors": [swap.clone()]})); + let compat = |m: &str| json!({"processor_type": "ctov:modular_compat", "modid": m, "reference": "v:house_ns"}); + let gravity = json!({"processor_type": "minecraft:gravity"}); + data.lists.insert( + "v:house".into(), + json!({"processors": [compat("ns"), compat("absent"), gravity.clone()]}), + ); + data.mark_loaded(&|m| m == "ns"); + assert_eq!(data.compat_loaded, BTreeSet::from(["ns".to_owned()])); + let mut v = json!({"processors": [compat("ns"), compat("absent"), gravity.clone()]}); + let mut carried = BTreeMap::new(); + assert!(carry("processor_list", &mut v, &data, &mut carried)); + assert_eq!(v, json!({"processors": [swap, gravity]})); + assert_eq!(carried["ctov:modular_compat"], 2); + } + #[test] fn lithostitched_references_are_written_in() { let mut data = data(); diff --git a/crates/horizon-port-pack/src/worldgen.rs b/crates/horizon-port-pack/src/worldgen.rs index 918dbf05e..91b659217 100644 --- a/crates/horizon-port-pack/src/worldgen.rs +++ b/crates/horizon-port-pack/src/worldgen.rs @@ -86,6 +86,31 @@ const YUNG_REPLACES: [(&str, &str); 7] = [ ("betterfortresses:fortress", "minecraft:fortress"), ("bettermineshafts:mineshaft_", "minecraft:mineshaft"), ]; +/// Mo' Structures' placement (`mostructures:type`) takes its spacing and +/// separation from the mod's config, not its files: the defaults it writes +/// (MoStructuresConfig), by config key, as (spacing, separation). +const MO_SPREADS: [(&str, i64, i64); 17] = [ + ("abandoned_church", 33, 20), + ("air_balloon", 22, 12), + ("barn_house", 32, 16), + ("big_pyramid", 32, 25), + ("ice_tower", 28, 20), + ("jungle_pyramid", 25, 22), + ("killer_bunny_castle", 32, 22), + ("lighthouse", 24, 14), + ("moai", 17, 15), + ("pillager_factory", 34, 16), + ("pillager_mines", 40, 27), + ("pirate_ship", 32, 16), + ("tavern", 26, 16), + ("the_castle_in_the_sky", 32, 22), + ("villager_market", 32, 16), + ("villager_tower", 26, 16), + ("sphinx", 24, 16), +]; +/// Mo' Structures keeps a start out of this many chunks around a start of +/// each set in its `structure_set_to_avoid`. +const MO_AVOID_CHUNKS: i64 = 3; /// Moog's Structure Lib spreads its structures 1.65 times as far apart as /// its files say (AdvancedRandomSpread's constructor). const MOOGS_SPACING: f64 = 1.65; @@ -510,12 +535,44 @@ fn upgrade_types( v["type"] = "minecraft:jigsaw".into(); true } + // Mo' Structures' ModStructure: vanilla's jigsaw that starts only + // where the terrain under the 5×5 chunks around varies by no + // more than `heightRange` blocks (-1: anywhere). + Some("mostructures:generic") => { + let range = v + .as_object_mut() + .and_then(|o| o.remove("heightRange")) + .and_then(|r| r.as_i64()) + .unwrap_or(-1); + if range >= 0 { + v["horizon:start_checks"] = + serde_json::json!({"terrain_radius": 2, "terrain_range": range}); + } + v["type"] = "minecraft:jigsaw".into(); + true + } // Formations' SimpleStructure: its pool and placement, laid out // by the game (`horizon_world::worldgen::structure::formations`). Some("formations:simple") => { v["type"] = "horizon:formations".into(); true } + // Its PiecedStructure: the same start, then vanilla's jigsaw + // (`horizon:pieced`). + Some("formations:pieced") => { + let Some(o) = v.as_object_mut() else { + return false; + }; + let pool = o.remove("start_pool").unwrap_or_default(); + let mut pieced = serde_json::Map::new(); + for k in ["max_depth", "max_distance_from_center"] { + pieced.insert(k.into(), o.remove(k).unwrap_or_default()); + } + o.insert("template".into(), pool); + o.insert("horizon:pieced".into(), pieced.into()); + o.insert("type".into(), "horizon:formations".into()); + true + } Some(t) if !t.starts_with("minecraft:") => { unsupported(t); false @@ -533,6 +590,7 @@ fn upgrade_types( p["type"] = "minecraft:random_spread".into(); true } + Some("mostructures:type") => mo_placement(&mut v["placement"], lost), Some(t) if YUNG_SPREADS.contains(&t) => { let t = t.to_owned(); yung_placement(&t, &mut v["placement"], set_tags, lost); @@ -1022,6 +1080,41 @@ fn placement_rules( } } +/// Mo' Structures' placement as vanilla's random spread: the spacing and +/// separation of its config key, and its sets to avoid as +/// `horizon:exclusion_zone` tested by their spread alone +/// (ModStructurePlacement.exclusionZoneCheck). A key the config does not +/// have fails the mod's codec, and the set stays as it is. +fn mo_placement(p: &mut Value, lost: &mut BTreeMap) -> bool { + let key = p["config_key"].as_str().unwrap_or_default(); + let Some(&(_, spacing, separation)) = MO_SPREADS.iter().find(|(k, ..)| *k == key) else { + *lost.entry("config_key".into()).or_default() += 1; + return false; + }; + let Some(o) = p.as_object_mut() else { + return false; + }; + o.remove("config_key"); + o.insert("spacing".into(), spacing.into()); + o.insert("separation".into(), separation.into()); + let avoid = o.remove("structure_set_to_avoid"); + let sets: Vec = avoid + .iter() + .flat_map(|a| a.as_array().into_iter().flatten()) + .filter(|s| s.is_string()) + .cloned() + .collect(); + if !sets.is_empty() { + o.insert( + "horizon:exclusion_zone".into(), + serde_json::json!({"other_sets": sets, "chunk_count": MO_AVOID_CHUNKS, + "their_zones": false}), + ); + } + o.insert("type".into(), "minecraft:random_spread".into()); + true +} + /// One of YUNG's placements as vanilla's random spread with `horizon:` keys: /// the enhanced exclusion zone as `horizon:exclusion_zone`; the temples' /// ocean and river search (findBiomeHorizontal around the chunk's middle @@ -1222,6 +1315,21 @@ mod tests { const NO_TAGS: BTreeMap> = BTreeMap::new(); + #[test] + fn formations_pieced_structure_keeps_its_jigsaw() { + let mut v = json!({"type": "formations:pieced", "start_pool": "fo:fountain/fountains", + "max_depth": 2, "max_distance_from_center": 116, "placement": "surface"}); + let mut report = Upgrade::default(); + assert!(upgrade("structure", &mut v, &mut report, &BTreeMap::new())); + assert_eq!( + v, + json!({"type": "horizon:formations", "template": "fo:fountain/fountains", + "placement": "surface", + "horizon:pieced": {"max_depth": 2, "max_distance_from_center": 116}}) + ); + assert!(report.unsupported.is_empty()); + } + #[test] fn formations_become_the_games() { let mut report = Upgrade::default(); @@ -1247,12 +1355,7 @@ mod tests { (json!(6), json!(1)) ); assert!(e(0).get("ground_level").is_none()); - // The pieced structure stays out. - let mut pieced = json!({"type": "formations:pieced", "start_pool": "f:p", "max_depth": 2, - "max_distance_from_center": 40, "placement": "surface", "biomes": "#f:x"}); - assert!(!upgrade("structure", &mut pieced, &mut report, &NO_TAGS)); - assert_eq!(report.unsupported.get("formations:pieced"), Some(&1)); - assert_eq!(report.unsupported.len(), 1); + assert!(report.unsupported.is_empty()); } #[test] @@ -1385,6 +1488,71 @@ mod tests { ); } + #[test] + fn mo_structures_become_vanillas_jigsaw_and_spread() { + let mut report = Upgrade::default(); + let mut s = json!({"type": "mostructures:generic", "start_pool": "mostructures:a/base", + "size": 7, "heightRange": 25, "use_expansion_hack": true, + "start_height": {"absolute": 0}, "max_distance_from_center": 80}); + assert!(upgrade("structure", &mut s, &mut report, &BTreeMap::new())); + assert_eq!(s["type"], "minecraft:jigsaw"); + assert!(s.get("heightRange").is_none()); + assert_eq!( + s["horizon:start_checks"], + json!({"terrain_radius": 2, "terrain_range": 25}) + ); + let mut anywhere = json!({"type": "mostructures:generic", "heightRange": -1}); + assert!(upgrade( + "structure", + &mut anywhere, + &mut report, + &BTreeMap::new() + )); + assert!(anywhere.get("horizon:start_checks").is_none()); + + // The config's spacing and separation, not the file's. + let mut set = json!({"placement": {"type": "mostructures:type", "config_key": "moai", + "salt": 12994829, "spacing": 17, "separation": 15, + "structure_set_to_avoid": ["minecraft:villages", "mostructures:lighthouse"]}}); + assert!(upgrade( + "structure_set", + &mut set, + &mut report, + &BTreeMap::new() + )); + assert_eq!( + set["placement"], + json!({"type": "minecraft:random_spread", "salt": 12994829, "spacing": 17, + "separation": 15, "horizon:exclusion_zone": {"chunk_count": 3, + "other_sets": ["minecraft:villages", "mostructures:lighthouse"], + "their_zones": false}}) + ); + let mut set = json!({"placement": {"type": "mostructures:type", + "config_key": "jungle_pyramid", "salt": 1, "spacing": 16, "separation": 14}}); + assert!(upgrade( + "structure_set", + &mut set, + &mut report, + &BTreeMap::new() + )); + assert_eq!( + ( + &set["placement"]["spacing"], + &set["placement"]["separation"] + ), + (&json!(25), &json!(22)) + ); + assert!(set["placement"].get("horizon:exclusion_zone").is_none()); + let mut unknown = json!({"placement": {"type": "mostructures:type", "config_key": "x"}}); + assert!(!upgrade( + "structure_set", + &mut unknown, + &mut report, + &BTreeMap::new() + )); + assert_eq!(report.rules_lost["config_key"], 1); + } + #[test] fn super_exclusion_zones_name_their_sets() { let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); diff --git a/crates/horizon-prepare/src/main.rs b/crates/horizon-prepare/src/main.rs index 0e8adc927..71b7a40cc 100644 --- a/crates/horizon-prepare/src/main.rs +++ b/crates/horizon-prepare/src/main.rs @@ -5,6 +5,13 @@ use std::io::Write; use std::path::{Path, PathBuf}; use std::process::ExitCode; +/// This release's version: release.yml builds it with `HORIZON_VERSION` from the tag +/// (docs/versioning.md); a build from source says Cargo.toml's. +const VERSION: &str = match option_env!("HORIZON_VERSION") { + Some(version) if !version.is_empty() => version, + _ => env!("CARGO_PKG_VERSION"), +}; + const HELP: &str = "\ horizon-prepare: prepare Horizon's resources from your own Minecraft Java Edition @@ -92,7 +99,7 @@ fn main() -> ExitCode { return ExitCode::SUCCESS; } "-V" | "--version" => { - println!("horizon-prepare {}", env!("CARGO_PKG_VERSION")); + println!("horizon-prepare {VERSION}"); return ExitCode::SUCCESS; } _ => Err(format!("unrecognized argument: {text}")), diff --git a/crates/horizon-protocol/src/item.rs b/crates/horizon-protocol/src/item.rs index 90ea5b6cd..02c9e4966 100644 --- a/crates/horizon-protocol/src/item.rs +++ b/crates/horizon-protocol/src/item.rs @@ -28,6 +28,21 @@ pub mod component { pub const STORED_ENCHANTMENTS: i32 = 45; pub const DYED_COLOR: i32 = 47; pub const MAP_ID: i32 = 48; + pub const MAP_POST_PROCESSING: i32 = 50; + pub const WRITABLE_BOOK_CONTENT: i32 = 56; + pub const WRITTEN_BOOK_CONTENT: i32 = 57; +} + +/// A written book's content (`WrittenBookContent.STREAM_CODEC`): the +/// filtered variants of the title and pages are read and dropped. +#[derive(Clone, Debug, PartialEq)] +pub struct WrittenBook { + pub title: String, + pub author: String, + pub generation: i32, + /// Each page's text component. + pub pages: Vec, + pub resolved: bool, } /// The value of one patched data component. Components whose stream codec @@ -52,13 +67,49 @@ pub enum Component { hide: bool, hidden: Vec, }, + /// `WritableBookContent`: the pages (raw text). + WritableBook(Vec), + WrittenBook(WrittenBook), +} + +/// `Filterable.streamCodec`: the raw value, then an optional filtered one +/// (dropped). +fn filterable(r: &mut Reader, value: impl Fn(&mut Reader) -> Result) -> Result { + let raw = value(r)?; + if r.bool()? { + value(r)?; + } + Ok(raw) } impl Component { fn read(kind: i32, r: &mut Reader) -> Result { use component::*; Ok(match kind { - MAX_STACK_SIZE | MAX_DAMAGE | DAMAGE | RARITY | REPAIR_COST | MAP_ID => { - Self::Int(r.varint()?) + MAX_STACK_SIZE | MAX_DAMAGE | DAMAGE | RARITY | REPAIR_COST | MAP_ID + | MAP_POST_PROCESSING => Self::Int(r.varint()?), + WRITABLE_BOOK_CONTENT => { + let n = r.count(100)?; + Self::WritableBook( + (0..n) + .map(|_| filterable(r, |r| r.string(1024))) + .collect::>()?, + ) + } + WRITTEN_BOOK_CONTENT => { + let title = filterable(r, |r| r.string(32))?; + let author = r.string(32767)?; + let generation = r.varint()?; + let n = r.count(r.remaining())?; + let pages = (0..n) + .map(|_| filterable(r, |r| r.nbt())) + .collect::>()?; + Self::WrittenBook(WrittenBook { + title, + author, + generation, + pages, + resolved: r.bool()?, + }) } DYED_COLOR => Self::Int(r.i32()?), UNBREAKABLE | CREATIVE_SLOT_LOCK => Self::Unit, @@ -144,6 +195,25 @@ impl Component { w.varint(hidden.len() as i32); hidden.iter().for_each(|h| w.varint(*h)); } + Self::WritableBook(pages) => { + w.varint(pages.len() as i32); + for page in pages { + w.string(page); + w.bool(false); + } + } + Self::WrittenBook(b) => { + w.string(&b.title); + w.bool(false); + w.string(&b.author); + w.varint(b.generation); + w.varint(b.pages.len() as i32); + for page in &b.pages { + w.nbt(page); + w.bool(false); + } + w.bool(b.resolved); + } } } } @@ -349,12 +419,43 @@ mod tests { Component::Lore(vec![literal("a"), literal("b")]), )); sword.removed.push(component::REPAIR_COST); + let mut book = Stack::new(1100, 1); + book.added.push(( + component::WRITTEN_BOOK_CONTENT, + Component::WrittenBook(WrittenBook { + title: "Notes".into(), + author: "Guest".into(), + generation: 1, + pages: vec![literal("one"), literal("two")], + resolved: true, + }), + )); + book.added + .push((component::MAP_POST_PROCESSING, Component::Int(1))); + round::, Slot>(Some(book)); + let mut quill = Stack::new(1099, 1); + quill.added.push(( + component::WRITABLE_BOOK_CONTENT, + Component::WritableBook(vec!["a".into(), String::new()]), + )); + round::, Slot>(Some(quill)); assert_eq!(sword.damage(), 17); round::, Slot>(Some(sword.clone())); round::, HashedSlot>(Some(Hashed::of(&sword))); round::, HashedSlot>(None); } + #[test] + fn filtered_book_pages_are_read_and_dropped() { + // A writable book with one page "hi" and its filtered "**". + let bytes = [1, 7, 1, 0, 56, 1, 2, b'h', b'i', 1, 2, b'*', b'*']; + let stack = Slot::read(&mut Reader::new(&bytes)).unwrap().unwrap(); + assert_eq!( + stack.component(component::WRITABLE_BOOK_CONTENT), + Some(&Component::WritableBook(vec!["hi".into()])) + ); + } + #[test] fn empty_stack_is_a_zero_count() { let mut w = Writer::new(); diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 95a68d1ef..bfda58e9b 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -1674,6 +1674,8 @@ packet!( ); packet!(ChangeDifficultyRequest { difficulty: i32 => VarInt }); packet!(LockDifficulty { locked: bool => Bool }); +// ServerboundPlayerAbilitiesPacket: only whether the player flies (2). +packet!(PlayerAbilitiesRequest { flags: i8 => Byte }); packet!(SetGameRule { entries: Vec => List }); packet!(ChunkBatchReceived { chunks_per_tick: f32 => Float }); packet!( @@ -1710,6 +1712,25 @@ packet!( } ); packet!(SelectTrade { item: i32 => VarInt }); +packet!( + /// ServerboundContainerButtonClickPacket: `AbstractContainerMenu.clickMenuButton` + /// (the loom's patterns, the stonecutter's recipes, the enchanting table's offers). + ContainerButtonClick { container: i32 => VarInt, button: i32 => VarInt } +); +packet!( + /// ServerboundContainerSlotStateChangedPacket: the crafter's slot toggle + /// (`CrafterBlockEntity.setSlotState`). + ContainerSlotStateChanged { slot: i32 => VarInt, container: i32 => VarInt, enabled: bool => Bool } +); +packet!( + /// ServerboundRenameItemPacket: `AnvilMenu.setItemName`. + RenameItem { name: String => Str } +); +packet!( + /// ServerboundSetBeaconPacket: `BeaconMenu.updateEffects`, each power an + /// optional `mob_effect` id. + SetBeacon { primary: Option => Opt, secondary: Option => Opt } +); packet!(Interact { id: i32 => VarInt, hand: i32 => VarInt, location: [f64; 3] => LpVec3, secondary: bool => Bool }); packet!( /// ServerboundMovePlayerPacket flags: 1 on ground, 2 horizontal collision. @@ -1775,6 +1796,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound { ClientInformation(ClientInformation) = CLIENT_INFORMATION, ClientTickEnd(Empty) = CLIENT_TICK_END, ConfigurationAcknowledged(Empty) = CONFIGURATION_ACKNOWLEDGED, + ContainerButtonClick(ContainerButtonClick) = CONTAINER_BUTTON_CLICK, ContainerClick(ContainerClick) = CONTAINER_CLICK, ContainerClose(ContainerClose) = CONTAINER_CLOSE, CustomPayload(CustomPayload) = CUSTOM_PAYLOAD, @@ -1786,14 +1808,18 @@ packet_enum!(Serverbound, crate::ids::play::serverbound { MovePlayerStatus(MovePlayerStatus) = MOVE_PLAYER_STATUS_ONLY, PickItemFromBlock(PickItemFromBlock) = PICK_ITEM_FROM_BLOCK, PingRequest(crate::packets::status::Ping) = PING_REQUEST, + PlayerAbilities(PlayerAbilitiesRequest) = PLAYER_ABILITIES, PlayerAction(PlayerAction) = PLAYER_ACTION, PlayerCommand(PlayerCommand) = PLAYER_COMMAND, PlayerInput(PlayerInput) = PLAYER_INPUT, PlayerLoaded(Empty) = PLAYER_LOADED, Pong(Ping) = PONG, + RenameItem(RenameItem) = RENAME_ITEM, + ContainerSlotStateChanged(ContainerSlotStateChanged) = CONTAINER_SLOT_STATE_CHANGED, Punch(Empty) = PUNCH, ResourcePack(ResourcePackResponse) = RESOURCE_PACK, SelectTrade(SelectTrade) = SELECT_TRADE, + SetBeacon(SetBeacon) = SET_BEACON, SetCarriedItem(SetCarriedItem) = SET_CARRIED_ITEM, SetCreativeModeSlot(SetCreativeModeSlot) = SET_CREATIVE_MODE_SLOT, UseItem(UseItem) = USE_ITEM, @@ -1805,6 +1831,17 @@ mod tests { use super::*; use crate::{chunk::BlockEntityInfo, packets::round_trip, text::literal}; + #[test] + fn serverbound_abilities_carry_only_flying() { + // ServerboundPlayerAbilitiesPacket.write: one byte, 2 when flying. + let flying = Serverbound::PlayerAbilities(PlayerAbilitiesRequest { flags: 2 }); + assert_eq!( + flying.encode(), + [crate::ids::play::serverbound::PLAYER_ABILITIES as u8, 2] + ); + round_trip(flying, Serverbound::encode, Serverbound::decode); + } + #[test] fn world_options_packets_match_vanilla_stream_codecs() { // mcsrc.dev 26.3: difficulty is a VarInt, locking is a Boolean, @@ -2360,6 +2397,34 @@ mod tests { Serverbound::encode, Serverbound::decode, ); + // CONTAINER_ID and the button, both VarInts. + let button = Serverbound::ContainerButtonClick(ContainerButtonClick { + container: 3, + button: 200, + }); + assert_eq!(&button.encode()[1..], &[3, 0xC8, 1]); + round_trip(button, Serverbound::encode, Serverbound::decode); + // The name, a UTF-8 string with its VarInt length. + let rename = Serverbound::RenameItem(RenameItem { + name: "Blade".into(), + }); + assert_eq!(&rename.encode()[1..], &[5, b'B', b'l', b'a', b'd', b'e']); + round_trip(rename, Serverbound::encode, Serverbound::decode); + // The slot, the container id (VarInts), then the new state. + let toggle = Serverbound::ContainerSlotStateChanged(ContainerSlotStateChanged { + slot: 4, + container: 2, + enabled: false, + }); + assert_eq!(&toggle.encode()[1..], &[4, 2, 0]); + round_trip(toggle, Serverbound::encode, Serverbound::decode); + // Two optional mob effect ids: a presence byte, then the VarInt. + let beacon = Serverbound::SetBeacon(SetBeacon { + primary: Some(2), + secondary: None, + }); + assert_eq!(&beacon.encode()[1..], &[1, 2, 0]); + round_trip(beacon, Serverbound::encode, Serverbound::decode); } #[test] diff --git a/crates/horizon-server-files/src/profiles.rs b/crates/horizon-server-files/src/profiles.rs index 3e16e2a41..3f7e2e509 100644 --- a/crates/horizon-server-files/src/profiles.rs +++ b/crates/horizon-server-files/src/profiles.rs @@ -45,7 +45,7 @@ pub fn resolve(name: &str, online: bool) -> Option { pub fn find_by_name(discovery: &str, name: &str) -> Option { let agent = ureq::AgentBuilder::new() .timeout(Duration::from_secs(15)) - .user_agent(concat!("Horizon/", env!("CARGO_PKG_VERSION"))) + .user_agent(&format!("Horizon/{}", horizon_core::release::VERSION)) .build(); let doc = json::parse(&agent.get(discovery).call().ok()?.into_string().ok()?, true).ok()?; let url = endpoint(&doc, "profiles", "getByName")?.replace("{name}", &name.to_lowercase()); @@ -61,7 +61,7 @@ pub fn fetch_profile_key_keys(discovery: &str) -> Result, &'st const FAILED: &str = "Failed to request Minecraft Services public key"; let agent = ureq::AgentBuilder::new() .timeout(Duration::from_secs(15)) - .user_agent(concat!("Horizon/", env!("CARGO_PKG_VERSION"))) + .user_agent(&format!("Horizon/{}", horizon_core::release::VERSION)) .build(); let get = |url: &str| agent.get(url).call().ok()?.into_string().ok(); let doc = get(discovery) diff --git a/crates/horizon-server/src/api.rs b/crates/horizon-server/src/api.rs index 03f7ae079..c9e553fab 100644 --- a/crates/horizon-server/src/api.rs +++ b/crates/horizon-server/src/api.rs @@ -286,7 +286,7 @@ fn status(shared: &Shared) -> Value { let state = shared.state.lock().unwrap(); json!({ "phase": state.phase.name(), - "version": env!("CARGO_PKG_VERSION"), + "version": crate::VERSION, "pid": std::process::id(), "uptime_seconds": shared.started.elapsed().as_secs(), "engine_pid": state.engine_pid, diff --git a/crates/horizon-server/src/main.rs b/crates/horizon-server/src/main.rs index 627961d81..b4512530c 100644 --- a/crates/horizon-server/src/main.rs +++ b/crates/horizon-server/src/main.rs @@ -18,6 +18,13 @@ mod update; use std::{path::PathBuf, process::ExitCode}; +/// This release's version: release.yml builds it with `HORIZON_VERSION` from the tag +/// (docs/versioning.md); a build from source says Cargo.toml's. +const VERSION: &str = match option_env!("HORIZON_VERSION") { + Some(version) if !version.is_empty() => version, + _ => env!("CARGO_PKG_VERSION"), +}; + const HELP: &str = "\ horizon-server: host a Horizon (Minecraft Java Edition 26.3) server @@ -86,7 +93,7 @@ fn main() -> ExitCode { Ok(()) } Some("version" | "-V" | "--version") => { - println!("horizon-server {}", env!("CARGO_PKG_VERSION")); + println!("horizon-server {VERSION}"); Ok(()) } Some("init") => init_answers(&args[1..]).and_then(|a| init::run(&dir, a)), diff --git a/crates/horizon-shaderpack/src/preprocess.rs b/crates/horizon-shaderpack/src/preprocess.rs index 18c890496..8a0c4e694 100644 --- a/crates/horizon-shaderpack/src/preprocess.rs +++ b/crates/horizon-shaderpack/src/preprocess.rs @@ -6,8 +6,9 @@ use crate::include::Inlined; use pp_rs::{ pp::Preprocessor, - token::{Punct, TokenValue}, + token::{PreprocessorError, Punct, TokenValue}, }; +use std::collections::HashMap; /// The version of Minecraft packs are told they run on (`MC_VERSION`, /// Iris's `formatVersionString("26.3")`). @@ -286,14 +287,176 @@ fn mark_comments(text: &str) -> (String, Vec) { (out, comments) } +/// Whether trimmed `line` is an `#if` or `#elif` directive. +pub(crate) fn is_condition(line: &str) -> bool { + line.strip_prefix('#') + .map(str::trim_start) + .and_then(|d| d.strip_prefix("elif").or_else(|| d.strip_prefix("if"))) + .is_some_and(|r| !r.starts_with(|c: char| c.is_ascii_alphanumeric() || c == '_')) +} + +/// Whether `word` is a float literal. +pub(crate) fn is_float(word: &str) -> bool { + word.starts_with(|c: char| c.is_ascii_digit() || c == '.') + && !word.starts_with("0x") + && !word.starts_with("0X") + && word.contains(['.', 'e', 'E']) +} + +/// What JCPP's `#if` makes of a number (`Preprocessor.expr` takes +/// `NumericValue.longValue`): a float counts as its integer part, so +/// `0.75` is 0 and `1.5e1` is 10. `None` for a non-number. +pub(crate) fn jcpp_integer(number: &str) -> Option { + let number = number.trim_end_matches(['f', 'F', 'l', 'L', 'u', 'U']); + let (mantissa, exponent) = match number.find(['e', 'E']) { + Some(i) => (&number[..i], number[i + 1..].parse::().ok()?), + None => (number, 0), + }; + let integer = mantissa.split('.').next()?; + let value = if integer.is_empty() { + 0 + } else { + integer.parse::().ok()? + }; + Some((value as f64 * 10f64.powi(exponent)) as i64) +} + +/// `line` with each word (identifier or number, with an exponent's sign: +/// `1e-3`) replaced by what `f` returns for it, if anything. The directive's +/// name and the names after `defined` are kept. +pub(crate) fn rewrite_condition(line: &str, f: impl Fn(&str) -> Option) -> String { + let mut out = String::with_capacity(line.len()); + let (mut rest, mut first, mut after_defined) = (line, true, false); + while let Some(c) = rest.chars().next() { + if !(c.is_ascii_alphanumeric() || c == '_' || c == '.') { + if !c.is_whitespace() && c != '(' && c != '#' { + after_defined = false; + } + out.push(c); + rest = &rest[c.len_utf8()..]; + continue; + } + let bytes = rest.as_bytes(); + let mut len = 0; + while let Some(&b) = bytes.get(len) { + let sign = (b == b'+' || b == b'-') + && bytes[0].is_ascii_digit() + && matches!(bytes[len - 1], b'e' | b'E'); + if !(b.is_ascii_alphanumeric() || b == b'_' || b == b'.' || sign) { + break; + } + len += 1; + } + let word = &rest[..len]; + let kept = first || after_defined; + match (!kept).then(|| f(word)).flatten() { + Some(replacement) => out.push_str(&replacement), + None => out.push_str(word), + } + after_defined = word == "defined"; + first = false; + rest = &rest[len..]; + } + out +} + +/// Make pp-rs read `text` as JCPP, Iris's preprocessor, does: +/// - a `#define` replaces an earlier macro (`Preprocessor.addMacro`; Bloop +/// and Steadfast redefine theirs), where pp-rs refuses a different +/// redefinition: an `#undef` line goes before every `#define`; +/// - in `#if`/`#elif`, a float counts as its integer part, and so does a +/// macro always defined as the same float (an option: `#define LEVEL 0.5`); +/// a macro always defined empty (Iris's `MC_GL_VENDOR_OTHER`, Bloop's +/// `#define TAA_USE_YCOCG`) counts as 0: JCPP reports the missing operand +/// and goes on with 0. pp-rs stops on both; +/// - `#error "..."` (Photon's guard in programs it disables) lexes: pp-rs +/// has no string tokens and fails on the quote, even in a skipped block. +/// +/// Returns the text and the added lines' 1-based numbers in it. +fn jcpp_compatible(text: &str, env: &Environment) -> (String, Vec) { + // A `#define` line's name and body. + let define = |l: &str| { + let rest = l + .trim_start() + .strip_prefix('#')? + .trim_start() + .strip_prefix("define") + .filter(|rest| rest.starts_with([' ', '\t']))? + .trim_start(); + let end = rest + .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) + .unwrap_or(rest.len()); + let (name, body) = rest.split_at(end); + let body = body.split("//").next().unwrap_or("").trim(); + (!name.is_empty()).then(|| (name.to_owned(), body.to_owned())) + }; + // Each macro's body, if every definition has the same one. + let mut bodies: HashMap> = HashMap::new(); + let definitions = env + .defines + .iter() + .cloned() + .chain(text.lines().filter_map(define)); + for (name, body) in definitions { + bodies + .entry(name) + .and_modify(|b| { + if b.as_ref() != Some(&body) { + *b = None; + } + }) + .or_insert(Some(body)); + } + let number = |word: &str| -> Option { + let word = match bodies.get(word) { + Some(Some(body)) if body.is_empty() => return Some("0".into()), + Some(Some(body)) => body.as_str(), + Some(None) => return None, + None => word, + }; + is_float(word) + .then(|| jcpp_integer(word)) + .flatten() + .map(|n| n.to_string()) + }; + let mut out = String::with_capacity(text.len() + text.len() / 16); + let mut added = Vec::new(); + let (mut line, mut continued) = (1, false); + for l in text.split_inclusive('\n') { + if !continued && let Some((name, _)) = define(l) { + out.push_str(&format!("#undef {name}\n")); + added.push(line); + line += 1; + } + let directive = l.trim_start().strip_prefix('#').map(str::trim_start); + if !continued + && directive.is_some_and(|d| d.starts_with("error") || d.starts_with("warning")) + { + out.push_str(&l.replace(['"', '\''], "")); + } else if !continued && is_condition(l.trim_start()) { + out.push_str(&rewrite_condition(l, number)); + } else { + out.push_str(l); + } + continued = l.trim_end().ends_with('\\'); + line += 1; + } + (out, added) +} + /// Expand `source` with `env`'s macros. Errors name the file and line. pub fn preprocess(source: &Inlined, env: &Environment) -> Result { let (marked, comments) = mark_comments(&source.text); - let text = &marked; + let (text, added) = jcpp_compatible(&marked, env); + let text = &text; let line_starts: Vec = std::iter::once(0) .chain(text.match_indices('\n').map(|(i, _)| i + 1)) .collect(); - let line_of = |offset: u32| line_starts.partition_point(|&s| s <= offset as usize) as u32; + // Lines of the source: the added `#undef` lines don't count. + let line_of = |offset: u32| { + let line = line_starts.partition_point(|&s| s <= offset as usize) as u32; + line - added.partition_point(|&a| a < line) as u32 + }; let mut pp = Preprocessor::new(text); for (name, value) in &env.defines { pp.add_define(name, value) @@ -307,8 +470,15 @@ pub fn preprocess(source: &Inlined, env: &Environment) -> Result break, + item => { + item.map_err(|(e, at)| format!("{}: {e:?}", source.locate(line_of(at.start))))? + } + }; let at = line_of(token.location.start); let piece = match token.value { TokenValue::Version(v) => { diff --git a/crates/horizon-shaderpack/src/properties.rs b/crates/horizon-shaderpack/src/properties.rs index 8c3f29c8f..3c6ee251c 100644 --- a/crates/horizon-shaderpack/src/properties.rs +++ b/crates/horizon-shaderpack/src/properties.rs @@ -6,7 +6,7 @@ //! so `#if` blocks pick the directives that apply. use crate::options::{OptionSet, OptionValues}; -use crate::preprocess::Environment; +use crate::preprocess::{Environment, is_condition, is_float, jcpp_integer, rewrite_condition}; use pp_rs::{pp::Preprocessor, token::TokenValue}; use std::collections::BTreeMap; @@ -120,9 +120,32 @@ const DIRECTIVES: &[&str] = &[ "#warning", "#pragma", "#line", "#include", ]; +/// An `#if`/`#elif` line with its floats as JCPP reads them (Steadfast tests +/// `#if ATMOSPHERE_FOG_STRENGTH_NOON == 0.75` with the option at 0.5, which +/// Iris reads as `0 == 0`): float literals and the options set to a float +/// become their integer part. +fn jcpp_condition(line: &str, options: &OptionSet, values: &OptionValues) -> String { + rewrite_condition(line, |word| { + let value = match options.strings.get(word) { + Some(o) => values.strings.get(word).unwrap_or(&o.default).as_str(), + None => word, + }; + is_float(value) + .then(|| jcpp_integer(value)) + .flatten() + .map(|n| n.to_string()) + }) +} + +/// What backslashes are while the macros expand, as in Iris: the +/// preprocessor must not join a `\`-continued value with the directive on +/// the next line (Photon ends an `#if`'d value with `) \` before `#else`). +const BACKSLASH: &str = "IRIS_PASSTHROUGHBACKSLASH"; + /// `PropertiesPreprocessor.preprocessSource`: comment lines dropped, other -/// `#`s removed, then the macros expanded. Tokens keep their source spelling -/// and spacing (`0.50` stays `0.50`, `` stays one word). +/// `#`s removed, then the macros expanded with the backslashes hidden. +/// Tokens keep their source spelling and spacing (`0.50` stays `0.50`, +/// `` stays one word). pub fn preprocess( text: &str, env: &Environment, @@ -132,7 +155,6 @@ pub fn preprocess( let filtered: String = text .lines() .map(str::trim) - .filter(|l| !l.is_empty()) .map(|l| match l.starts_with('#') { // JCPP lets a #define replace a macro (Complementary sets // COLORED_LIGHTING 0 on macOS); pp-rs refuses, so undefine first. @@ -142,11 +164,12 @@ pub fn preprocess( None => l.to_owned(), } } + true if is_condition(l) => jcpp_condition(l, options, values), true if DIRECTIVES.iter().any(|d| l.starts_with(d)) => l.to_owned(), true => String::new(), false => l.replace('#', ""), }) - .map(|l| l + "\n") + .map(|l| l.replace('\\', BACKSLASH) + "\n") .collect(); let mut pp = Preprocessor::new(&filtered); let mut define = |name: &str, value: &str| { @@ -202,7 +225,7 @@ pub fn preprocess( }); } out.push('\n'); - Ok(out) + Ok(out.replace(BACKSLASH, "\\")) } /// One element of an option screen (`OptionMenuElement`). @@ -698,6 +721,39 @@ mod tests { ); } + #[test] + fn floats_in_conditions_count_as_their_integer_part() { + assert_eq!( + [".5", "0.75", "1.0", "2.5f", "1.5e1", "7", "0x10"].map(jcpp_integer), + [Some(0), Some(0), Some(1), Some(2), Some(10), Some(7), None] + ); + // Steadfast's fog strength: the option is 0.5, so Iris takes the + // 0.75 branch (0 == 0). + let set = options(&["#define FOG 0.5 // [0.0 0.5 0.75 1.0]"]); + let text = "\ +#if FOG == 1.0 +a = 1 +#elif FOG == 0.75 +a = 0.75 +#else +a = 0.5 +#endif +#if(FOG<1e1) +b = 1 +#endif +"; + let env = Environment { + defines: Vec::new(), + }; + let values = OptionValues::default(); + let out = preprocess(text, &env, &set, &values).unwrap(); + assert_eq!(out, "a = 0.75\nb = 1\n"); + assert_eq!( + jcpp_condition("#elif FOG == 0.75 && X > 2.5", &set, &values), + "#elif 0 == 0 && X > 2" + ); + } + #[test] fn boolean_expressions() { let set = options(&["#define A", "//#define B", "#define C"]); diff --git a/crates/horizon-shaderpack/src/translate.rs b/crates/horizon-shaderpack/src/translate.rs index f9a61169e..8a32795af 100644 --- a/crates/horizon-shaderpack/src/translate.rs +++ b/crates/horizon-shaderpack/src/translate.rs @@ -18,7 +18,11 @@ //! swizzled shadow lookup is widened first (naga has no scalar swizzle); //! - global initialisers run at the start of `main` (drivers accept //! non-constant ones), unsized global arrays are sized from them; -//! - `isnan`, `isinf` and `modf` are helper functions (WGSL has none). +//! - `isnan`, `isinf` and `modf` are helper functions (WGSL has none); +//! - what naga refuses and drivers accept: `%` goes through overloads (naga +//! won't take `ivec2 % int`), `sqrt` of a negative constant isn't folded, +//! constants naga can't fold (`?:`, `mix`) become globals set in `main`, +//! and 16/8-bit types are their 32-bit ones. //! //! The programs of one pass share a [`Link`], so their locations, bindings and //! uniform block agree. @@ -234,6 +238,106 @@ vec3 iris_modf(vec3 x, out vec3 i) { i = trunc(x); return x - i; } vec4 iris_modf(vec4 x, out vec4 i) { i = trunc(x); return x - i; } "; +/// A fragment output narrower than four channels (`out vec3 color`, +/// Steadfast's `final`): the four-channel type it is written through and the +/// epilogue line that fills it, with alpha 1 and the rest 0. `None` when the +/// output already has four channels. +fn widen_output(ty: &str, name: &str) -> Option<(String, String)> { + let (wide, one, zero) = match ty { + "float" | "vec2" | "vec3" => ("vec4", "1.0", "0.0"), + "int" | "ivec2" | "ivec3" => ("ivec4", "1", "0"), + "uint" | "uvec2" | "uvec3" => ("uvec4", "1u", "0u"), + _ => return None, + }; + let channels = match ty.chars().last() { + Some('2') => 2, + Some('3') => 3, + _ => 1, + }; + let mut parts = vec![name.to_owned()]; + parts.extend((channels..3).map(|_| zero.to_owned())); + parts.push(one.to_owned()); + Some(( + wide.to_owned(), + format!("iris_out_{name} = {wide}({});", parts.join(", ")), + )) +} + +/// `%` as overloads: naga's GLSL front end splats a scalar operand for +/// `+ - / & ^ |` but not for `%`, and rejects `ivec2(uv) % 256` (Noble). +fn modulo_helpers() -> String { + let mut out = String::new(); + for (s, v) in [("int", "ivec"), ("uint", "uvec")] { + out.push_str(&format!("{s} iris_mod({s} a, {s} b) {{ return a % b; }}\n")); + for n in 2..=4 { + let v = format!("{v}{n}"); + out.push_str(&format!("{v} iris_mod({v} a, {v} b) {{ return a % b; }}\n")); + out.push_str(&format!( + "{v} iris_mod({v} a, {s} b) {{ return a % {v}(b); }}\n" + )); + out.push_str(&format!( + "{v} iris_mod({s} a, {v} b) {{ return {v}(a) % b; }}\n" + )); + } + } + out +} + +/// 16- and 8-bit types (`GL_NV_gpu_shader5`, `GL_EXT_shader_explicit_arithmetic_types`) +/// and their built-ins, as the 32-bit ones WGSL has: Noble declares +/// `u16vec2` & co. when Iris reports an NVIDIA GPU, and falls back to these +/// same aliases elsewhere. +const SMALL_TYPES: &[(&str, &str)] = &[ + ("float16_t", "float"), + ("f16vec2", "vec2"), + ("f16vec3", "vec3"), + ("f16vec4", "vec4"), + ("int16_t", "int"), + ("i16vec2", "ivec2"), + ("i16vec3", "ivec3"), + ("i16vec4", "ivec4"), + ("uint16_t", "uint"), + ("u16vec2", "uvec2"), + ("u16vec3", "uvec3"), + ("u16vec4", "uvec4"), + ("int8_t", "int"), + ("i8vec2", "ivec2"), + ("i8vec3", "ivec3"), + ("i8vec4", "ivec4"), + ("uint8_t", "uint"), + ("u8vec2", "uvec2"), + ("u8vec3", "uvec3"), + ("u8vec4", "uvec4"), + ("packFloat2x16", "packHalf2x16"), + ("unpackFloat2x16", "unpackHalf2x16"), +]; + +/// `source` with [`SMALL_TYPES`] replaced, word by word. +fn widen_small_types(source: &str) -> std::borrow::Cow<'_, str> { + if !SMALL_TYPES.iter().any(|(t, _)| source.contains(t)) { + return source.into(); + } + let mut out = String::with_capacity(source.len()); + let mut rest = source; + while let Some(c) = rest.chars().next() { + let len = if c.is_ascii_alphanumeric() || c == '_' { + rest.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) + .unwrap_or(rest.len()) + } else { + c.len_utf8() + }; + let word = &rest[..len]; + out.push_str( + SMALL_TYPES + .iter() + .find(|(t, _)| *t == word) + .map_or(word, |(_, w)| w), + ); + rest = &rest[len..]; + } + out.into() +} + /// Translate one preprocessed program. `locate` turns a line of `source` /// into `file:line` for errors. pub fn translate( @@ -248,7 +352,8 @@ pub fn translate( Stage::Compute => naga::ShaderStage::Compute, _ => return Err(format!("{stage:?} programs are not supported")), }; - let mut unit = ast::TranslationUnit::parse(source).map_err(|e| { + let source = widen_small_types(source); + let mut unit = ast::TranslationUnit::parse(&source).map_err(|e| { let line = e.line() + 1; format!("{}: {}", locate(line), e.inner()) })?; @@ -281,6 +386,111 @@ pub fn translate( }) } +/// The GLSL built-ins naga's constant evaluator folds (`MathFunction`s it +/// implements), besides type constructors. +const FOLDABLE: &[&str] = &[ + "abs", + "acos", + "acosh", + "asin", + "asinh", + "atan", + "atanh", + "ceil", + "clamp", + "cos", + "cosh", + "cross", + "degrees", + "distance", + "dot", + "exp", + "exp2", + "floor", + "fma", + "fract", + "inversesqrt", + "length", + "log", + "log2", + "max", + "min", + "normalize", + "pow", + "radians", + "round", + "sign", + "sin", + "sinh", + "sqrt", + "step", + "tan", + "tanh", + "trunc", +]; + +/// Whether a constant's initialisers need what naga can't fold and drivers +/// do: a `?:`, another built-in (Bliss's `mix`), or a constant that had to +/// become a global (`runtime`). +fn needs_runtime(list: &ast::InitDeclaratorList, runtime: &HashSet) -> bool { + let constructor = |name: &str| { + let n = name.trim_start_matches(['i', 'u', 'b', 'd']); + matches!(name, "float" | "int" | "uint" | "bool" | "double") + || n.starts_with("vec") + || n.starts_with("mat") + }; + let expr = |e: &ast::Expr| { + fn walk(e: &ast::Expr, f: &dyn Fn(&ast::Expr) -> bool) -> bool { + use ast::ExprData as E; + f(e) || match &e.content { + E::Unary(_, a) | E::PostInc(a) | E::PostDec(a) | E::Dot(a, _) => walk(a, f), + E::Binary(_, a, b) | E::Assignment(a, _, b) | E::Comma(a, b) | E::Bracket(a, b) => { + walk(a, f) || walk(b, f) + } + E::Ternary(a, b, c) => walk(a, f) || walk(b, f) || walk(c, f), + E::FunCall(_, args) => args.iter().any(|a| walk(a, f)), + _ => false, + } + } + walk(e, &|e| match &e.content { + ast::ExprData::Ternary(..) => true, + ast::ExprData::Variable(v) => runtime.contains(v.as_str()), + ast::ExprData::FunCall(f, _) => { + callee(f).is_some_and(|c| !constructor(&c) && !FOLDABLE.contains(&c.as_str())) + } + _ => false, + }) + }; + fn init(i: &ast::Initializer, expr: &dyn Fn(&ast::Expr) -> bool) -> bool { + match &i.content { + ast::InitializerData::Simple(e) => expr(e), + ast::InitializerData::List(items) => items.iter().any(|i| init(i, expr)), + } + } + let tail = list.tail.iter().filter_map(|t| t.initializer.as_ref()); + list.head + .initializer + .iter() + .chain(tail) + .any(|i| init(i, &expr)) +} + +/// A negative number: `-1.0`, `-1`. +fn negative_constant(e: &ast::Expr) -> bool { + use ast::ExprData as E; + match &e.content { + E::Unary(op, a) if op.content == ast::UnaryOpData::Minus => { + matches!( + a.content, + E::FloatConst(v) if v > 0.0 + ) || matches!(a.content, E::IntConst(v) if v > 0) + || matches!(a.content, E::DoubleConst(v) if v > 0.0) + } + E::FloatConst(v) => *v < 0.0, + _ => false, + } +} + fn first_lines(s: &str) -> String { s.lines().take(8).collect::>().join("\n") } @@ -316,6 +526,14 @@ struct Legaliser<'a> { /// Identifiers used, for the implicit declarations. used: HashSet, errors: Vec, + /// Inside a constant initialiser: no helper calls there. + constant: bool, + /// The program uses `%` ([`modulo_helpers`]) or `iris_sqrt`: their + /// helpers go in. + modulo: bool, + nan: bool, + /// Constants turned into globals ([`needs_runtime`]). + runtime_constants: HashSet, } fn var(name: &str) -> ast::Expr { @@ -507,6 +725,10 @@ impl<'a> Legaliser<'a> { declared: HashSet::new(), used: HashSet::new(), errors: Vec::new(), + constant: false, + modulo: false, + nan: false, + runtime_constants: HashSet::new(), } } @@ -727,8 +949,19 @@ impl<'a> Legaliser<'a> { let at = explicit .map(|l: u32| l + i as u32) .unwrap_or_else(|| self.next_output()); - self.header - .push(format!("layout(location = {at}) out {full} {name}{array};")); + if let (Some(widened), "") = (widen_output(&full, name), array.as_str()) { + // GL fills the missing channels of a narrow output; + // wgpu wants every channel of the target written. + let (wide, fill) = widened; + self.header.push(format!("{full} {name};")); + self.header.push(format!( + "layout(location = {at}) out {wide} iris_out_{name};" + )); + self.epilogue.push(fill); + } else { + self.header + .push(format!("layout(location = {at}) out {full} {name}{array};")); + } self.interface.outputs.insert(at, name.clone()); } else { self.varying(dir, &interp, &full, name, array); @@ -736,9 +969,25 @@ impl<'a> Legaliser<'a> { } return Ok(false); } - if has(ast::StorageQualifierData::Const) || has(ast::StorageQualifierData::Shared) { + // A constant naga can't fold becomes a global set at the start of `main`. + if has(ast::StorageQualifierData::Const) && needs_runtime(list, &self.runtime_constants) { + self.runtime_constants + .extend(names.iter().map(|(n, _)| n.clone())); + let q = &mut list.head.ty.qualifier; + if let Some(q) = q { + q.qualifiers.retain(|q| { + !matches!(&q.content, ast::TypeQualifierSpecData::Storage(s) + if s.content == ast::StorageQualifierData::Const) + }); + } + if q.as_ref().is_some_and(|q| q.qualifiers.is_empty()) { + *q = None; + } + } else if has(ast::StorageQualifierData::Const) || has(ast::StorageQualifierData::Shared) { self.sized(list); + self.constant = true; self.global_initialisers(list, false); + self.constant = false; return Ok(true); } self.sized(list); @@ -930,6 +1179,8 @@ impl<'a> Legaliser<'a> { return; }; self.sized(list); + self.constant = + storage(&list.head.ty.qualifier).contains(&ast::StorageQualifierData::Const); if let Some(i) = &mut list.head.initializer { self.initializer(i); } @@ -944,6 +1195,7 @@ impl<'a> Legaliser<'a> { let n = t.ident.ident.as_str().to_owned(); self.declare(&n); } + self.constant = false; } fn initializer(&mut self, i: &mut ast::Initializer) { @@ -1148,6 +1400,24 @@ impl<'a> Legaliser<'a> { | E::FloatConst(_) | E::DoubleConst(_) => {} E::Unary(_, a) | E::PostInc(a) | E::PostDec(a) => self.expr(a), + E::Binary(op, a, b) if op.content == ast::BinaryOpData::Mod && !self.constant => { + self.expr(a); + self.expr(b); + self.modulo = true; + let (a, b) = ( + std::mem::replace(&mut **a, var("_")), + std::mem::replace(&mut **b, var("_")), + ); + *e = call("iris_mod", vec![a, b]); + } + E::Assignment(a, op, b) if op.content == ast::AssignmentOpData::Mod => { + self.expr(a); + self.expr(b); + self.modulo = true; + let rhs = std::mem::replace(&mut **b, var("_")); + **b = call("iris_mod", vec![(**a).clone(), rhs]); + *op = ast::AssignmentOpData::Equal.into_node(); + } E::Binary(_, a, b) | E::Assignment(a, _, b) | E::Comma(a, b) => { self.expr(a); self.expr(b); @@ -1268,6 +1538,12 @@ impl<'a> Legaliser<'a> { if self.functions.contains(&name) { return; } + // `sqrt(-1.0)`, Bloop's NaN: naga folds it and fails, drivers give NaN. + if name == "sqrt" && !self.constant && args.len() == 1 && negative_constant(&args[0]) { + *f = ast::FunIdentifierData::Expr(Box::new(var("iris_sqrt"))).into_node(); + self.nan = true; + return; + } if let Some((_, new)) = LEGACY_CALLS.iter().find(|(old, _)| *old == name) { *f = ast::FunIdentifierData::Expr(Box::new(var(new))).into_node(); } else if let Some((_, new)) = SHADOW_CALLS.iter().find(|(old, _)| *old == name) { @@ -1307,6 +1583,12 @@ impl<'a> Legaliser<'a> { } let mut out = String::from("#version 450 core\n"); out.push_str(HELPERS); + if self.modulo { + out.push_str(&modulo_helpers()); + } + if self.nan { + out.push_str("float iris_sqrt(float x) { return sqrt(x); }\n"); + } if !self.link.uniforms.is_empty() { out.push_str("layout(std140, set = 0, binding = 0) uniform IrisUniforms {\n"); for (_, decl) in &self.link.uniforms { diff --git a/crates/horizon-shaderpack/tests/pack.rs b/crates/horizon-shaderpack/tests/pack.rs index 7aa45e8fa..c957d7fb4 100644 --- a/crates/horizon-shaderpack/tests/pack.rs +++ b/crates/horizon-shaderpack/tests/pack.rs @@ -121,6 +121,69 @@ fn preprocesses_with_defaults_and_with_values() { ); } +/// JCPP lets a `#define` replace a macro (Bloop's `TILT_ANGLE`); the added +/// `#undef`s don't move the lines errors name. +#[test] +fn a_define_replaces_an_earlier_one() { + use horizon_shaderpack::{include::Inlined, preprocess::preprocess}; + let text = "#define TILT 5.0\nfloat a = TILT;\n # define TILT 1.5 // radians\nfloat b = TILT;\n#define F(x) x\n#define F(x) (x * 2)\nfloat c = F(1);\n#if\n"; + let source = Inlined { + text: text.into(), + origin: (1..=8).map(|l| ("lib/specular.glsl".into(), l)).collect(), + }; + let error = preprocess(&source, &env()).unwrap_err(); + assert!(error.starts_with("lib/specular.glsl:8:"), "{error}"); + let source = Inlined { + text: text.replace("#if\n", ""), + ..source + }; + let out = preprocess(&source, &env()).unwrap().text; + let lines: Vec<&str> = out.lines().collect(); + assert_eq!(lines[1], "float a = 5.0 ;"); + assert_eq!(lines[3], "float b = 1.5 ;"); + assert_eq!(lines[6], "float c = ( 1 * 2 ) ;"); +} + +/// Conditions as JCPP reads them: an empty macro counts as 0 (Bloop's +/// `#if MC_GL_VENDOR_INTEL || MC_GL_VENDOR_OTHER` with Iris's empty vendor +/// macro, its `#define TAA_USE_YCOCG`), a float as its integer part; a +/// quoted `#error` lexes, and an `#if` may run to the end. +#[test] +fn conditions_read_as_jcpp_does() { + use horizon_shaderpack::{include::Inlined, preprocess::preprocess}; + let mut env = env(); + env.define("MC_GL_VENDOR_OTHER", ""); + let text = "#define TAA_USE_YCOCG +#define LEVEL 0.5 +#if MC_GL_VENDOR_INTEL || MC_GL_VENDOR_OTHER +float gather = 0.0; +#else +float gather = 1.0; +#endif +#if TAA_USE_YCOCG +float ycocg = 1.0; +#endif +#if defined TAA_USE_YCOCG && defined(MC_GL_VENDOR_OTHER) && LEVEL == 0 +float both = 1.0; +#endif +#ifndef TAA_USE_YCOCG +#error \"This program should be disabled\" +#endif +#ifdef TAA_USE_YCOCG +float open = 1.0; +"; + let source = Inlined { + text: text.into(), + origin: Vec::new(), + }; + let out = preprocess(&source, &env).unwrap().text; + let words: Vec<&str> = out.split_whitespace().collect(); + assert_eq!( + words.join(" "), + "float gather = 1.0 ; float both = 1.0 ; float open = 1.0 ;" + ); +} + #[test] fn reports_missing_includes_and_cycles() { let pack = JavaPack::open(&mini()).unwrap(); diff --git a/crates/horizon-shaderpack/tests/translate.rs b/crates/horizon-shaderpack/tests/translate.rs index da8dc7e32..3c71d8546 100644 --- a/crates/horizon-shaderpack/tests/translate.rs +++ b/crates/horizon-shaderpack/tests/translate.rs @@ -290,6 +290,103 @@ fn reports_errors_with_their_place() { assert_eq!(err, "uniform a is declared as both `float a` and `int a`"); } +/// What naga refuses and drivers accept: `vec % scalar` (Noble), `sqrt` of +/// a negative constant (Bloop's NaN), constants naga can't fold (Bliss's +/// `?:`, `mix`), and 16-bit types (Noble on NVIDIA). +#[test] +fn legalises_what_naga_refuses() { + let mut link = Link::default(); + let fs = run( + Stage::Fragment, + "uniform vec2 uv; +const int RES = 256 % 100; +const vec3 TARGET = length(vec3(1.0)) < 0.001 ? vec3(0.0) : normalize(vec3(1.0)); +const vec3 TINT = mix(TARGET, vec3(1.0), 0.5); +const vec3 HALF = TINT * 0.5; +u16vec2 pack(uint v) { return u16vec2(v & 65535u, v >> 16u); } +float nan() { return sqrt(-1.0); } +void main() { + ivec2 texel = ivec2(uv) % RES; + texel %= 7; + uint packed = packFloat2x16(f16vec2(HALF.xy)); + gl_FragColor = vec4(vec2(texel), float(pack(packed).x), nan()); +} +", + &mut link, + ) + .unwrap(); + for wanted in [ + "const int RES = 256 % 100;", + "vec3 TARGET;", + "vec3 TINT;", + "vec3 HALF;", + "ivec2 texel = iris_mod(ivec2(uv), RES);", + "texel = iris_mod(texel, 7);", + "uvec2 pack(uint v)", + "return iris_sqrt(-1.);", + "uint packed = packHalf2x16(vec2(HALF.xy));", + ] { + assert!(fs.glsl.contains(wanted), "{wanted}\n{}", fs.glsl); + } + reparse(&fs.wgsl).unwrap(); +} + +/// A fragment output narrower than its four-channel target (Steadfast's +/// `final` writes `out vec3 color`) is written through a `vec4` with alpha 1: +/// GL fills the missing channels, wgpu refuses the pipeline. +#[test] +fn narrow_fragment_outputs_fill_four_channels() { + let mut link = Link::default(); + let fs = run( + Stage::Fragment, + "uniform vec3 tint; +layout(location = 0) out vec3 color; +layout(location = 1) out float depth; +out vec4 extra; +void main() { + color = tint; + depth = 0.5; + extra = vec4(tint, 0.25); +} +", + &mut link, + ) + .unwrap(); + for wanted in [ + "layout(location = 0) out vec4 iris_out_color;", + "iris_out_color = vec4(color, 1.0);", + "layout(location = 1) out vec4 iris_out_depth;", + "iris_out_depth = vec4(depth, 0.0, 0.0, 1.0);", + "layout(location = 2) out vec4 extra;", + ] { + assert!(fs.glsl.contains(wanted), "{wanted}\n{}", fs.glsl); + } + assert_eq!( + fs.interface.outputs.values().collect::>(), + ["color", "depth", "extra"] + ); + let module = naga::front::wgsl::parse_str(&fs.wgsl).unwrap(); + let entry = &module.entry_points[0]; + let result = entry.function.result.as_ref().unwrap(); + let naga::TypeInner::Struct { members, .. } = &module.types[result.ty].inner else { + panic!("{}", fs.wgsl); + }; + for m in members { + assert!( + matches!( + module.types[m.ty].inner, + naga::TypeInner::Vector { + size: naga::VectorSize::Quad, + .. + } + ), + "{}", + fs.wgsl + ); + } + reparse(&fs.wgsl).unwrap(); +} + /// The written WGSL, read back and validated: what wgpu is given. fn reparse(wgsl: &str) -> Result<(), String> { let module = naga::front::wgsl::parse_str(wgsl).map_err(|e| e.emit_to_string(wgsl))?; diff --git a/crates/horizon-telemetry-server/README.md b/crates/horizon-telemetry-server/README.md index cf2d52393..dc1f51248 100644 --- a/crates/horizon-telemetry-server/README.md +++ b/crates/horizon-telemetry-server/README.md @@ -1,6 +1,6 @@ # horizon-telemetry-server -This server receives what players choose to send (performance summaries, crash and bug reports, benchmark uploads: [docs/telemetry.md](../../docs/telemetry.md)) and stores it in one SQLite file. It serves anonymous totals to the website. It is one small Rust process, about 7 MB of memory when idle. +This server receives what players choose to send (performance summaries, crash and bug reports, benchmark uploads: [docs/telemetry.md](../../docs/telemetry.md)) and stores it in one SQLite file. It serves anonymous totals to the website. It also keeps the live player count from the games' anonymous "I'm playing" pings, in memory only. It is one small Rust process, about 7 MB of memory when idle. cargo run --release # in this folder: its own workspace, like the launcher's PORT=8080 HORIZON_TELEMETRY_DB=/data/telemetry.sqlite3 horizon-telemetry-server @@ -14,6 +14,8 @@ The launcher sends to it when `HORIZON_TELEMETRY_URL` is set (and to `DEFAULT_EN | `POST /v1/batch` | A zstd batch (`Content-Encoding: zstd`, at most 256 KiB, 1 MiB inflated, 64 items). Returns 204. Returns 400 for a bad batch, 413 for one too large, 415 if it is not zstd, 429 when over a limit. | | `DELETE /v1/installs/` | Deletes everything that install sent. Its share of the daily totals is rebuilt at once. | | `GET /v1/aggregate?days=30` | The totals the website reads. Cached 10 minutes, with `Access-Control-Allow-Origin` set to the website. | +| `POST /v1/live` | A game's "I'm playing" ping (JSON, at most 512 bytes). Returns 204. Returns 400 for a bad ping, 413 for one too large, 429 over the address's limit, 503 when it holds `LIVE_MAX_SESSIONS` already. | +| `GET /v1/live` | How many play now, rounded: `playing`, `lan`, `versions`, `platforms`. Made again at most every 15 seconds, with the same `Access-Control-Allow-Origin`. | | `GET /healthz` | `ok` | The totals are grouped per version, OS, GPU vendor and render distance. Each group has its sessions, install-days, hours played, the 14 frame-time buckets summed, and the mean p50 and p99 frame times. Groups with fewer than 5 install-days are left out. The totals also list crash counts per version and the newest 50 benchmark uploads. @@ -27,6 +29,8 @@ The totals are grouped per version, OS, GPU vendor and render distance. Each gro Measured: **about 190 bytes per play session** on disk, indexes included (`tests/server.rs`, 10 000 sessions). 1 000 players playing twice a day for 180 days is about 70 MB. +The live count is a table in memory: a session ID, when it last pinged, its version, platform and LAN flag, about 100 bytes a session. A session counts while its last ping is under 2 minutes old and is forgotten after that. Nothing of it reaches the disk, so a restart empties it; it is whole again a minute later. + The day stored is the day the server received an item. The sender's IP address is never written down. The per-address rate limit keeps addresses in memory for an hour at most. Raw rows are deleted after `HORIZON_TELEMETRY_RETENTION_DAYS` (180). The daily totals stay; they hold no install ID. @@ -43,6 +47,9 @@ All are environment variables: - `HORIZON_TELEMETRY_ITEMS_PER_DAY` per install (100) - `HORIZON_TELEMETRY_TRUST_PROXY=1` behind a proxy (the client's address is then the first of `X-Forwarded-For`) - `HORIZON_TELEMETRY_ALLOW_ORIGIN` (`https://playhorizon.dev`) +- `HORIZON_TELEMETRY_LIVE_PER_HOUR` per address, pings and reads (600, bursts of 60: ten players behind one address) +- `HORIZON_TELEMETRY_LIVE_WINDOW_SECONDS` (120) +- `HORIZON_TELEMETRY_LIVE_MAX_SESSIONS` (200 000) ## Hosting diff --git a/crates/horizon-telemetry-server/src/lib.rs b/crates/horizon-telemetry-server/src/lib.rs index b1521a714..061a9ca37 100644 --- a/crates/horizon-telemetry-server/src/lib.rs +++ b/crates/horizon-telemetry-server/src/lib.rs @@ -3,12 +3,15 @@ //! - `POST /v1/batch`: a zstd batch from the launcher, checked by `horizon_telemetry::batch`. //! - `DELETE /v1/installs/`: everything an install sent goes. //! - `GET /v1/aggregate?days=30`: the anonymous totals the website reads, cached. +//! - `POST /v1/live`: a game's anonymous "I'm playing" ping (`live`, in memory only). +//! - `GET /v1/live`: how many play now, rounded, cached briefly. //! - `GET /healthz`. //! //! Abuse limits: a token bucket per IP address (kept in memory for an hour, never stored), a -//! daily item cap per install, and the batch size limits. Raw rows expire after -//! `retention_days`; the daily totals stay. One small process and one SQLite file: see -//! `README.md` for running it. +//! daily item cap per install, and the batch size limits. The live count has its own, larger +//! bucket per address (several players can share one) and a cap on the sessions it holds. Raw +//! rows expire after `retention_days`; the daily totals stay. One small process and one SQLite +//! file: see `README.md` for running it. use std::collections::HashMap; use std::net::{IpAddr, SocketAddr}; use std::sync::{Arc, Mutex}; @@ -21,8 +24,11 @@ use axum::response::{IntoResponse, Response}; use axum::routing::{delete, get, post}; use horizon_telemetry::batch; +pub mod live; pub mod store; +use horizon_telemetry::live::{MAX_PING_BYTES, Ping}; +use live::Live; use store::Store; pub struct Config { @@ -38,6 +44,13 @@ pub struct Config { pub trust_proxy: bool, /// The website allowed to read the totals from a browser. pub allow_origin: String, + /// Live count requests (pings and reads) an IP address may make an hour, with a burst of a + /// tenth of it. A game pings once a minute, so the default lets ten play behind one address. + pub live_per_hour: f64, + /// How long a session counts after its last ping. + pub live_window: Duration, + /// Sessions the live count holds at most; a new one past that is refused. + pub live_max_sessions: usize, } impl Default for Config { @@ -49,13 +62,17 @@ impl Default for Config { items_per_day: 100, trust_proxy: false, allow_origin: "https://playhorizon.dev".into(), + live_per_hour: 600.0, + live_window: horizon_telemetry::live::WINDOW, + live_max_sessions: 200_000, } } } impl Config { /// The defaults, with `HORIZON_TELEMETRY_RETENTION_DAYS`, `…_MIN_INSTALL_DAYS`, - /// `…_REQUESTS_PER_HOUR`, `…_ITEMS_PER_DAY`, `…_TRUST_PROXY` (1) and `…_ALLOW_ORIGIN`. + /// `…_REQUESTS_PER_HOUR`, `…_ITEMS_PER_DAY`, `…_TRUST_PROXY` (1), `…_ALLOW_ORIGIN`, + /// `…_LIVE_PER_HOUR`, `…_LIVE_WINDOW_SECONDS` and `…_LIVE_MAX_SESSIONS`. pub fn from_env() -> Self { let var = |k: &str| std::env::var(format!("HORIZON_TELEMETRY_{k}")).ok(); let d = Self::default(); @@ -74,6 +91,15 @@ impl Config { .unwrap_or(d.items_per_day), trust_proxy: var("TRUST_PROXY").is_some_and(|v| v == "1"), allow_origin: var("ALLOW_ORIGIN").unwrap_or(d.allow_origin), + live_per_hour: var("LIVE_PER_HOUR") + .and_then(|v| v.parse().ok()) + .unwrap_or(d.live_per_hour), + live_window: var("LIVE_WINDOW_SECONDS") + .and_then(|v| v.parse().ok()) + .map_or(d.live_window, Duration::from_secs), + live_max_sessions: var("LIVE_MAX_SESSIONS") + .and_then(|v| v.parse().ok()) + .unwrap_or(d.live_max_sessions), } } } @@ -82,13 +108,21 @@ pub struct App { store: Mutex, config: Config, /// Tokens left and when they were counted, per client address. - buckets: Mutex>, + buckets: Mutex, + /// The same for the live count's requests. + live_buckets: Mutex, + /// Who is playing now (`live`). + live: Mutex, + /// `GET /v1/live`'s answer and when it was made. + live_cache: Mutex>, /// `/v1/aggregate` answers by `days`, with when they were made. cache: Mutex>, /// Today, in days since 1970 (a test moves it). today: Box u32 + Send + Sync>, } +type Buckets = HashMap; + const CACHE_FOR: Duration = Duration::from_secs(600); fn status(code: StatusCode, message: &str) -> Response { @@ -105,10 +139,14 @@ impl App { config: Config, today: Box u32 + Send + Sync>, ) -> Arc { + let live = Live::new(config.live_window, config.live_max_sessions); Arc::new(Self { store: Mutex::new(store), config, buckets: Mutex::default(), + live_buckets: Mutex::default(), + live: Mutex::new(live), + live_cache: Mutex::default(), cache: Mutex::default(), today, }) @@ -120,18 +158,16 @@ impl App { /// Takes a token for `ip`; false when it has none left. fn allow(&self, ip: IpAddr) -> bool { - let rate = self.config.requests_per_hour / 3600.0; - let burst = (self.config.requests_per_hour / 10.0).max(1.0); - let mut buckets = self.buckets.lock().unwrap_or_else(|e| e.into_inner()); - let now = Instant::now(); - let (tokens, at) = buckets.entry(ip).or_insert((burst, now)); - *tokens = (*tokens + now.duration_since(*at).as_secs_f64() * rate).min(burst); - *at = now; - if *tokens < 1.0 { - return false; - } - *tokens -= 1.0; - true + take(&self.buckets, self.config.requests_per_hour, ip) + } + + /// [`Self::allow`] for the live count's requests. + fn allow_live(&self, ip: IpAddr) -> bool { + take(&self.live_buckets, self.config.live_per_hour, ip) + } + + fn live(&self) -> std::sync::MutexGuard<'_, Live> { + self.live.lock().unwrap_or_else(|e| e.into_inner()) } fn client(&self, headers: &HeaderMap, peer: Option) -> IpAddr { @@ -160,14 +196,18 @@ impl App { self.store().newest_day(install).ok().flatten() } - /// Daily upkeep: totals rebuilt, expired rows removed, idle rate-limit entries forgotten. + /// Daily upkeep: totals rebuilt, expired rows removed, idle rate-limit entries and live + /// sessions forgotten. pub fn maintain(&self) -> rusqlite::Result { let oldest = (self.today)().saturating_sub(self.config.retention_days); let removed = self.store().expire(oldest)?; - self.buckets - .lock() - .unwrap_or_else(|e| e.into_inner()) - .retain(|_, (_, at)| at.elapsed() < Duration::from_secs(3600)); + for buckets in [&self.buckets, &self.live_buckets] { + buckets + .lock() + .unwrap_or_else(|e| e.into_inner()) + .retain(|_, (_, at)| at.elapsed() < Duration::from_secs(3600)); + } + self.live().forget_expired(Instant::now()); if removed > 0 { self.cache.lock().unwrap_or_else(|e| e.into_inner()).clear(); } @@ -175,6 +215,23 @@ impl App { } } +/// Takes a token for `ip` from its bucket in `buckets` (`per_hour`, bursts of a tenth of it); +/// false when it has none left. +fn take(buckets: &Mutex, per_hour: f64, ip: IpAddr) -> bool { + let rate = per_hour / 3600.0; + let burst = (per_hour / 10.0).max(1.0); + let mut buckets = buckets.lock().unwrap_or_else(|e| e.into_inner()); + let now = Instant::now(); + let (tokens, at) = buckets.entry(ip).or_insert((burst, now)); + *tokens = (*tokens + now.duration_since(*at).as_secs_f64() * rate).min(burst); + *at = now; + if *tokens < 1.0 { + return false; + } + *tokens -= 1.0; + true +} + fn peer(req: &Request) -> Option { req.extensions() .get::>() @@ -278,18 +335,65 @@ async fn aggregate(State(app): State>, Query(window): Query) -> } } }; + json_response(&app, json, CACHE_FOR.as_secs()) +} + +/// `POST /v1/live`: one "I'm playing". 204, or 400 for a bad ping, 413 for one too large, 429 +/// over the address's limit, 503 when the table is full. +async fn ping(State(app): State>, req: Request) -> Response { + if !app.allow_live(app.client(req.headers(), peer(&req))) { + return status(StatusCode::TOO_MANY_REQUESTS, "too many requests"); + } + let Ok(body) = axum::body::to_bytes(req.into_body(), MAX_PING_BYTES).await else { + return status(StatusCode::PAYLOAD_TOO_LARGE, "a ping is at most 512 bytes"); + }; + let ping: Ping = match serde_json::from_slice(&body) { + Ok(ping) => ping, + Err(e) => return status(StatusCode::BAD_REQUEST, &e.to_string()), + }; + if let Err(e) = ping.check() { + return status(StatusCode::BAD_REQUEST, e); + } + match app.live().ping(&ping, Instant::now()) { + Ok(()) => StatusCode::NO_CONTENT.into_response(), + Err(live::Full) => status(StatusCode::SERVICE_UNAVAILABLE, "try again later"), + } +} + +/// `GET /v1/live`: the rounded live count (`horizon_telemetry::live::Count`), made again at +/// most every eighth of the window. +async fn playing(State(app): State>, req: Request) -> Response { + if !app.allow_live(app.client(req.headers(), peer(&req))) { + return status(StatusCode::TOO_MANY_REQUESTS, "too many requests"); + } + let fresh_for = app.config.live_window / 8; + let json = { + let mut cache = app.live_cache.lock().unwrap_or_else(|e| e.into_inner()); + match &*cache { + Some((at, json)) if at.elapsed() < fresh_for => json.clone(), + _ => { + let json = + serde_json::to_string(&app.live().count(Instant::now())).unwrap_or_default(); + *cache = Some((Instant::now(), json.clone())); + json + } + } + }; + json_response(&app, json, fresh_for.as_secs()) +} + +fn json_response(app: &App, json: String, max_age: u64) -> Response { let origin = HeaderValue::from_str(&app.config.allow_origin).unwrap_or(HeaderValue::from_static("*")); + let cache = HeaderValue::from_str(&format!("public, max-age={max_age}")) + .unwrap_or(HeaderValue::from_static("no-cache")); ( [ ( header::CONTENT_TYPE, HeaderValue::from_static("application/json"), ), - ( - header::CACHE_CONTROL, - HeaderValue::from_static("public, max-age=600"), - ), + (header::CACHE_CONTROL, cache), (header::ACCESS_CONTROL_ALLOW_ORIGIN, origin), ], json, @@ -300,6 +404,7 @@ async fn aggregate(State(app): State>, Query(window): Query) -> pub fn router(app: Arc) -> Router { Router::new() .route("/v1/batch", post(receive)) + .route("/v1/live", post(ping).get(playing)) .route("/v1/installs/{id}", delete(forget)) .route("/v1/aggregate", get(aggregate)) .route("/healthz", get(|| async { "ok" })) diff --git a/crates/horizon-telemetry-server/src/live.rs b/crates/horizon-telemetry-server/src/live.rs new file mode 100644 index 000000000..f28165da5 --- /dev/null +++ b/crates/horizon-telemetry-server/src/live.rs @@ -0,0 +1,201 @@ +//! Who is playing now, from the games' "I'm playing" pings (`horizon_telemetry::live`). Kept in +//! memory only: a session ID, when it last pinged, its version, platform and LAN flag. A +//! session counts while its last ping is under the window old and is forgotten after it. No +//! address is kept, and nothing is written to disk, so a restart starts the count again (it +//! is whole again a minute later). +use std::collections::{BTreeMap, HashMap}; +use std::time::{Duration, Instant}; + +use horizon_telemetry::live::{Count, PLATFORMS, Ping, round}; + +/// Versions listed by name in a count; the rest are summed under `other`. +const VERSIONS_SHOWN: usize = 12; + +struct Seen { + at: Instant, + version: Box, + platform: u8, + lan: bool, +} + +pub struct Live { + sessions: HashMap, + window: Duration, + max_sessions: usize, +} + +/// The table is full and this session is new. +#[derive(Debug, PartialEq, Eq)] +pub struct Full; + +impl Live { + pub fn new(window: Duration, max_sessions: usize) -> Self { + Self { + sessions: HashMap::new(), + window, + max_sessions, + } + } + + /// Records `ping` (already checked) as seen at `now`. + pub fn ping(&mut self, ping: &Ping, now: Instant) -> Result<(), Full> { + let Ok(id) = u128::from_str_radix(&ping.session, 16) else { + return Ok(()); + }; + if !self.sessions.contains_key(&id) && self.sessions.len() >= self.max_sessions { + self.forget_expired(now); + if self.sessions.len() >= self.max_sessions { + return Err(Full); + } + } + let platform = PLATFORMS + .iter() + .position(|p| *p == ping.platform) + .unwrap_or(PLATFORMS.len() - 1) as u8; + self.sessions.insert( + id, + Seen { + at: now, + version: ping.version.as_str().into(), + platform, + lan: ping.lan, + }, + ); + Ok(()) + } + + /// Drops the sessions whose last ping is older than the window. + pub fn forget_expired(&mut self, now: Instant) { + let window = self.window; + self.sessions + .retain(|_, s| now.saturating_duration_since(s.at) < window); + } + + /// Who is playing at `now`, rounded. + pub fn count(&mut self, now: Instant) -> Count { + self.forget_expired(now); + let mut versions: HashMap<&str, u64> = HashMap::new(); + let mut platforms = [0u64; PLATFORMS.len()]; + let mut lan = 0; + for s in self.sessions.values() { + *versions.entry(&s.version).or_default() += 1; + platforms[usize::from(s.platform)] += 1; + lan += u64::from(s.lan); + } + let mut by_count: Vec<(&str, u64)> = versions.into_iter().collect(); + by_count.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0))); + let mut shown = BTreeMap::new(); + let mut other = 0; + for (i, (version, n)) in by_count.into_iter().enumerate() { + if i < VERSIONS_SHOWN { + shown.insert(version.to_owned(), round(n)); + } else { + other += n; + } + } + if other > 0 { + *shown.entry("other".to_owned()).or_default() += round(other); + } + Count { + playing: round(self.sessions.len() as u64), + lan: round(lan), + versions: shown, + platforms: PLATFORMS + .iter() + .zip(platforms) + .filter(|(_, n)| *n > 0) + .map(|(p, n)| ((*p).to_owned(), round(n))) + .collect(), + } + } + + /// Sessions held now, counted or not yet forgotten. + pub fn len(&self) -> usize { + self.sessions.len() + } + + pub fn is_empty(&self) -> bool { + self.sessions.is_empty() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ping(n: u32, version: &str, platform: &str, lan: bool) -> Ping { + Ping { + session: format!("{n:032x}"), + version: version.into(), + platform: platform.into(), + lan, + } + } + + #[test] + fn sessions_count_until_the_window_passes() { + let t = Instant::now(); + let mut live = Live::new(Duration::from_secs(120), 100); + live.ping(&ping(1, "0.2.0", "linux", false), t).unwrap(); + live.ping(&ping(2, "0.2.0", "macos", true), t).unwrap(); + // The same session again is still one. + live.ping( + &ping(1, "0.2.0", "linux", false), + t + Duration::from_secs(60), + ) + .unwrap(); + let count = live.count(t + Duration::from_secs(61)); + assert_eq!((count.playing, count.lan), (2, 1)); + assert_eq!(count.versions, BTreeMap::from([("0.2.0".into(), 2)])); + assert_eq!( + count.platforms, + BTreeMap::from([("linux".into(), 1), ("macos".into(), 1)]) + ); + // Session 2 stopped pinging two minutes ago; session 1 pinged a minute later. + let count = live.count(t + Duration::from_secs(150)); + assert_eq!((count.playing, count.lan), (1, 0)); + assert_eq!(live.len(), 1); + assert_eq!(live.count(t + Duration::from_secs(181)), Count::default()); + assert!(live.is_empty()); + } + + #[test] + fn a_full_table_takes_no_new_session_until_one_expires() { + let t = Instant::now(); + let mut live = Live::new(Duration::from_secs(120), 2); + live.ping(&ping(1, "0.2.0", "linux", false), t).unwrap(); + live.ping(&ping(2, "0.2.0", "linux", false), t).unwrap(); + assert_eq!(live.ping(&ping(3, "0.2.0", "linux", false), t), Err(Full)); + // A known session still refreshes. + live.ping( + &ping(1, "0.2.0", "linux", false), + t + Duration::from_secs(100), + ) + .unwrap(); + let later = t + Duration::from_secs(130); + live.ping(&ping(3, "0.2.0", "linux", false), later).unwrap(); + assert_eq!(live.count(later).playing, 2); + } + + #[test] + fn rare_versions_are_summed_and_counts_rounded() { + let t = Instant::now(); + let mut live = Live::new(Duration::from_secs(120), 1000); + for n in 0..40 { + live.ping(&ping(n, "0.2.0", "windows", n % 4 == 0), t) + .unwrap(); + } + for n in 0..(VERSIONS_SHOWN as u32 + 3) { + live.ping(&ping(100 + n, &format!("dev {n}"), "other", false), t) + .unwrap(); + } + let count = live.count(t); + assert_eq!(count.playing, 55); + assert_eq!(count.lan, 10); + assert_eq!(count.versions["0.2.0"], 40); + assert_eq!(count.versions["other"], 4); + assert_eq!(count.versions.len(), VERSIONS_SHOWN + 1); + assert_eq!(count.platforms["windows"], 40); + assert_eq!(count.platforms["other"], 15); + } +} diff --git a/crates/horizon-telemetry-server/tests/live.rs b/crates/horizon-telemetry-server/tests/live.rs new file mode 100644 index 000000000..d8c7f33fe --- /dev/null +++ b/crates/horizon-telemetry-server/tests/live.rs @@ -0,0 +1,190 @@ +//! The live count through its HTTP interface, and end to end with the game's ping and the +//! launcher's read (`horizon_telemetry::live`). +use std::sync::Arc; +use std::time::Duration; + +use axum::body::Body; +use axum::http::{Request, StatusCode, header}; +use horizon_telemetry::live::{self, Count, Ping}; +use horizon_telemetry_server::store::Store; +use horizon_telemetry_server::{App, Config, router}; +use http_body_util::BodyExt; +use tower::ServiceExt; + +fn app(config: Config) -> Arc { + App::new(Store::open(":memory:").unwrap(), config) +} + +fn quick() -> Config { + Config { + live_per_hour: 100_000.0, + live_window: Duration::from_secs(1), + trust_proxy: true, + ..Config::default() + } +} + +fn ping(n: u32, version: &str, lan: bool) -> String { + serde_json::to_string(&Ping { + session: format!("{n:032x}"), + version: version.into(), + platform: "linux".into(), + lan, + }) + .unwrap() +} + +async fn send(app: &Arc, req: Request) -> (StatusCode, axum::http::HeaderMap, String) { + let res = router(app.clone()).oneshot(req).await.unwrap(); + let (code, headers) = (res.status(), res.headers().clone()); + let body = res.into_body().collect().await.unwrap().to_bytes(); + (code, headers, String::from_utf8_lossy(&body).into_owned()) +} + +async fn post(app: &Arc, body: impl Into, from: &str) -> StatusCode { + let req = Request::post("/v1/live") + .header("x-forwarded-for", from) + .body(body.into()) + .unwrap(); + send(app, req).await.0 +} + +async fn count(app: &Arc) -> Count { + let req = Request::get("/v1/live") + .header("x-forwarded-for", "198.51.100.1") + .body(Body::empty()) + .unwrap(); + let (code, headers, body) = send(app, req).await; + assert_eq!(code, StatusCode::OK, "{body}"); + assert_eq!(headers[header::CONTENT_TYPE], "application/json"); + assert_eq!( + headers[header::ACCESS_CONTROL_ALLOW_ORIGIN], + "https://playhorizon.dev" + ); + serde_json::from_str(&body).unwrap() +} + +#[tokio::test] +async fn sessions_count_while_they_ping_and_expire_after() { + let app = app(quick()); + assert_eq!( + post(&app, ping(1, "0.2.0", false), "203.0.113.1").await, + StatusCode::NO_CONTENT + ); + assert_eq!( + post(&app, ping(2, "0.2.0", true), "203.0.113.2").await, + StatusCode::NO_CONTENT + ); + // A second ping from the same session is still one player. + assert_eq!( + post(&app, ping(1, "0.2.0", false), "203.0.113.1").await, + StatusCode::NO_CONTENT + ); + let now = count(&app).await; + assert_eq!((now.playing, now.lan), (2, 1)); + assert_eq!(now.versions["0.2.0"], 2); + assert_eq!(now.platforms["linux"], 2); + + // Session 1 keeps pinging; session 2 stops. + for _ in 0..5 { + tokio::time::sleep(Duration::from_millis(250)).await; + post(&app, ping(1, "0.2.0", false), "203.0.113.1").await; + } + let later = count(&app).await; + assert_eq!((later.playing, later.lan), (1, 0)); + tokio::time::sleep(Duration::from_millis(1200)).await; + assert_eq!(count(&app).await, Count::default()); +} + +#[tokio::test] +async fn bad_pings_are_refused() { + let app = app(quick()); + let from = "203.0.113.3"; + assert_eq!(post(&app, "not json", from).await, StatusCode::BAD_REQUEST); + assert_eq!( + post(&app, ping(1, "0.2", false), from).await, + StatusCode::BAD_REQUEST + ); + let extra = r#"{"session":"00000000000000000000000000000001","version":"0.2.0","platform":"linux","lan":false,"name":"Steve"}"#; + assert_eq!(post(&app, extra, from).await, StatusCode::BAD_REQUEST); + assert_eq!( + post(&app, "x".repeat(4096), from).await, + StatusCode::PAYLOAD_TOO_LARGE + ); + assert_eq!(count(&app).await.playing, 0); +} + +#[tokio::test] +async fn an_address_is_rate_limited_on_its_own_bucket() { + let app = app(Config { + live_per_hour: 60.0, + trust_proxy: true, + ..Config::default() + }); + // A burst of a tenth of the hour's 60, then 429. + let mut codes = Vec::new(); + for n in 0..8 { + codes.push(post(&app, ping(n, "0.2.0", false), "203.0.113.4").await); + } + assert_eq!( + codes + .iter() + .filter(|c| **c == StatusCode::NO_CONTENT) + .count(), + 6 + ); + assert_eq!(codes[7], StatusCode::TOO_MANY_REQUESTS); + // Another address is not held back. + assert_eq!( + post(&app, ping(9, "0.2.0", false), "203.0.113.5").await, + StatusCode::NO_CONTENT + ); +} + +#[tokio::test] +async fn a_full_table_refuses_new_sessions() { + let app = app(Config { + live_max_sessions: 2, + ..quick() + }); + for n in 0..2 { + assert_eq!( + post(&app, ping(n, "0.2.0", false), "203.0.113.6").await, + StatusCode::NO_CONTENT + ); + } + assert_eq!( + post(&app, ping(2, "0.2.0", false), "203.0.113.6").await, + StatusCode::SERVICE_UNAVAILABLE + ); + assert_eq!( + post(&app, ping(1, "0.2.0", false), "203.0.113.6").await, + StatusCode::NO_CONTENT + ); +} + +#[tokio::test] +async fn the_games_ping_and_the_launchers_read_reach_it_end_to_end() { + let app = app(Config { + live_window: Duration::from_secs(120), + ..quick() + }); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let service = router(app.clone()).into_make_service_with_connect_info::(); + tokio::spawn(async move { axum::serve(listener, service).await.unwrap() }); + + let count = tokio::task::spawn_blocking(move || { + let a = Ping::new(&live::session_id(), "0.2.0", false); + let b = Ping::new(&live::session_id(), "dev 0.1.0", true); + live::send(&url, &a)?; + live::send(&url, &b)?; + live::fetch(&url) + }) + .await + .unwrap() + .unwrap(); + assert_eq!((count.playing, count.lan), (2, 1)); + assert_eq!(count.versions.len(), 2); + assert_eq!(count.platforms[live::platform()], 2); +} diff --git a/crates/horizon-telemetry/Cargo.toml b/crates/horizon-telemetry/Cargo.toml index ea54b079d..913eac453 100644 --- a/crates/horizon-telemetry/Cargo.toml +++ b/crates/horizon-telemetry/Cargo.toml @@ -13,12 +13,14 @@ serde_json = "1" ruzstd = "0.9" # The random install ID and outbox file names. getrandom = "0.3" -# Sending, for the launcher; the ingest server builds without it. +# Sending, for the launcher (and the game's "I'm playing" ping); the ingest server builds without it. ureq = { version = "2", default-features = false, features = ["tls"], optional = true } [features] -default = ["upload"] +default = ["upload", "live"] upload = ["dep:ureq"] +# The "I'm playing" ping and reading the live count (`live`), for the game and the launcher. +live = ["dep:ureq"] [[test]] name = "consent_gating" diff --git a/crates/horizon-telemetry/src/lib.rs b/crates/horizon-telemetry/src/lib.rs index e903936db..8d2840a08 100644 --- a/crates/horizon-telemetry/src/lib.rs +++ b/crates/horizon-telemetry/src/lib.rs @@ -6,11 +6,15 @@ //! connection. Items are small summaries (percentiles and histogram buckets, never raw streams), //! dated to the day, with no account, world, server or address in them ([`scrub`]); they leave //! in zstd batches ([`batch`]). `docs/telemetry.md` lists every field. +//! +//! The one exception is [`live`]: the anonymous "I'm playing" ping the game sends while it +//! runs, for the live player count. It holds no install ID and nothing about the player. use std::path::{Path, PathBuf}; use std::time::{SystemTime, UNIX_EPOCH}; pub mod batch; pub mod consent; +pub mod live; pub mod outbox; pub mod payload; pub mod scrub; @@ -29,8 +33,9 @@ pub const SCHEMA: u32 = 1; /// and until the player answers nothing new is kept or sent. pub const CONSENT_VERSION: u32 = 1; -/// The ingest server, or none while there isn't one: then nothing is ever sent and the outbox -/// stays within its caps. `HORIZON_TELEMETRY_URL` overrides it (tests, a local server). +/// The ingest server, or none while there isn't one: then nothing is ever sent (no ping either) +/// and the outbox stays within its caps. `HORIZON_TELEMETRY_URL` overrides it (tests, a local +/// server). pub const DEFAULT_ENDPOINT: Option<&str> = None; /// Where items are sent, if anywhere. diff --git a/crates/horizon-telemetry/src/live.rs b/crates/horizon-telemetry/src/live.rs new file mode 100644 index 000000000..b1df57320 --- /dev/null +++ b/crates/horizon-telemetry/src/live.rs @@ -0,0 +1,215 @@ +//! The anonymous "I'm playing" ping, and the live count it feeds ("N playing now" in the +//! launcher). +//! +//! Unlike everything else in this crate it does not wait for consent: Ludovic decided +//! (2026-10-22) to count every player and tell them, in the launcher's first-run question, its +//! Settings and the privacy page. So a ping holds only what the count needs: a random session ID +//! made when the game starts and kept only in its memory (not the install ID), the Horizon +//! version, the platform and whether a LAN or play-with-friends world is open. The game sends +//! one every [`INTERVAL`]; the server counts a session while its last ping is under +//! [`WINDOW`] old, keeps nothing on disk and serves the counts rounded ([`round`]). +use std::collections::BTreeMap; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; + +/// How often the game pings while it runs. +pub const INTERVAL: Duration = Duration::from_secs(60); + +/// How long a session counts after its last ping: two pings, so one lost on the way doesn't +/// drop it. +pub const WINDOW: Duration = Duration::from_secs(120); + +/// The platforms a ping may name; anything else is `other`. +pub const PLATFORMS: [&str; 4] = ["linux", "macos", "windows", "other"]; + +/// The largest ping body the server reads. +pub const MAX_PING_BYTES: usize = 512; + +const MAX_VERSION: usize = 40; + +/// One "I'm playing", as it is sent: `{"session":"…","version":"…","platform":"…","lan":false}`. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Ping { + /// 128 random bits in hex, made when the game starts ([`session_id`]) and never written down. + pub session: String, + /// The release (`v2026.10.15`, `0.2.0`) or `dev 0.1.0` for a build from source. + pub version: String, + /// One of [`PLATFORMS`]. + pub platform: String, + /// A world is open to LAN or to friends over the internet. + pub lan: bool, +} + +impl Ping { + pub fn new(session: &str, version: &str, lan: bool) -> Self { + Self { + session: session.to_owned(), + version: version.to_owned(), + platform: platform().to_owned(), + lan, + } + } + + /// Why the server refuses this ping, if it does. + pub fn check(&self) -> Result<(), &'static str> { + if !crate::consent::is_install_id(&self.session) { + return Err("session: 32 lowercase hex digits"); + } + let version_ok = !self.version.is_empty() + && self.version.len() <= MAX_VERSION + && self + .version + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b" .+-_".contains(&b)); + if !version_ok { + return Err("version: at most 40 letters, digits, spaces and .+-_"); + } + if !PLATFORMS.contains(&self.platform.as_str()) { + return Err("platform: linux, macos, windows or other"); + } + Ok(()) + } +} + +/// A new session ID: 128 random bits in hex. +pub fn session_id() -> String { + crate::random_hex(16) +} + +/// This machine's entry in [`PLATFORMS`]. +pub fn platform() -> &'static str { + match std::env::consts::OS { + os @ ("linux" | "macos" | "windows") => os, + _ => "other", + } +} + +/// The live count, as `GET /v1/live` serves it: every number already [`round`]ed. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Count { + /// Sessions that pinged within the window. + pub playing: u64, + /// Of those, the ones with a LAN or play-with-friends world open. + pub lan: u64, + /// Per version: the most played ones, the rest summed under `other`. + pub versions: BTreeMap, + /// Per platform. + pub platforms: BTreeMap, +} + +/// Rounds a count for showing: exact under 10, then to the nearest 5 under 100, the nearest 10 +/// under 1000 and the nearest 100 above. Small numbers stay true; large ones don't pretend to +/// a precision a two-minute window doesn't have. +pub fn round(n: u64) -> u64 { + let step = match n { + 0..10 => return n, + 10..100 => 5, + 100..1000 => 10, + _ => 100, + }; + (n + step / 2) / step * step +} + +/// Sends `ping` to `endpoint` (`https://host`, without a trailing slash). +#[cfg(feature = "live")] +pub fn send(endpoint: &str, ping: &Ping) -> Result<(), String> { + agent() + .post(&format!("{endpoint}/v1/live")) + .set("Content-Type", "application/json") + .send_string(&serde_json::to_string(ping).map_err(|e| e.to_string())?) + .map(drop) + .map_err(|e| e.to_string()) +} + +/// The live count at `endpoint`. +#[cfg(feature = "live")] +pub fn fetch(endpoint: &str) -> Result { + let body = agent() + .get(&format!("{endpoint}/v1/live")) + .call() + .map_err(|e| e.to_string())? + .into_string() + .map_err(|e| e.to_string())?; + serde_json::from_str(&body).map_err(|e| e.to_string()) +} + +#[cfg(feature = "live")] +fn agent() -> ureq::Agent { + ureq::AgentBuilder::new() + .timeout(Duration::from_secs(5)) + .build() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ping() -> Ping { + Ping::new(&session_id(), "v2026.10.15", false) + } + + #[test] + fn a_ping_holds_only_the_four_fields() { + let json = serde_json::to_value(Ping::new(&"a".repeat(32), "0.2.0", true)).unwrap(); + let mut keys: Vec<&str> = json + .as_object() + .unwrap() + .keys() + .map(|k| k.as_str()) + .collect(); + keys.sort_unstable(); + assert_eq!(keys, ["lan", "platform", "session", "version"]); + assert!(serde_json::to_string(&ping()).unwrap().len() < MAX_PING_BYTES); + } + + #[test] + fn session_ids_are_fresh_each_time() { + let (a, b) = (session_id(), session_id()); + assert_ne!(a, b); + assert!(ping().check().is_ok()); + } + + #[test] + fn bad_pings_are_refused() { + let bad = |f: fn(&mut Ping)| { + let mut p = ping(); + f(&mut p); + p.check().is_err() + }; + assert!(bad(|p| p.session = "ABC".into())); + assert!(bad(|p| p.session = "G".repeat(32))); + assert!(bad(|p| p.version = String::new())); + assert!(bad(|p| p.version = "1".repeat(41))); + assert!(bad(|p| p.version = "