From d422564ab3f292d0c5be6a24073f540069417406 Mon Sep 17 00:00:00 2001 From: Eshayat Al-Wasiu Date: Mon, 26 Oct 2026 13:16:45 +0600 Subject: [PATCH 1/6] Respect tool restrictions on Creative block destruction Check the tool component before server destruction, local mining and remote prediction. Cover vanilla item defaults, overrides and mode-switch cancellation. Co-Authored-By: OpenAI GPT-6.1 Sol --- .../examples/probe/creative_mining_probe.rs | 48 ++++++++++++++ crates/horizon-client/examples/probe/main.rs | 2 + crates/horizon-client/src/game.rs | 14 +++- crates/horizon-client/src/game/remote.rs | 9 +++ crates/horizon-client/src/items.rs | 26 ++++++++ .../parity/VanillaCreativeMiningOracle.java | 64 +++++++++++++++++++ tests/test_remote_mining.py | 28 ++++++-- tools/lan_e2e.py | 38 +++++++++++ tools/test_creative_mining_parity.py | 35 ++++++++++ 9 files changed, 259 insertions(+), 5 deletions(-) create mode 100644 crates/horizon-client/examples/probe/creative_mining_probe.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCreativeMiningOracle.java create mode 100644 tools/test_creative_mining_parity.py diff --git a/crates/horizon-client/examples/probe/creative_mining_probe.rs b/crates/horizon-client/examples/probe/creative_mining_probe.rs new file mode 100644 index 000000000..897e4bf81 --- /dev/null +++ b/crates/horizon-client/examples/probe/creative_mining_probe.rs @@ -0,0 +1,48 @@ +use horizon_client::{ + Result, + item_data::StackData, + items::{ItemStack, Items}, +}; +use horizon_world::nbt::Tag; +use serde_json::Value; +use std::{ + fs::File, + io::{BufRead, BufReader, BufWriter, Write}, + path::Path, +}; + +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().collect(); + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3"); + let items = Items::catalog(&root)?; + let mut out = BufWriter::new(File::create(&args[2])?); + for line in BufReader::new(File::open(&args[1])?).lines() { + let row: Value = serde_json::from_str(&line?)?; + let mut stack = ItemStack::new( + row["item"].as_str().unwrap(), + row["count"].as_u64().unwrap() as u32, + ); + match row["tool"].as_str().unwrap() { + "default" => {} + mode => { + let mut data = StackData::default(); + let tool = if mode == "implicit" { + Tag::compound([] as [(&str, Tag); 0]) + } else { + Tag::compound([( + "can_destroy_blocks_in_creative", + Tag::Byte(i8::from(mode == "allow")), + )]) + }; + data.set_other("minecraft:tool", Some(tool)); + stack.extra = Some(Box::new(data)); + } + } + writeln!( + out, + "{}", + items.can_destroy_block(Some(&stack), row["creative"].as_bool().unwrap()) + )?; + } + Ok(()) +} diff --git a/crates/horizon-client/examples/probe/main.rs b/crates/horizon-client/examples/probe/main.rs index e80088fd0..c803dcf2f 100644 --- a/crates/horizon-client/examples/probe/main.rs +++ b/crates/horizon-client/examples/probe/main.rs @@ -27,6 +27,7 @@ mod chat_screen_fixture; mod cloud_fixture; mod command_parse_fixture; mod container_screen_probe; +mod creative_mining_probe; mod creative_search_fixture; mod emitter_particles_probe; mod enchanting_fixture; @@ -107,6 +108,7 @@ probes! { block_transform_fixture, breaking_fixture, camera_probe, + creative_mining_probe, cauldron_fixture, chat_screen_fixture, cloud_fixture, diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index f7dffb734..1073b7308 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3318,6 +3318,13 @@ impl Game<'_> { self.with_player_actor(|game| game.break_block_as_player(pos)) } fn break_block_as_player(&mut self, pos: [i32; 3]) -> Result<()> { + if !self + .res + .items() + .can_destroy_block(self.held(), self.creative) + { + return Ok(()); + } self.pad_rumble(horizon_client::gamepad::Rumble::BlockBroken); // ServerPlayerGameMode.destroyBlock. let state = self.world.block(pos[0], pos[1], pos[2]); @@ -3936,7 +3943,12 @@ impl Game<'_> { return Ok(()); }; // GameType.isBlockPlacingRestricted: adventure and spectator. - if !self.may_build() { + if !self.may_build() + || !self + .res + .items() + .can_destroy_block(self.held(), self.creative) + { self.mining = None; return Ok(()); } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3a2dd1d69..e18e49949 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3779,6 +3779,15 @@ impl Game<'_> { /// MultiPlayerGameMode.startDestroyBlock / continueDestroyBlock. fn remote_mining(&mut self, start: bool) { + if !self + .res + .items() + .can_destroy_block(self.held(), self.creative) + { + self.stop_remote_mining(); + self.mining = None; + return; + } let Some(r) = self.remote.as_mut() else { return; }; diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index 8ac450bcb..b35bcdc29 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -71,6 +71,8 @@ pub struct ItemInfo { /// The `tool` component's `damage_per_block`, when the item has the /// component (a mace or trident has one without rules). pub tool_damage_per_block: Option, + /// `tool.can_destroy_blocks_in_creative` (defaults to true). + pub can_destroy_blocks_in_creative: bool, pub food: Option<(u32, f32)>, pub can_always_eat: bool, /// `consumable`: its timing, sound, particles and `on_consume_effects`. @@ -552,6 +554,10 @@ impl Items { tool_damage_per_block: c .get("minecraft:tool") .map(|t| t["damage_per_block"].as_u64().unwrap_or(1) as u32), + can_destroy_blocks_in_creative: + c["minecraft:tool"]["can_destroy_blocks_in_creative"] + .as_bool() + .unwrap_or(true), food, can_always_eat, // Consumable.CODEC's defaults. @@ -746,6 +752,26 @@ impl Items { None => spec == block, } } + /// `Item.canDestroyBlock`: a tool may forbid block destruction with instabuild. + pub fn can_destroy_block(&self, held: Option<&ItemStack>, creative: bool) -> bool { + if !creative { + return true; + } + let Some(held) = held.filter(|s| s.count > 0 && &*s.item != "minecraft:air") else { + return true; + }; + if let Some(tool) = held.data().and_then(|d| d.other("minecraft:tool")) { + return tool + .get("can_destroy_blocks_in_creative") + .and_then(|v| match v { + horizon_world::nbt::Tag::Byte(v) => Some(*v), + _ => None, + }) + .is_none_or(|v| v != 0); + } + self.get(&held.item) + .is_none_or(|info| info.can_destroy_blocks_in_creative) + } /// `Tool.getMiningSpeed` for the held item (1.0 without a tool component). pub fn mining_speed(&self, held: Option<&ItemStack>, block: &str) -> f32 { let Some(info) = held.and_then(|s| self.get(&s.item)) else { diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCreativeMiningOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCreativeMiningOracle.java new file mode 100644 index 000000000..7d1d5f6e3 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCreativeMiningOracle.java @@ -0,0 +1,64 @@ +package dev.horizonlab.parity; + +import com.google.gson.JsonParser; +import java.io.PrintWriter; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import net.minecraft.core.component.DataComponents; +import net.minecraft.core.component.DataComponentMap; +import com.mojang.serialization.JsonOps; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.Identifier; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.player.Abilities; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.Tool; + +/** Calls the actual item predicate; its unused block and level arguments are null. */ +public final class VanillaCreativeMiningOracle { + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion(); + net.minecraft.server.Bootstrap.bootStrap(); + var defaults = JsonParser.parseString(Files.readString(Path.of(args[0]).getParent() + .getParent().resolve("horizon-client/26.3/items.json"))).getAsJsonObject(); + for (var entry : defaults.entrySet()) { + var item = BuiltInRegistries.ITEM.getValue(Identifier.parse(entry.getKey())); + var components = DataComponentMap.builder(); + var tool = entry.getValue().getAsJsonObject().getAsJsonObject("minecraft:tool"); + if (tool != null) { + // Only the restriction is queried here; mining-rule tag resolution is separate. + tool = tool.deepCopy(); + tool.add("rules", new com.google.gson.JsonArray()); + components.set(DataComponents.TOOL, Tool.CODEC.parse(JsonOps.INSTANCE, tool).getOrThrow()); + } + item.builtInRegistryHolder().bindComponents(components.build()); + } + var unsafeClass = Class.forName("sun.misc.Unsafe"); + var unsafeField = unsafeClass.getDeclaredField("theUnsafe"); + unsafeField.setAccessible(true); + var unsafe = unsafeField.get(null); + var player = (ServerPlayer) unsafeClass.getMethod("allocateInstance", Class.class) + .invoke(unsafe, ServerPlayer.class); + var abilities = new Abilities(); + var field = Player.class.getDeclaredField("abilities"); + field.setAccessible(true); + field.set(player, abilities); + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]))); + var lines = Files.lines(Path.of(args[0]))) { + for (var line : (Iterable) lines::iterator) { + var row = JsonParser.parseString(line).getAsJsonObject(); + var item = BuiltInRegistries.ITEM.getValue(Identifier.parse(row.get("item").getAsString())); + var stack = new ItemStack(item, row.get("count").getAsInt()); + var mode = row.get("tool").getAsString(); + if (!mode.equals("default")) { + stack.set(DataComponents.TOOL, new Tool(List.of(), 1.0f, 1, !mode.equals("deny"))); + } + abilities.instabuild = row.get("creative").getAsBoolean(); + // Use the base Item implementation: special debug-stick interactions are separate. + out.println(net.minecraft.world.item.Items.STICK.canDestroyBlock(stack, null, null, null, player)); + } + } + } +} diff --git a/tests/test_remote_mining.py b/tests/test_remote_mining.py index 1a35b3865..9feb255fa 100644 --- a/tests/test_remote_mining.py +++ b/tests/test_remote_mining.py @@ -18,7 +18,7 @@ ROOT = Path(__file__).resolve().parents[1] class RemoteMiningTests(unittest.TestCase): def test_break_timing_and_packets(self): source = (ROOT / "crates/horizon-client/src/game/remote.rs").read_text() - start = source.index(" fn remote_mining(") + start = source.index(" pub(super) fn stop_remote_mining(") end = source.index(" /// MultiPlayerGameMode.destroyBlock", start) fixture = r''' #![allow(dead_code)] @@ -33,8 +33,11 @@ struct Player { ground: Ground } struct Sounds { hit: String, volume: f32, pitch: f32 } #[derive(Clone)] struct Facts { hardness: f32, name: String, requires_tool: bool, sounds: Sounds } -struct Resources { facts: Facts, speed: f32 } +struct Resources { facts: Facts, speed: f32, tool_allows_creative: bool } impl Resources { + fn can_destroy_block(&self, _: Option<&()>, creative: bool) -> bool { + !creative || self.tool_allows_creative + } fn facts(&self) -> &Self { self } fn items(&self) -> &Self { self } fn get(&self, _: u32) -> &Facts { &self.facts } @@ -72,7 +75,7 @@ impl Game { remote: Some(Remote::default()), mining: None, creative, world: World::default(), res: Resources { facts: Facts { hardness, name: "block".into(), - requires_tool: false, sounds: Sounds { hit: "hit".into(), volume: 1.0, pitch: 1.0 } }, speed }, + requires_tool: false, sounds: Sounds { hit: "hit".into(), volume: 1.0, pitch: 1.0 } }, speed, tool_allows_creative: true }, player: Some(Player { ground: Ground { on_ground: true } }), audio: Audio, hit: Hit { pos: [0, 64, 0], face: 1 }, sequence: 0, packets: vec![], } @@ -138,8 +141,25 @@ fn main() { game.remote_mining(false); assert_eq!(game.world.broken.len(), 2); assert_eq!(game.remote.as_ref().unwrap().destroy_delay, 5); + // A restricted tool must neither predict a break nor send START in Creative. + let mut game = Game::new(1.0, 1.0, true); + game.res.tool_allows_creative = false; + game.remote_mining(true); + game.remote_mining(false); + assert!(game.world.broken.is_empty()); + assert!(game.packets.is_empty()); + // Survival still mines with the same tool. Switching to Creative aborts the crack. + game.creative = false; + game.remote_mining(true); + assert_eq!(game.packets[0].action, 0); + game.creative = true; + game.remote_mining(false); + assert_eq!(game.packets.iter().map(|p| p.action).collect::>(), [0, 2]); + assert!(game.remote.as_ref().unwrap().destroying.is_none()); + assert!(game.mining.is_none()); + assert!(game.world.broken.is_empty()); } -'''.replace("METHOD", source[start:end]) +'''.replace("METHOD", source[start:end].replace("pub(super) fn", "fn")) with tempfile.TemporaryDirectory(prefix="remote-mining-") as directory: path = Path(directory) (path / "main.rs").write_text(fixture) diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 804add98a..8592c3e35 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -6591,5 +6591,43 @@ CHECKS += ['replant'] CHECK_FNS['replant'] = check_replant +def check_creative_tools(host, guest, out): + """#2035: switching Survival -> Creative cannot mine with a restricted tool. + Verify both the player's prediction and the host's authoritative block; + an ordinary tool must still break the same block. + """ + seen = {} + for label, player in (('host', host), ('guest', guest)): + x, y, z = (int(v // 1) for v in pos_of(player)) + cell = (x, y + 1, z + 2) + host('command', command=f'fill {x - 1} {y} {z + 1} {x + 1} {y + 3} {z + 3} minecraft:air') + player('command', command='gamemode survival') + player('command', command='item replace entity @s weapon.mainhand with minecraft:netherite_sword') + player('command', command='gamemode creative') + host('command', command=f'setblock {cell[0]} {cell[1]} {cell[2]} minecraft:stone') + player.wait(10) + player.raw('look-at', x + 0.5, y + 1.5, z + 2.5) + player.raw('mouse', 'left', 'down') + try: + player.wait(15) + finally: + player.raw('mouse', 'left', 'up') + seen[label] = {'client': player.raw('block', *cell).get('block'), + 'server': host.raw('block', *cell).get('block')} + player.shot(out, 'creative-sword') + assert seen[label]['client'] == seen[label]['server'] == 'minecraft:stone', seen + player('command', command='item replace entity @s weapon.mainhand with minecraft:diamond_pickaxe') + player.wait(6) + player.raw('mouse', 'left', 'click') + player.wait(10) + seen[label]['ordinary_tool'] = host.raw('block', *cell).get('block') + assert seen[label]['ordinary_tool'] == 'minecraft:air', seen + return seen + + +CHECKS += ['creative_tools'] +CHECK_FNS['creative_tools'] = check_creative_tools + + if __name__ == '__main__': main() diff --git a/tools/test_creative_mining_parity.py b/tools/test_creative_mining_parity.py new file mode 100644 index 000000000..3e6bfed1a --- /dev/null +++ b/tools/test_creative_mining_parity.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +"""Compare Creative mining eligibility for every item and tool overrides.""" +import json + +try: + from . import lab, oracle_harness as harness +except ImportError: + import lab, oracle_harness as harness + + +def make_input(build): + resources = lab.LOCAL / 'horizon-client' / '26.3' + items = json.loads((resources / 'items.json').read_text()) + rows = [dict(item=item, creative=creative, count=count, tool=tool) + for item in sorted(items) + for creative in (False, True) + for count in (0, 1) + for tool in ('default', 'allow', 'deny', 'implicit')] + path = build / 'inputs.jsonl' + path.write_text(''.join(json.dumps(row) + '\n' for row in rows)) + return path, len(rows) + + +def main(): + harness.differential( + 'rust-creative-mining-parity', 'VanillaCreativeMiningOracle', + 'creative_mining_probe', make_input, + 'Item.canDestroyBlock with each vanilla item, empty stacks, Survival/Creative ' + 'abilities, and explicit/implicit tool overrides. Block destruction and network ' + 'prediction call this predicate; end-to-end packet handling is not covered here.', + sources=[lab.ROOT / 'crates/horizon-client/src/items.rs']) + + +if __name__ == '__main__': + main() From fc0b73954f28fe022b0f9ac4ace3392118469108 Mon Sep 17 00:00:00 2001 From: FusselTV Date: Sun, 25 Oct 2026 20:28:49 +0100 Subject: [PATCH 2/6] x A container whose items no longer match its roll is saved without the table, also when it was loaded with one, so a chest emptied after a load does not fill again on the next one. A zero LootTableSeed is left out, as trySaveLootTable does. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/fishing.rs | 2 +- crates/horizon-client/src/game/minecarts.rs | 10 ++ crates/horizon-client/src/game/persist.rs | 27 +++- crates/horizon-client/src/save.rs | 147 ++++++++++++++++- crates/horizon-client/src/structure_blocks.rs | 149 ++++++++++-------- crates/horizon-client/src/vanillagen.rs | 11 +- 6 files changed, 274 insertions(+), 72 deletions(-) diff --git a/crates/horizon-client/src/game/fishing.rs b/crates/horizon-client/src/game/fishing.rs index d454df406..22cb3774b 100644 --- a/crates/horizon-client/src/game/fishing.rs +++ b/crates/horizon-client/src/game/fishing.rs @@ -231,7 +231,7 @@ impl Game<'_> { } damage } - fn biome_name_at(&self, p: Vec3) -> Option { + pub(super) fn biome_name_at(&self, p: Vec3) -> Option { let (x, y, z) = (p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32); let c = self.world.chunks.get(&(x >> 4, z >> 4))?; Some( diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index 8d4920b48..3ab6ae304 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -87,6 +87,9 @@ pub(super) struct Minecart { pub fuse: i32, /// Hopper minecarts: an unpowered activator rail enables them. pub enabled: bool, + /// Chest minecarts: the loot table rolled into `items` on load, saved + /// again while the items are still that roll. + pub loot: Option, } const WIDTH: f64 = 0.98; const HEIGHT: f64 = 0.7; @@ -182,6 +185,7 @@ impl Minecart { push: [0.0; 2], fuse: -1, enabled: true, + loot: None, } } pub fn bounds(&self) -> Aabb { @@ -1514,6 +1518,12 @@ impl Minecart { } CartKind::Rideable => {} } + // A loaded loot table goes back while the items are still its roll; + // otherwise the items replace it, as vanilla's unpackLootTable does. + if !self.loot.as_ref().is_some_and(|l| l.restore(map)) { + map.remove(&JavaString::from("LootTable")); + map.remove(&JavaString::from("LootTableSeed")); + } } tag } diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 45ef8801f..24fd9a5aa 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -279,7 +279,8 @@ impl Game<'_> { k if super::minecarts::CartKind::from_id(k).is_some() => { let kind = super::minecarts::CartKind::from_id(k).unwrap(); let id = self.next_entity + 1; - if let Some(c) = super::minecarts::Minecart::from_nbt(&tag, id, kind) { + if let Some(mut c) = super::minecarts::Minecart::from_nbt(&tag, id, kind) { + self.roll_cart_loot(&mut c, &tag); self.next_entity = id; self.remember(id, uuid, tag); self.carts.push(c); @@ -527,6 +528,30 @@ impl Game<'_> { pub(super) fn persist_raw(&self, id: u32) -> Option<&Tag> { self.persist.raw.get(&id) } + /// A loaded chest minecart with a loot table and no items: the table + /// rolled now, as generated containers are (Horizon does not unpack on + /// first open), and kept to save it again while unchanged. + fn roll_cart_loot(&self, cart: &mut super::minecarts::Minecart, tag: &Tag) { + let Some(table) = horizon_client::save::text(tag.get("LootTable")) else { + return; + }; + if cart.items.is_empty() || cart.items.iter().any(Option::is_some) { + return; + } + let loot = horizon_client::structure_blocks::loot_data(&self.options.resources); + let p = cart.position; + let pos = (p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32); + let biome = self.biome_name_at(p).unwrap_or_default(); + let seed = horizon_client::structure_blocks::loot_seed(tag); + cart.loot = Some(horizon_client::structure_blocks::roll_container( + &mut cart.items, + loot.as_deref(), + table, + seed, + pos, + &biome, + )); + } fn remember(&mut self, id: u32, uuid: Option<[i32; 4]>, tag: Tag) { self.restore_portal_cooldown(id, &tag); if let Some(u) = uuid { diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 0c353bb38..783aa506d 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -297,6 +297,35 @@ impl SaveTables { } } +/// A container's loot table and what Horizon rolled from it. Vanilla keeps +/// `LootTable` and `LootTableSeed` until the container is first opened; +/// Horizon rolls when it generates or loads the chunk, and saves the table +/// again while the container still holds exactly the rolled items. +#[derive(Clone, Debug, PartialEq)] +pub struct RolledLoot { + pub pos: (i32, i32, i32), + pub table: String, + /// The saved `LootTableSeed`, written back unless 0 (trySaveLootTable). + pub seed: Option, + /// The rolled `Items`. + pub items: Tag, +} +impl RolledLoot { + /// Puts the loot table back in place of `Items` while they are still the + /// roll; false once the container holds anything else. + pub fn restore(&self, map: &mut Compound) -> bool { + if map.get(&"Items".into()) != Some(&self.items) { + return false; + } + map.remove(&"Items".into()); + map.insert("LootTable".into(), string(&self.table)); + if let Some(seed) = self.seed.filter(|s| *s != 0) { + map.insert("LootTableSeed".into(), Tag::Long(seed)); + } + true + } +} + /// Save data loaded with a chunk that Horizon keeps but does not simulate. #[derive(Clone, Debug, Default)] pub struct ChunkExtras { @@ -318,6 +347,8 @@ pub struct ChunkExtras { pub fluid_ticks: Vec, /// Game time written as `LastUpdate`. pub last_update: i64, + /// Containers still holding their loot table's roll. + pub rolled_loot: Vec, } fn tick_list(ticks: &[SavedTick], name: impl Fn(u32) -> Option) -> Tag { @@ -594,6 +625,34 @@ pub fn decode_banner(tag: &Tag) -> crate::containers::Banner { }, } } +/// A loaded container with a loot table and no items yet, rolled as +/// generation rolls it (Horizon does not unpack on first open). +fn roll_loaded_loot( + chunk: &Chunk, + biomes: &Biomes, + tag: &Tag, + be: &mut ((i32, i32, i32), crate::containers::BlockEntity), +) -> Option { + let crate::containers::BlockEntity::Chest(slots) = &mut be.1 else { + return None; + }; + let table = text(tag.get("LootTable"))?; + if slots.iter().any(Option::is_some) { + return None; + } + let loot = crate::structure_blocks::loaded_loot_data()?; + let (x, y, z) = be.0; + let biome = &biomes.get(chunk.biome(x & 15, y, z & 15)).name; + let seed = crate::structure_blocks::loot_seed(tag); + Some(crate::structure_blocks::roll_container( + slots, + Some(&loot), + table, + seed, + be.0, + biome, + )) +} pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers::BlockEntity)> { use crate::containers::BlockEntity; let int = |k: &str| number(tag.get(k)).map(|v| v as i32); @@ -959,7 +1018,16 @@ pub fn encode_with( } None => current, }; - crate::block_entity_nbt::canonical(&merged).unwrap_or(merged) + let mut saved = crate::block_entity_nbt::canonical(&merged).unwrap_or(merged); + if let Some(r) = extras.and_then(|x| x.rolled_loot.iter().find(|r| r.pos == *p)) + && let Tag::Compound(map) = &mut saved + && !r.restore(map) + { + // A loaded source still carries the table; kept, it rolls again on load. + map.remove(&"LootTable".into()); + map.remove(&"LootTableSeed".into()); + } + saved }) .collect(); if let Some(extras) = extras { @@ -1189,10 +1257,13 @@ fn decode_column( extras.block_entity_order.push((x, y, z)); } match decode_block_entity(e) { - Some(be) => { + Some(mut be) => { if let Some(name) = text(e.get("CustomName")) { chunk.block_names.push((be.0, name)); } + if let Some(rolled) = roll_loaded_loot(&chunk, biomes, e, &mut be) { + extras.rolled_loot.push(rolled); + } extras.block_entity_sources.push((be.0, e.clone())); chunk.block_entities.push(be); } @@ -3436,6 +3507,78 @@ impl ChunkGenerator for Persistent { #[cfg(test)] mod tests { + #[test] + fn unopened_rolled_containers_save_their_loot_table() { + let Some(root) = std::env::var_os("HORIZON_TEST_RESOURCES") else { + return; + }; + let root = PathBuf::from(root); + let assets = crate::assets::Assets::load(&root).expect("assets"); + let biomes = Biomes::load(&root).expect("biomes"); + let tables = SaveTables::new(&assets); + let chest = assets.registry.default_state("minecraft:chest").unwrap(); + let mut slots = vec![None; 27]; + slots[3] = Some(crate::items::ItemStack::new("minecraft:bone", 2)); + let mut chunk = Chunk::empty(0, 0); + chunk.set(1, 64, 2, chest.0); + chunk.block_entities.push(( + (1, 64, 2), + crate::containers::BlockEntity::Chest(slots.clone()), + )); + let rolled = RolledLoot { + pos: (1, 64, 2), + table: "minecraft:chests/simple_dungeon".into(), + seed: Some(42), + items: encode_items(&slots), + }; + chunk.saved = Some(Arc::new(ChunkExtras { + rolled_loot: vec![rolled], + ..ChunkExtras::default() + })); + let saved_chest = |chunk: &Chunk| -> Tag { + let saved = encode_with(chunk, assets.registry, &biomes, Some(&tables), true); + let Some(Tag::List(list)) = saved.tag.get("block_entities") else { + panic!("no block entities"); + }; + list[0].clone() + }; + let unopened = saved_chest(&chunk); + assert_eq!( + text(unopened.get("LootTable")).as_deref(), + Some("minecraft:chests/simple_dungeon") + ); + assert_eq!(number(unopened.get("LootTableSeed")), Some(42)); + assert!(unopened.get("Items").is_none()); + // Taking an item makes the items the container's own. + if let crate::containers::BlockEntity::Chest(s) = &mut chunk.block_entities[0].1 { + s[3] = None; + s[4] = Some(crate::items::ItemStack::new("minecraft:bone", 1)); + } + let opened = saved_chest(&chunk); + assert!(opened.get("LootTable").is_none()); + assert!(opened.get("Items").is_some()); + // Loaded with its table, rolled, then emptied: no table, or it refills on load. + let mut extras = ChunkExtras::clone(chunk.saved.as_ref().unwrap()); + extras.block_entity_sources = vec![( + (1, 64, 2), + Tag::compound([ + ("id", string("minecraft:chest")), + ("x", Tag::Int(1)), + ("y", Tag::Int(64)), + ("z", Tag::Int(2)), + ("LootTable", string("minecraft:chests/simple_dungeon")), + ("LootTableSeed", Tag::Long(42)), + ]), + )]; + chunk.saved = Some(Arc::new(extras)); + if let crate::containers::BlockEntity::Chest(s) = &mut chunk.block_entities[0].1 { + s.fill(None); + } + let emptied = saved_chest(&chunk); + assert!(emptied.get("LootTable").is_none()); + assert!(emptied.get("LootTableSeed").is_none()); + } + #[test] fn saved_far_surface_reads_builds_and_water_without_gameplay_chunks() { let Some(root) = std::env::var_os("HORIZON_TEST_RESOURCES") else { diff --git a/crates/horizon-client/src/structure_blocks.rs b/crates/horizon-client/src/structure_blocks.rs index 9503294e0..f77696277 100644 --- a/crates/horizon-client/src/structure_blocks.rs +++ b/crates/horizon-client/src/structure_blocks.rs @@ -108,9 +108,10 @@ pub fn has_pending_map(item: &ItemStack) -> bool { }) } +static LOOT: OnceLock>> = OnceLock::new(); + /// Loot data of the resource root, loaded once per process. pub fn loot_data(root: &Path) -> Option> { - static LOOT: OnceLock>> = OnceLock::new(); LOOT.get_or_init(|| match LootData::load(root) { Ok(data) => Some(Arc::new(data)), Err(e) => { @@ -121,6 +122,54 @@ pub fn loot_data(root: &Path) -> Option> { .clone() } +/// The loot data `loot_data` loaded, if it ran. +pub fn loaded_loot_data() -> Option> { + LOOT.get().cloned().flatten() +} + +/// `RandomizableContainer.unpackLootTable` of a container at `pos`: `table` +/// rolled into `slots`. A missing or zero seed is the level's random in +/// vanilla; Horizon derives one from the position. Without loot data the +/// container stays empty and still saves its table. +pub fn roll_container( + slots: &mut [Option], + loot: Option<&LootData>, + table: String, + saved_seed: Option, + pos: (i32, i32, i32), + biome: &str, +) -> crate::save::RolledLoot { + let seed = saved_seed.filter(|s| *s != 0).unwrap_or_else(|| { + horizon_core::random::position_seed(horizon_core::position::BlockPos::new( + pos.0, pos.1, pos.2, + )) + }); + if let Some(loot) = loot { + // LootTable.fill spreads the items over the container's own size. + let rolled = loot.fill(&table, seed, slots.len(), Some(biome)); + for (slot, stack) in slots.iter_mut().zip(rolled) { + // With what the rolls put on them: enchantments + // (enchant_with_levels in End city chests), potions and an + // ominous bottle's level. + *slot = stack.map(|s| loot_item_with_components(&s)); + } + } + crate::save::RolledLoot { + pos, + table, + seed: saved_seed, + items: crate::save::encode_items(slots), + } +} + +/// A saved `LootTableSeed`, if any. +pub fn loot_seed(nbt: &Tag) -> Option { + match nbt.get("LootTableSeed") { + Some(Tag::Long(seed)) => Some(*seed), + _ => None, + } +} + fn text(nbt: &Compound, key: &str) -> Option { match nbt.get(&JavaString::from(key)) { Some(Tag::String(s)) => Some(s.to_string_lossy()), @@ -149,81 +198,37 @@ fn generated_block_entity(block: &str, nbt: &Compound) -> Option { Some(entity) } -/// Client block entities for the generated block entities of a chunk. +/// Client block entities for the generated block entities of a chunk, and the +/// loot rolled into its containers. pub fn block_entities( chunk: &ProtoChunk, loot: Option<&LootData>, -) -> Vec<((i32, i32, i32), BlockEntity)> { +) -> ( + Vec<((i32, i32, i32), BlockEntity)>, + Vec, +) { let mut out = Vec::new(); + let mut rolled = Vec::new(); for (pos, nbt) in &chunk.block_entities { let [x, y, z] = *pos; let block = chunk.block_name(x, y, z); let Some(mut entity) = generated_block_entity(block, nbt) else { continue; }; - if let (BlockEntity::Chest(slots), Some(table), Some(loot)) = - (&mut entity, text(nbt, "LootTable"), loot) - { - let seed = match nbt.get(&JavaString::from("LootTableSeed")) { - Some(Tag::Long(seed)) => *seed, - // Seed 0 means "the level's random": derive one from the position. - _ => horizon_core::random::position_seed(horizon_core::position::BlockPos::new( - x, y, z, - )), - }; - let biome = chunk.biome_at(x, y, z); - for (slot, stack) in slots - .iter_mut() - .zip(loot.fill(&table, seed, 27, Some(biome))) - { - // With what the rolls put on them: enchantments - // (enchant_with_levels in End city chests), potions and an - // ominous bottle's level. - *slot = stack.map(|s| loot_item_with_components(&s)); - } + if let (BlockEntity::Chest(slots), Some(table)) = (&mut entity, text(nbt, "LootTable")) { + let seed = loot_seed(&Tag::Compound(nbt.clone())); + rolled.push(roll_container( + slots, + loot, + table, + seed, + (x, y, z), + chunk.biome_at(x, y, z), + )); } out.push(((x, y, z), entity)); } - out -} - -/// Chest minecarts placed with a loot table (mineshafts): the table rolled -/// into `Items` as `unpackLootTable` would on first open. -pub fn unpack_entity_loot( - chunk: &ProtoChunk, - mut nbt: horizon_world::nbt::Compound, - loot: Option<&LootData>, -) -> horizon_world::nbt::Compound { - let (Some(table), Some(loot)) = ( - match nbt.get(&JavaString::from("LootTable")) { - Some(Tag::String(s)) => Some(s.to_string_lossy()), - _ => None, - }, - loot, - ) else { - return nbt; - }; - let seed = match nbt.get(&JavaString::from("LootTableSeed")) { - Some(Tag::Long(seed)) => *seed, - _ => 0, - }; - let pos = match nbt.get(&JavaString::from("Pos")) { - Some(Tag::List(p)) => std::array::from_fn(|i| match p.get(i) { - Some(Tag::Double(b)) => f64::from_bits(*b).floor() as i32, - _ => 0, - }), - _ => [0; 3], - }; - let biome = chunk.biome_at(pos[0], pos[1], pos[2]); - let slots: Vec> = loot - .fill(&table, seed, 27, Some(biome)) - .into_iter() - .map(|s| s.map(|s| loot_item_with_components(&s))) - .collect(); - nbt.remove(&JavaString::from("LootTable")); - nbt.remove(&JavaString::from("LootTableSeed")); - nbt.insert("Items".into(), crate::save::encode_items(&slots)); - nbt + (out, rolled) } #[cfg(test)] @@ -270,6 +275,24 @@ mod tests { assert_eq!(arrow.potion(), Some("minecraft:slowness")); } + #[test] + fn a_container_rolled_without_loot_data_saves_its_table() { + let mut slots = vec![None; 27]; + let rolled = roll_container( + &mut slots, + None, + "minecraft:chests/simple_dungeon".into(), + Some(7), + (1, 2, 3), + "minecraft:plains", + ); + let mut saved = horizon_world::nbt::Compound::new(); + saved.insert("Items".into(), crate::save::encode_items(&slots)); + assert!(rolled.restore(&mut saved)); + assert!(!saved.contains_key(&"Items".into())); + assert_eq!(saved.get(&"LootTableSeed".into()), Some(&Tag::Long(7))); + } + #[test] fn exploration_maps_wait_in_custom_data_until_searched() { let mut stack = LootStack { diff --git a/crates/horizon-client/src/vanillagen.rs b/crates/horizon-client/src/vanillagen.rs index c890213c5..441375b23 100644 --- a/crates/horizon-client/src/vanillagen.rs +++ b/crates/horizon-client/src/vanillagen.rs @@ -531,7 +531,9 @@ impl ChunkGenerator for VanillaTerrain { VanillaProto::Failed(x, z) => return Chunk::empty(x, z), }; let mut out = self.column(&chunk); - out.block_entities = crate::structure_blocks::block_entities(&chunk, self.loot.as_deref()); + let (block_entities, rolled_loot) = + crate::structure_blocks::block_entities(&chunk, self.loot.as_deref()); + out.block_entities = block_entities; // The block entities Horizon does not model (decorated pots with their // sherds and loot table, brushable blocks) stay as placed, like a // loaded chunk's. @@ -555,13 +557,14 @@ impl ChunkGenerator for VanillaTerrain { Some(Tag::Compound(nbt)) }) .collect(); - if !unmodelled.is_empty() { + if !unmodelled.is_empty() || !rolled_loot.is_empty() { let mut extras = out .saved .take() .map(Arc::unwrap_or_clone) .unwrap_or_default(); extras.block_entities = unmodelled; + extras.rolled_loot = rolled_loot; out.saved = Some(Arc::new(extras)); } out.structure_refs = chunk @@ -570,11 +573,9 @@ impl ChunkGenerator for VanillaTerrain { .map(|(id, start, _, _)| (Arc::from(id), (start.x, start.z))) .collect(); let entities = std::mem::take(&mut chunk.entities); + // Chest minecarts keep their loot table; the game rolls it on load. out.entities = entities .into_iter() - .map(|nbt| { - crate::structure_blocks::unpack_entity_loot(&chunk, nbt, self.loot.as_deref()) - }) .map(horizon_world::nbt::Tag::Compound) .collect(); for s in &mut out.sections { From 9ef7a6fa256a5e9ba56d823552a211ae5b8ec2ed Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 12:05:16 +0100 Subject: [PATCH 3/6] Server players see the dragon's breath clouds The breath clouds are kept as a list, not entities, so the server thread drew their particles into its own copy and players never saw them. Each cloud is now tracked as an area_effect_cloud (radius, waiting, particle), and a server's client draws it as AreaEffectCloud.clientTick does. --- crates/horizon-client/src/game/dragon.rs | 10 +- .../horizon-client/src/game/lan_entities.rs | 24 +++++ .../horizon-client/src/game/lan_particles.rs | 6 +- crates/horizon-client/src/game/potions.rs | 2 + .../src/game/remote_projectiles.rs | 101 +++++++++++++++++- 5 files changed, 138 insertions(+), 5 deletions(-) diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index 8c316deeb..468d6fbb1 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -1558,6 +1558,7 @@ impl Game<'_> { y -= 1.0; } self.breath_clouds.push(Breath { + id: 0, at: [x, y.floor() + 1.0, z], radius: 5.0, age: 0, @@ -2083,6 +2084,7 @@ impl Game<'_> { }); if hit_block || hit_player || b.age > 600 { self.breath_clouds.push(Breath { + id: 0, at: [next.x, next.y, next.z], radius: 3.0, age: 0, @@ -2208,9 +2210,11 @@ pub(super) struct DragonFireball { age: i32, } pub(super) struct Breath { - at: [f64; 3], - radius: f32, - age: i32, + /// Its entity id once a server's players track it (0 until then). + pub(super) id: u32, + pub(super) at: [f64; 3], + pub(super) radius: f32, + pub(super) age: i32, duration: i32, from_dragon: bool, } diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index cd4ba2fb8..2ef862200 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -279,6 +279,7 @@ impl Game<'_> { self.bolts.iter_mut().for_each(|b| give(&mut b.id)); self.potions.thrown_ids().for_each(&mut give); self.end.eye_ids().for_each(&mut give); + self.breath_clouds.iter_mut().for_each(|b| give(&mut b.id)); } /// Primed TNT, falling blocks, projectiles, tridents, firework rockets and @@ -435,6 +436,29 @@ impl Game<'_> { } out.push(e); } + // The dragon's breath clouds (AreaEffectCloud's DATA_RADIUS, + // DATA_WAITING for its 20-tick wait, and DATA_PARTICLE): the + // client draws them from these (`tick_remote_clouds`). + let breath = self.network_particle( + &horizon_client::particles::ParticleOptions::simple( + horizon_client::particles::ParticleType::DragonBreath, + ), + None, + ); + for b in self.breath_clouds.iter().filter(|b| b.id != 0) { + let mut e = state(b.id, "minecraft:area_effect_cloud", b.at, 0.0, false); + e.meta.push((8, serializer::FLOAT, Value::Float(b.radius))); + if b.age < 20 { + e.meta.push((9, serializer::BOOLEAN, Value::Bool(true))); + } + if let Some(p) = &breath { + e.meta + .push((10, serializer::PARTICLE, Value::Particle(p.clone()))); + } + e.defaults + .push((9, serializer::BOOLEAN, Value::Bool(false))); + out.push(e); + } out.extend(self.lan_dragon_state()); } } diff --git a/crates/horizon-client/src/game/lan_particles.rs b/crates/horizon-client/src/game/lan_particles.rs index 0e35392bf..8162be3ec 100644 --- a/crates/horizon-client/src/game/lan_particles.rs +++ b/crates/horizon-client/src/game/lan_particles.rs @@ -68,7 +68,11 @@ impl Game<'_> { /// The options a server's particle stands for (None for a type or data /// this client doesn't draw). - fn received_particle(&mut self, p: &Particle, at: [f64; 3]) -> Option { + pub(super) fn received_particle( + &mut self, + p: &Particle, + at: [f64; 3], + ) -> Option { let name = self .remote .as_ref()? diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index b28c2fb4d..74c4ccd0c 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -71,6 +71,8 @@ pub(super) struct BodyPotions { pub(super) struct PotionState { pub(super) effects: PlayerEffects, thrown: Vec, + /// The area effect clouds a server tracks (game/remote_projectiles.rs). + pub(super) clouds: Vec, applied: Vec<(&'static str, &'static str, f64, &'static str)>, /// Armor the protection table was computed for. protection_for: Option>>, diff --git a/crates/horizon-client/src/game/remote_projectiles.rs b/crates/horizon-client/src/game/remote_projectiles.rs index a117b1b7c..fa1a5b35c 100644 --- a/crates/horizon-client/src/game/remote_projectiles.rs +++ b/crates/horizon-client/src/game/remote_projectiles.rs @@ -3,11 +3,26 @@ //! and `handleSetEntityData`): the server simulates them, the client draws //! them where it says and interpolates their moves. use super::{FallStep, FallingBlock, Game, fireworks::fireworks_of, view_vector}; +use horizon_client::particles::{ParticleOptions, ParticleType}; use horizon_client::projectiles::{Projectile, ProjectileKind}; -use horizon_core::{geometry::Vec3, position::BlockPos}; +use horizon_core::{geometry::Vec3, position::BlockPos, random::RandomSource}; use horizon_protocol::entity_data::Value; use horizon_world::registry::BlockStateId; +/// An `AreaEffectCloud` a server tracks: what its client tick reads. +pub(super) struct RemoteCloud { + id: u32, + at: [f64; 3], + radius: f32, + waiting: bool, + particle: ParticleOptions, +} + +/// `AreaEffectCloud.DEFAULT_PARTICLE`: a white entity effect. +fn default_cloud_particle() -> ParticleOptions { + ParticleOptions::colored(ParticleType::EntityEffect, [1.0; 4]) +} + /// The projectile a type id names, as Horizon models it. fn projectile_kind(kind: &str) -> Option { Some(match kind { @@ -92,6 +107,13 @@ impl Game<'_> { | "minecraft:experience_bottle" => { self.potions.add_remote_thrown(id, kind, at, velocity); } + "minecraft:area_effect_cloud" => self.potions.clouds.push(RemoteCloud { + id, + at: position, + radius: 3.0, + waiting: false, + particle: default_cloud_particle(), + }), "minecraft:eye_of_ender" => { self.end .add_remote_eye(id, position, [velocity.x, velocity.y, velocity.z]) @@ -125,6 +147,31 @@ impl Game<'_> { pub(super) fn remote_projectile_data(&mut self, id: i32, values: &[(u8, i32, Value)]) { let id = id as u32; self.remote_hook_data(id, values); + if let Some(at) = self + .potions + .clouds + .iter() + .find(|c| c.id == id) + .map(|c| c.at) + { + // AreaEffectCloud.DATA_RADIUS, DATA_WAITING and DATA_PARTICLE. + for (index, _, value) in values { + let particle = match (index, value) { + (10, Value::Particle(p)) => self.received_particle(p, at), + _ => None, + }; + let Some(c) = self.potions.clouds.iter_mut().find(|c| c.id == id) else { + return; + }; + match (index, value) { + (8, Value::Float(r)) => c.radius = *r, + (9, Value::Bool(w)) => c.waiting = *w, + (10, _) => c.particle = particle.unwrap_or_else(default_cloud_particle), + _ => {} + } + } + return; + } if self.rockets.iter().any(|r| r.id == id) { for (index, _, value) in values { match (index, value) { @@ -308,6 +355,56 @@ impl Game<'_> { let at = step(id, Vec3::new(at[0], at[1], at[2])); [at.x, at.y, at.z] }); + self.tick_remote_clouds(); + } + + /// `AreaEffectCloud.clientTick`: while waiting, now and then two + /// particles near the middle; then about one per square block of the + /// disc, drifting (an entity effect stays still). + fn tick_remote_clouds(&mut self) { + for c in &self.potions.clouds { + let r = self.particles.random(); + if c.waiting && r.next_boolean() { + continue; + } + let (count, spread) = if c.waiting { + (2, 0.2) + } else { + ( + (std::f32::consts::PI * c.radius * c.radius).ceil() as i32, + c.radius, + ) + }; + for _ in 0..count { + let r = self.particles.random(); + let angle = r.next_float() * std::f32::consts::TAU; + let distance = r.next_float().sqrt() * spread; + let at = [ + c.at[0] + f64::from(angle.cos() * distance), + c.at[1], + c.at[2] + f64::from(angle.sin() * distance), + ]; + let (options, velocity) = if c.particle.ty == ParticleType::EntityEffect { + let default = c.waiting && r.next_boolean(); + let options = if default { + default_cloud_particle() + } else { + c.particle.clone() + }; + (options, [0.0; 3]) + } else if c.waiting { + (c.particle.clone(), [0.0; 3]) + } else { + let v = [ + (0.5 - r.next_double()) * 0.15, + f64::from(0.01f32), + (0.5 - r.next_double()) * 0.15, + ]; + (c.particle.clone(), v) + }; + self.particles.add(&options, at, velocity); + } + } } pub(super) fn remove_remote_projectile(&mut self, id: u32) { @@ -318,6 +415,7 @@ impl Game<'_> { self.rockets.retain(|r| r.id != id); self.crystals.retain(|c| c.id != id); self.potions.remove_remote_thrown(id); + self.potions.clouds.retain(|c| c.id != id); self.end.remove_remote_eye(id); self.remove_remote_hook(id); } @@ -331,6 +429,7 @@ impl Game<'_> { self.rockets.clear(); self.crystals.clear(); self.potions.clear_thrown(); + self.potions.clouds.clear(); self.end.clear_remote_eyes(); self.clear_remote_hooks(); } From f5ef003bada695889f9d788d6a97ede2fa404299 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 12:09:05 +0100 Subject: [PATCH 4/6] Server players see the dragon's fireballs in flight Dragon fireballs were a server-side list like the breath clouds, so a server's players never saw them. Each is now tracked as a minecraft:dragon_fireball; the client keeps it in the same list, flies it on as AbstractHurtingProjectile.tick does, snaps it to the server's moves and draws it with its dragon_breath trail. --- crates/horizon-client/src/game/dragon.rs | 41 +++++++++++++++++-- .../horizon-client/src/game/lan_entities.rs | 9 ++++ crates/horizon-client/src/game/remote.rs | 10 +++++ .../src/game/remote_projectiles.rs | 24 +++++++++++ 4 files changed, 81 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index 468d6fbb1..e1880f9aa 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -2038,6 +2038,7 @@ impl Game<'_> { // assignDirectionalMovement: the direction times the acceleration power 0.1. let velocity = Vec3::new(v.x * 0.1, v.y * 0.1, v.z * 0.1); self.dragon_fireballs.push(DragonFireball { + id: 0, position: at, previous: at, velocity, @@ -2204,11 +2205,45 @@ impl Game<'_> { } } pub(super) struct DragonFireball { - position: Vec3, - previous: Vec3, - velocity: Vec3, + /// Its entity id once a server's players track it (0 until then). + pub(super) id: u32, + pub(super) position: Vec3, + pub(super) previous: Vec3, + pub(super) velocity: Vec3, age: i32, } +impl DragonFireball { + /// One a server sent (`handleAddEntity`). + pub(super) fn remote(id: u32, at: Vec3, velocity: Vec3) -> Self { + Self { + id, + position: at, + previous: at, + velocity, + age: 0, + } + } + /// `AbstractHurtingProjectile.tick` on a server's client: accelerate + /// along the motion (power 0.1, inertia 0.95 or 0.8 in water) and move; + /// only the server decides what it hits. + pub(super) fn remote_step(&mut self, water: bool) { + self.previous = self.position; + self.age += 1; + let v = self.velocity; + self.position = Vec3::new( + self.position.x + v.x, + self.position.y + v.y, + self.position.z + v.z, + ); + let l = (v.x * v.x + v.y * v.y + v.z * v.z).sqrt().max(1.0e-9); + let inertia = if water { 0.8 } else { 0.95 }; + self.velocity = Vec3::new( + (v.x + v.x / l * 0.1) * inertia, + (v.y + v.y / l * 0.1) * inertia, + (v.z + v.z / l * 0.1) * inertia, + ); + } +} pub(super) struct Breath { /// Its entity id once a server's players track it (0 until then). pub(super) id: u32, diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index 2ef862200..574f5303e 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -280,6 +280,9 @@ impl Game<'_> { self.potions.thrown_ids().for_each(&mut give); self.end.eye_ids().for_each(&mut give); self.breath_clouds.iter_mut().for_each(|b| give(&mut b.id)); + self.dragon_fireballs + .iter_mut() + .for_each(|b| give(&mut b.id)); } /// Primed TNT, falling blocks, projectiles, tridents, firework rockets and @@ -445,6 +448,12 @@ impl Game<'_> { ), None, ); + for b in self.dragon_fireballs.iter().filter(|b| b.id != 0) { + let p = b.position; + let mut e = state(b.id, "minecraft:dragon_fireball", at(p), 0.0, false); + e.velocity = [b.velocity.x, b.velocity.y, b.velocity.z]; + out.push(e); + } for b in self.breath_clouds.iter().filter(|b| b.id != 0) { let mut e = state(b.id, "minecraft:area_effect_cloud", b.at, 0.0, false); e.meta.push((8, serializer::FLOAT, Value::Float(b.radius))); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 5651647b7..7bde124b0 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1377,6 +1377,14 @@ impl Game<'_> { } return; } + // A dragon fireball keeps Entity's NO_OP InterpolationHandler too: + // the server's position replaces its own at once. + if let Some(b) = self.dragon_fireballs.iter_mut().find(|b| b.id == id as u32) { + if path.is_some() { + b.position = Vec3::new(position[0], position[1], position[2]); + } + return; + } if let Some(p) = r.pending_items.get_mut(&id) { p.0 = position; } @@ -2949,6 +2957,8 @@ impl Game<'_> { .find(|p| p.id == id as u32) { p.velocity = v; + } else if let Some(b) = self.dragon_fireballs.iter_mut().find(|b| b.id == id as u32) { + b.velocity = v; } else if let Some(p) = self .remote .as_mut() diff --git a/crates/horizon-client/src/game/remote_projectiles.rs b/crates/horizon-client/src/game/remote_projectiles.rs index fa1a5b35c..bbb7b7cde 100644 --- a/crates/horizon-client/src/game/remote_projectiles.rs +++ b/crates/horizon-client/src/game/remote_projectiles.rs @@ -107,6 +107,9 @@ impl Game<'_> { | "minecraft:experience_bottle" => { self.potions.add_remote_thrown(id, kind, at, velocity); } + "minecraft:dragon_fireball" => self + .dragon_fireballs + .push(super::dragon::DragonFireball::remote(id, at, velocity)), "minecraft:area_effect_cloud" => self.potions.clouds.push(RemoteCloud { id, at: position, @@ -356,6 +359,25 @@ impl Game<'_> { [at.x, at.y, at.z] }); self.tick_remote_clouds(); + // The dragon's fireballs fly on between the tracker's updates, with + // their dragon_breath trail (`AbstractHurtingProjectile.getTrailParticle`). + let trail = ParticleOptions::simple(ParticleType::DragonBreath); + for b in &mut self.dragon_fireballs { + let at = b.position; + let water = self + .res + .facts() + .get(self.world.block( + at.x.floor() as i32, + at.y.floor() as i32, + at.z.floor() as i32, + )) + .fluid + == horizon_client::blocks::Fluid::Water; + b.remote_step(water); + let p = b.position; + self.particles.add(&trail, [p.x, p.y + 0.5, p.z], [0.0; 3]); + } } /// `AreaEffectCloud.clientTick`: while waiting, now and then two @@ -416,6 +438,7 @@ impl Game<'_> { self.crystals.retain(|c| c.id != id); self.potions.remove_remote_thrown(id); self.potions.clouds.retain(|c| c.id != id); + self.dragon_fireballs.retain(|b| b.id != id); self.end.remove_remote_eye(id); self.remove_remote_hook(id); } @@ -430,6 +453,7 @@ impl Game<'_> { self.crystals.clear(); self.potions.clear_thrown(); self.potions.clouds.clear(); + self.dragon_fireballs.clear(); self.end.clear_remote_eyes(); self.clear_remote_hooks(); } From e0fea857ce23200d76cdd1db1e707a79384428b5 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:15:16 +0100 Subject: [PATCH 5/6] Remote dragon fireball: apply inertia before the move AbstractHurtingProjectile.tick calls applyInertia first and then moves by the new delta movement; Vec3.normalize leaves a near-zero vector at zero. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/dragon.rs | 27 +++++++++++++++--------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index e1880f9aa..89be88e61 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -2223,25 +2223,32 @@ impl DragonFireball { age: 0, } } - /// `AbstractHurtingProjectile.tick` on a server's client: accelerate - /// along the motion (power 0.1, inertia 0.95 or 0.8 in water) and move; - /// only the server decides what it hits. + /// `AbstractHurtingProjectile.tick` on a server's client: `applyInertia` + /// first (power 0.1, inertia 0.95 or 0.8 in water), then the move; only + /// the server decides what it hits. pub(super) fn remote_step(&mut self, water: bool) { self.previous = self.position; self.age += 1; let v = self.velocity; + // Vec3.normalize: a vector shorter than 1e-5 stays zero. + let l = (v.x * v.x + v.y * v.y + v.z * v.z).sqrt(); + let n = if l < 1.0e-5 { + Vec3::new(0.0, 0.0, 0.0) + } else { + Vec3::new(v.x / l, v.y / l, v.z / l) + }; + let inertia = f64::from(if water { 0.8f32 } else { 0.95f32 }); + let v = Vec3::new( + (v.x + n.x * 0.1) * inertia, + (v.y + n.y * 0.1) * inertia, + (v.z + n.z * 0.1) * inertia, + ); + self.velocity = v; self.position = Vec3::new( self.position.x + v.x, self.position.y + v.y, self.position.z + v.z, ); - let l = (v.x * v.x + v.y * v.y + v.z * v.z).sqrt().max(1.0e-9); - let inertia = if water { 0.8 } else { 0.95 }; - self.velocity = Vec3::new( - (v.x + v.x / l * 0.1) * inertia, - (v.y + v.y / l * 0.1) * inertia, - (v.z + v.z / l * 0.1) * inertia, - ); } } pub(super) struct Breath { From fb8643081370f15bf6ca0695d3cb41df0d9e658a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 14:30:23 +0100 Subject: [PATCH 6/6] mods: command.run-quiet (API level 3), a batch of commands with nothing in the chat A mod hands `run-quiet` a list of lines (at most 256 a call). In single player they run as the player typing them would, with the player's source made silent; on a Horizon server (it announces horizon:quiet_commands) they go as one payload that the server runs the same way; on any other server they fall back to chat commands, whose feedback shows. command.run is unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/cargo-horizon-mod/src/check.rs | 3 + crates/horizon-client/src/game/mods.rs | 56 +++++++++++++++++++ crates/horizon-client/src/game/remote.rs | 8 +++ crates/horizon-client/src/net.rs | 4 ++ crates/horizon-mod-sdk/wit/horizon.wit | 8 +++ crates/horizon-mods/src/api_level.rs | 5 +- crates/horizon-mods/src/runtime.rs | 23 ++++++++ crates/horizon-mods/tests/sandbox.rs | 28 +++++++++- crates/horizon-mods/tests/ui_guest/src/lib.rs | 16 +++++- docs/api/mods-reference.md | 1 + docs/api/stability.md | 2 +- docs/mods.md | 2 +- 12 files changed, 149 insertions(+), 7 deletions(-) diff --git a/crates/cargo-horizon-mod/src/check.rs b/crates/cargo-horizon-mod/src/check.rs index f42674da8..33095a115 100644 --- a/crates/cargo-horizon-mod/src/check.rs +++ b/crates/cargo-horizon-mod/src/check.rs @@ -262,6 +262,9 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> { format!("{}: {text}", if error { "error" } else { "feedback" }) } Output::Command { line } => format!("command: /{line}"), + Output::QuietCommands { lines, .. } => { + format!("{} quiet command(s)", lines.len()) + } Output::Stopped { reason, .. } => return Err(format!("it stopped: {reason}")), Output::OpenScreen { .. } => "opened a screen".to_string(), Output::CloseScreen { .. } => "closed its screen".to_string(), diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index 1752dec91..12deb61fc 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -57,6 +57,10 @@ pub(super) struct ModsState { /// is still being shown, and a mod answering its own lines would recurse. #[cfg(feature = "mods")] commands: Vec, + /// `command.run-quiet` batches for this window's own world, by mod id, + /// run on the next tick as `commands` are. + #[cfg(feature = "mods")] + quiet: Vec<(String, Vec)>, /// The server's command tree with the running mods' commands added. #[cfg(feature = "mods")] remote_tree: Option, @@ -474,6 +478,51 @@ impl Game<'_> { } None } + /// A mod's `command.run-quiet` lines (vanilla's commands only, as + /// `command.run`): to a server that runs them quietly as one payload + /// (`horizon_protocol::quiet`), to any other as chat commands, or for this + /// window's own world next tick. + fn mod_quiet_commands(&mut self, mod_id: String, lines: Vec) { + let lines: Vec = lines + .into_iter() + .filter(|l| vanilla_command(l.split(' ').next().unwrap_or_default())) + .collect(); + match self.remote.as_ref().map(|r| r.quiet_commands) { + Some(true) => { + for data in horizon_protocol::quiet::encode(&mod_id, &lines) { + self.send(horizon_protocol::packets::play::Serverbound::CustomPayload( + horizon_protocol::packets::configuration::CustomPayload { + channel: horizon_protocol::quiet::CHANNEL.into(), + data, + }, + )); + } + } + // The server checks the player's permissions; its feedback shows. + Some(false) => { + for line in lines { + self.send_chat(&format!("/{line}")); + } + } + None => self.mods.quiet.push((mod_id, lines)), + } + } + /// A quiet batch in this window's own world, as a server runs one + /// (game/lan_quiet.rs): each line as the player typing it, no chat, a + /// chat message refused; one line in the log. + fn run_quiet_batch(&mut self, mod_id: &str, lines: &[String]) { + let permission = self.ui.registries.permission; + let mut failed = 0; + for line in lines { + let ok = self.signable_arguments(permission, line).is_empty() + && self.run_command_quietly(line); + failed += usize::from(!ok); + } + log::info!( + "[mod {mod_id}] ran {} quiet command(s): {failed} failed", + lines.len() + ); + } /// A game tick. pub(super) fn tick_mods(&mut self) { // Here, at the player's level: shown inside a console call (a control @@ -481,6 +530,9 @@ impl Game<'_> { for line in std::mem::take(&mut self.mods.commands) { self.run_command(&line); } + for (mod_id, lines) in std::mem::take(&mut self.mods.quiet) { + self.run_quiet_batch(&mod_id, &lines); + } if !self.mods.mods.is_running() { return; } @@ -561,6 +613,10 @@ impl Game<'_> { } continue; } + Output::QuietCommands { mod_id, lines } => { + self.mod_quiet_commands(mod_id, lines); + continue; + } Output::Stopped { name, reason } => { // Its screen goes with it: the entry's run is gone, so // `mod_ui_view` finds no widgets and the screen closes. diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 1474858b8..1459c8dd6 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -109,6 +109,8 @@ enum Received { pub(super) struct Remote { pub session: Session, pub brand: String, + /// The server announced it runs mods' quiet commands. + pub quiet_commands: bool, pub(super) builtin: Arc, lang: Arc, pub(super) registries: Arc, @@ -419,6 +421,7 @@ impl Game<'_> { self.remote = Some(Remote { session, brand: "unknown".into(), + quiet_commands: false, builtin: Arc::new(builtin), lang, registries: Arc::new(Dynamic::default()), @@ -839,6 +842,11 @@ impl Game<'_> { remote.brand = brand; } } + Event::QuietCommands => { + if let Some(remote) = &mut self.remote { + remote.quiet_commands = true; + } + } Event::Reconfigured(registries) => self.set_registries(registries), // handleTransfer: "Cannot transfer to server from // singleplayer" (no ServerData), so the world just closes. diff --git a/crates/horizon-client/src/net.rs b/crates/horizon-client/src/net.rs index 0eb260477..34daaf85c 100644 --- a/crates/horizon-client/src/net.rs +++ b/crates/horizon-client/src/net.rs @@ -40,6 +40,8 @@ pub enum Event { Status(String), /// The server's `minecraft:brand` custom payload. Brand(String), + /// The server runs mods' quiet commands (`horizon_protocol::quiet`). + QuietCommands, /// Configuration finished: the play state begins with these registries. Joined { registries: Arc, @@ -668,6 +670,8 @@ fn receive_brand(payload: &cfg::CustomPayload, send: &Sender) { && let Ok(brand) = horizon_protocol::buf::Reader::new(&payload.data).string(32767) { let _ = send.send(Event::Brand(brand)); + } else if payload.channel == horizon_protocol::quiet::CHANNEL { + let _ = send.send(Event::QuietCommands); } } diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit index 7f8245c48..d9bb9f5c2 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -111,6 +111,14 @@ interface storage { interface command { /// `line` without its slash; its feedback goes to the chat as if typed. run: func(line: string); + /// `lines` (each without its slash, at most 256 a call) as `run` does, + /// but with nothing in the chat: no feedback and no failure. In single + /// player and on Horizon's servers, each runs exactly as the player + /// typing it would (the same rights), in order, 64 a tick, and the + /// server logs one line a batch; one that carries a chat message (`say`, + /// `msg`) is refused. On any other server they go as chat commands, and + /// there their feedback shows: a mod running many should say so. + run-quiet: func(lines: list); } /// Capability `ui`: widgets the game draws with its own menus' widgets, for diff --git a/crates/horizon-mods/src/api_level.rs b/crates/horizon-mods/src/api_level.rs index 785f0e573..bf87d0cfa 100644 --- a/crates/horizon-mods/src/api_level.rs +++ b/crates/horizon-mods/src/api_level.rs @@ -7,13 +7,13 @@ //! version's level so the launcher can tell before it installs. /// The newest level this Horizon serves. -pub const LEVEL: u32 = 2; +pub const LEVEL: u32 = 3; /// Every function the game offers mods, as `interface.function`, with its /// level. Level 0 is the contract of Horizon 0.2.67 to 0.2.69. A new /// function takes the next level and raises [`LEVEL`] (the `api_reference` /// test fails until it is listed here). -pub const FUNCTIONS: [(&str, u32); 33] = [ +pub const FUNCTIONS: [(&str, u32); 34] = [ ("log.write", 0), ("game.get-player", 0), ("game.get-clock", 0), @@ -47,6 +47,7 @@ pub const FUNCTIONS: [(&str, u32); 33] = [ ("players.tell", 1), ("players.broadcast", 1), ("game.raycast", 2), + ("command.run-quiet", 3), ]; /// What the game's program carries so the launcher can read its level diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index ea603ee31..ce48f2317 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -89,6 +89,9 @@ const FUEL_FRAME: u64 = 10_000_000; const FUEL_EVENT: u64 = 100_000_000; /// Chat lines a mod may show per call, HUD lines and their length. const CHAT_PER_CALL: usize = 8; +/// `command.run-quiet` lines one call of a mod may queue (a quiet payload's +/// cap, `horizon_protocol::quiet::MAX_LINES`). +const QUIET_PER_CALL: usize = 256; /// How far `game.raycast` sees, in blocks. pub const RAYCAST_MAX: f32 = 1024.0; const HUD_LINES: usize = 16; @@ -160,6 +163,9 @@ pub enum Output { /// `command.run`: a vanilla command line, without its slash, to run as /// the player. Command { line: String }, + /// `command.run-quiet`: vanilla command lines to run as the player with + /// nothing in the chat (`horizon_protocol::quiet` on a server). + QuietCommands { mod_id: String, lines: Vec }, /// The mod was turned off: it trapped, overran or failed to start. Stopped { name: String, reason: String }, /// `players.tell`: a line after the mod's name, to the player with this id. @@ -1408,6 +1414,23 @@ impl command::Host for State { self.out.push(Output::Command { line: clip(line) }); } } + fn run_quiet(&mut self, lines: Vec) { + let queued: usize = self + .out + .iter() + .map(|o| match o { + Output::QuietCommands { lines, .. } => lines.len(), + _ => 0, + }) + .sum(); + let room = QUIET_PER_CALL.saturating_sub(queued); + if room > 0 && !lines.is_empty() { + self.out.push(Output::QuietCommands { + mod_id: self.id.clone(), + lines: lines.into_iter().take(room).map(clip).collect(), + }); + } + } } impl hud::Host for State { fn set_panel(&mut self, corner: Corner, lines: Vec) { diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index 5b673583d..c6b835f10 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -26,7 +26,7 @@ id = "test_ui_guest" name = "Test UI Guest" version = "0.1.0" api = "0.1" -capabilities = ["game-read", "chat", "ui", "render", "input"] +capabilities = ["game-read", "chat", "command", "ui", "render", "input"] experimental = ["ui", "render", "input"] "#; @@ -763,6 +763,32 @@ fn game_raycast_sees_the_view_hit_within_its_distance() { assert_eq!(said(&mut mods, "1e9"), [hit]); } +#[test] +fn quiet_commands_come_out_as_one_batch_capped() { + let mut mods = load("horizon_mods_test_ui_guest.hmod"); + let quiet = |mods: &mut Mods, command: &str| -> Vec<(String, Vec)> { + assert!(mods.command(command)); + mods.drain() + .into_iter() + .filter_map(|o| match o { + Output::QuietCommands { mod_id, lines } => Some((mod_id, lines)), + _ => None, + }) + .collect() + }; + assert_eq!( + quiet(&mut mods, "quiet setblock 0 0 0 stone;say hi"), + [( + "test_ui_guest".to_string(), + vec!["setblock 0 0 0 stone".to_string(), "say hi".to_string()] + )] + ); + let batches = quiet(&mut mods, "quiet_many 300"); + assert_eq!(batches.len(), 1); + assert_eq!(batches[0].1.len(), 256); + assert_eq!(batches[0].1[255], "setblock 255 300 0 stone"); +} + #[test] fn corner_panels_text_width_and_readings() { let mut mods = load("horizon_mods_test_ui_guest.hmod"); diff --git a/crates/horizon-mods/tests/ui_guest/src/lib.rs b/crates/horizon-mods/tests/ui_guest/src/lib.rs index 32e811fc7..74fb64350 100644 --- a/crates/horizon-mods/tests/ui_guest/src/lib.rs +++ b/crates/horizon-mods/tests/ui_guest/src/lib.rs @@ -5,9 +5,10 @@ //! `/input_claim`, `/input_poll`, `/input_held` and `/input_wheel` test //! `input`; `/zoom FACTOR SMOOTH TURN` tests `render.set-zoom`; //! `/corner` and `/readings` the calls the official extras mods use; -//! `/raycast DISTANCE` says what `game.raycast` sees. +//! `/raycast DISTANCE` says what `game.raycast` sees; `/quiet A;B` runs +//! lines with `command.run-quiet` (`/quiet_many N`: N of them). use horizon_mod_sdk::{ - Mod, Registration, chat, game, + Mod, Registration, chat, command, game, input::{self, Event}, render::{self, FillShape, ItemShape, Point, QuadShape, Rect, Shape, SpriteShape, TextShape}, ui::{self, ItemWidget, ListWidget, Screen, TextWidget, Widget}, @@ -99,6 +100,8 @@ impl Mod for Guest { "zoom", "minimap", "raycast", + "quiet", + "quiet_many", "corner", "readings", ] @@ -219,6 +222,15 @@ impl Mod for Guest { }); render::set_minimap(map); } + "quiet" => command::run_quiet(&args.split(';').map(str::to_owned).collect::>()), + "quiet_many" => { + let n: usize = args.parse().unwrap_or(0); + command::run_quiet( + &(0..n) + .map(|i| format!("setblock {i} 300 0 stone")) + .collect::>(), + ); + } "raycast" => { let distance = args.parse().unwrap_or(f32::NAN); chat::show(&match game::raycast(distance) { diff --git a/docs/api/mods-reference.md b/docs/api/mods-reference.md index a197b2c04..c44f27576 100644 --- a/docs/api/mods-reference.md +++ b/docs/api/mods-reference.md @@ -176,6 +176,7 @@ Capability `command`: vanilla commands run as the player, with the player's perm | Function | Signature | What it does | | --- | --- | --- | | `run` | `func(line: string)` | `line` without its slash; its feedback goes to the chat as if typed. | +| `run-quiet` | `func(lines: list)` | `lines` (each without its slash, at most 256 a call) as `run` does, but with nothing in the chat: no feedback and no failure. In single player and on Horizon's servers, each runs exactly as the player typing it would (the same rights), in order, 64 a tick, and the server logs one line a batch; one that carries a chat message (`say`, `msg`) is refused. On any other server they go as chat commands, and there their feedback shows: a mod running many should say so. | ## `ui` diff --git a/docs/api/stability.md b/docs/api/stability.md index f6b40fabe..df2c1aeb3 100644 --- a/docs/api/stability.md +++ b/docs/api/stability.md @@ -38,7 +38,7 @@ don't import it); faster, or fixing behaviour to what the reference already says A new WIT function doesn't break older mods, but a mod that calls it can't run on a Horizon from before it. So every function the game offers mods has an **API level**, the one it arrived at (`crates/horizon-mods/src/api_level.rs`): -level 0 is the contract of Horizon 0.2.67 to 0.2.69, level 1 adds `render.set-minimap` and server mods' `players`, level 2 `game.raycast`. A mod needs the level of +level 0 is the contract of Horizon 0.2.67 to 0.2.69, level 1 adds `render.set-minimap` and server mods' `players`, level 2 `game.raycast`, level 3 `command.run-quiet`. A mod needs the level of the newest function it imports (a component imports only the functions it calls). The level is read from the file, never declared: diff --git a/docs/mods.md b/docs/mods.md index 0d26978dc..28415d28f 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -87,7 +87,7 @@ folder, loads no runtime and plays exactly like vanilla 26.3. | `chat` | `chat` | `show(text)`: a line only the local player sees, after the mod's name (8 per call) | | `hud` | `hud` | `set-panel(corner, lines)`, `clear()`: up to 16 lines of 256 characters | | `storage` | `storage` | `get(key)`, `set(key, value)`, `delete(key)`: a per-mod folder of up to 64 files, 4 MiB total, at most 1 MiB written per call | -| `command` | `command` | `run(line)`: a vanilla command run as the player, with the player's permissions, after the hook returns (8 per call); mods' own commands are not run | +| `command` | `command` | `run(line)`: a vanilla command run as the player, with the player's permissions, after the hook returns (8 per call); mods' own commands are not run. `run-quiet(lines)`: up to 256 a call, the same rights, nothing in the chat (single player and Horizon's servers run them 64 a tick and log one line a batch; elsewhere they go as chat commands and their feedback shows) | | `ui` | `ui` | `open-screen`, `close-screen`, `set-settings`: a screen the mod owns and a page in Options > Mods, of text, button, item and list widgets the game lays out and draws with its own menus' code. **Experimental:** the manifest needs `experimental = ["ui"]` | | `render` | `render` | `set-hud(shapes)`: up to 1024 fills, four-cornered shapes, GUI sprites, items and text, kept on the HUD (over the hotbar, under chat and screens, hidden with F1) until replaced; `set-corner(corner, w, h, shapes)`: a box the game places in a corner, stacked with its overlays and other panels, as `hud`'s panels are; `text-width(text)`; `frame-stats()`: the game's FPS, min and 1% low; `gui-size()`; `shake(strength, seconds)`: the view turns, the player doesn't, scaled by Distortion Effects; `set-zoom(zoom)`: the field of view divided by up to 10, eased or at once, with slower turning, while playing and not through a spyglass (the strongest of several mods' zooms counts); `set-minimap(minimap)`: a map of the world around the player in a corner, as a map item colours it (the floor underground and under roofs), square or round, turning with the player or north up, with the player's arrow; the game keeps its tiles within its own frame budget (one map at a time, the first loaded mod's). The game's own HUD renderer draws them: a mod never supplies shader code. **Experimental:** `experimental = ["render"]` | | `input` | `input` | `claim-items(ids)`: the use button on those items is the mod's (`use-start`, `use-stop` with the ticks held; the game doesn't place, eat or swing); `register-key(name, label, key)`: up to 16 keys (`key.keyboard.r`), heard while playing as `key-down` / `key-up` (the game's own mapping on that key still runs; a screen opening lets held keys up), mouse buttons as `key.mouse.4`. The player rebinds them on the mod's page in Options > Mods, where the game lists them first as Key Binds rows (click, then press a key or mouse button; Esc binds none), even for a mod without `ui`; the choice is kept in `horizon-mods.txt` (`key..:key.keyboard.z`) and wins over `register-key`'s default; `claim-wheel(on)`: the wheel's steps become `wheel` events and the hotbar doesn't move (the one input a mod takes from the game; a mod's keys never do); `held()`; `mapping(name)`: a movement or click mapping's key label and whether it is held; `clicks-per-second()`; `poll()` returns the events, at most 256 kept. **Experimental:** `experimental = ["input"]` |