From c9f554d1c4842ce6b408f5db95479879df545cd5 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 15:51:15 +0100 Subject: [PATCH 01/13] Mod API 0.3 (experimental): server mods' contract, runtime and SDK A server mod runs where the world is simulated. Its manifest says side = "server" and api = "0.3" (only a server mod may), and its component targets the new WIT world horizon-server-mod: - imports log and storage as client mods do, and the new capability players: online() (id, name, position, dimension, game mode, health), tell(id, text), broadcast(text), 8 lines per call shared with chat; - exports server-events: init, tick, player-joined, player-left, chat, command (with the player who typed it; its feedback goes back to that player), block-broken and block-placed (with the block state as text). horizon-mods: a second bindgen world sharing log and storage with the first; a running mod holds either kind of hooks; Mods::load_for(Runs) starts only the mods a game runs (the window client mods, the world's server server mods, in-frame single player both) and marks the others Elsewhere. Client and server commands are owned separately. The game passes Runs::Client for now, so nothing changes in game until its server code calls these hooks. The SDK gains horizon_mod_sdk::server (ServerMod, Registration, export_server_mod!), the example server mod welcome (greets, announces newcomers kept in storage, /online, /mined), and cargo horizon-mod check's trial run plays a server mod with a player joining, chatting, typing its commands and leaving. The manifest refuses client capabilities on a server mod and players on a client mod. The generated reference, the guide, the portal and the stability table describe it. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 7 + Cargo.toml | 2 +- crates/cargo-horizon-mod/src/check.rs | 73 ++-- crates/horizon-client/src/game/mods.rs | 12 +- .../examples/welcome/Cargo.toml | 16 + .../examples/welcome/horizon-mod.toml | 8 + .../examples/welcome/src/lib.rs | 84 ++++ crates/horizon-mod-sdk/src/lib.rs | 152 +++++++- crates/horizon-mod-sdk/wit/horizon.wit | 88 +++++ crates/horizon-mods/src/manifest.rs | 57 ++- crates/horizon-mods/src/runtime.rs | 363 +++++++++++++++--- crates/horizon-mods/src/testing.rs | 1 + crates/horizon-mods/tests/sandbox.rs | 85 +++- docs/api/mods-reference.md | 85 +++- docs/api/mods.md | 27 +- docs/api/stability.md | 2 +- docs/mods.md | 34 +- 17 files changed, 984 insertions(+), 112 deletions(-) create mode 100644 crates/horizon-mod-sdk/examples/welcome/Cargo.toml create mode 100644 crates/horizon-mod-sdk/examples/welcome/horizon-mod.toml create mode 100644 crates/horizon-mod-sdk/examples/welcome/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 2d09d2d0e..0b8adf3ea 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4197,6 +4197,13 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "welcome" +version = "0.1.0" +dependencies = [ + "horizon-mod-sdk", +] + [[package]] name = "wgpu" version = "30.0.1" diff --git a/Cargo.toml b/Cargo.toml index c6f2bc581..44ed89122 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] exclude = ["launcher", "crates/horizon-telemetry-server", "crates/horizon-mod-registry", "third_party/wgpu-hal"] -members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"] +members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/welcome", "xtask"] resolver = "2" [workspace.package] diff --git a/crates/cargo-horizon-mod/src/check.rs b/crates/cargo-horizon-mod/src/check.rs index 0294bec98..86ce9654d 100644 --- a/crates/cargo-horizon-mod/src/check.rs +++ b/crates/cargo-horizon-mod/src/check.rs @@ -1,10 +1,11 @@ //! `cargo horizon-mod check `: what the registry checks of a submission, //! run anywhere: its kind's own checks (docs/api/mod-index.md), its signature //! when given a key, and for a mod a trial run in the sandbox: it must start, -//! survive ticks, frames, a chat line and each of its commands, and import -//! no more than its capabilities. +//! survive ticks, frames, a chat line and each of its commands (a server mod: +//! a player joining, chatting, typing them and leaving), and import no more +//! than its capabilities. use horizon_mods::{ - Clock, Mods, Output, Package, Player, Snapshot, Status, + Clock, GameMode, Mods, Output, Package, Player, ServerPlayer, Snapshot, Status, index::{self, Facts, Kind}, manifest::component_imports, }; @@ -181,37 +182,63 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> { if let Some(reason) = failed(&mods) { return Err(format!("it didn't start: {reason}")); } - report.commands = mods.commands().map(str::to_owned).collect(); + let client: Vec = mods.commands().map(str::to_owned).collect(); + let server: Vec = mods.server_commands().map(str::to_owned).collect(); + report.commands = [client.clone(), server.clone()].concat(); + // A server mod plays with one player on, who joins, chats and leaves. + let steve = ServerPlayer { + id: "00000000-0000-4000-8000-000000000001".into(), + name: "Steve".into(), + x: 0.5, + y: 64.0, + z: 0.5, + dimension: "minecraft:overworld".into(), + game_mode: GameMode::Survival, + health: 20.0, + }; + let snapshot = |t: u64| Snapshot { + player: Some(Player { + x: 0.5 + t as f64 * 0.1, + y: 64.0, + z: 0.5, + yaw: 90.0, + pitch: 0.0, + health: 20.0, + food: 20, + dimension: "minecraft:overworld".into(), + }), + clock: Some(Clock { + game_time: t, + day_time: 1000 + t, + }), + players: vec![steve.clone()], + }; + mods.set_snapshot(snapshot(0)); + mods.player_joined(&steve); for t in 0..TICKS { - mods.set_snapshot(Snapshot { - player: Some(Player { - x: 0.5 + t as f64 * 0.1, - y: 64.0, - z: 0.5, - yaw: 90.0, - pitch: 0.0, - health: 20.0, - food: 20, - dimension: "minecraft:overworld".into(), - }), - clock: Some(Clock { - game_time: t, - day_time: 1000 + t, - }), - }); + mods.set_snapshot(snapshot(t)); mods.tick(t); + mods.server_tick(t); for _ in 0..FRAMES_PER_TICK { mods.frame(1.0 / 60.0); } } mods.chat(" hello"); - for name in report.commands.clone() { - mods.command(&name); + mods.player_chat(&steve, "hello"); + for name in &client { + mods.command(name); } + for name in &server { + mods.server_command(&steve, name); + } + mods.set_snapshot(Snapshot::default()); + mods.player_left(&steve); for out in mods.drain() { report.output.push(match out { Output::Chat { text, .. } => format!("chat: {text}"), - Output::Feedback { text, error } => { + Output::Tell { text, .. } => format!("tell: {text}"), + Output::Broadcast { text, .. } => format!("broadcast: {text}"), + Output::Feedback { text, error } | Output::Reply { text, error, .. } => { format!("{}: {text}", if error { "error" } else { "feedback" }) } Output::Stopped { reason, .. } => return Err(format!("it stopped: {reason}")), diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index 572f9fe2b..5cd7bc368 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -23,7 +23,7 @@ use { mod_list::Installed, text::{self, Text}, }, - horizon_mods::{Clock, Mods, Output, Player, Snapshot, Status}, + horizon_mods::{Clock, Mods, Output, Player, Runs, Snapshot, Status}, std::time::Instant, }; @@ -185,7 +185,7 @@ impl Game<'_> { .collect(); let enabled = &self.settings.mods.enabled; let on = |id: &str| enabled.contains(id) || dev_ids.iter().any(|d| d == id); - let mods = Mods::load(&paths, on, vanilla_command); + let mods = Mods::load_for(Runs::Client, &paths, on, vanilla_command); self.mods.mods = mods; self.list_mods(); self.sync_mod_commands(); @@ -279,7 +279,11 @@ impl Game<'_> { game_time: self.world.game_time.max(0) as u64, day_time: self.world.day_time.max(0) as u64, }); - Snapshot { player, clock } + Snapshot { + player, + clock, + players: Vec::new(), + } } /// A game tick. pub(super) fn tick_mods(&mut self) { @@ -347,6 +351,8 @@ impl Game<'_> { self.sync_mod_commands(); Text::literal(format!("Mod {name} stopped: {reason}")).with_color(text::RED) } + // Server mods' lines: this game runs no server mod yet. + Output::Tell { .. } | Output::Broadcast { .. } | Output::Reply { .. } => continue, }; // Not through system_message: a mod must not hear its own lines. let focused = self.screen == Screen::Chat; diff --git a/crates/horizon-mod-sdk/examples/welcome/Cargo.toml b/crates/horizon-mod-sdk/examples/welcome/Cargo.toml new file mode 100644 index 000000000..50ab1a10a --- /dev/null +++ b/crates/horizon-mod-sdk/examples/welcome/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "welcome" +version = "0.1.0" +edition.workspace = true +license.workspace = true +publish = false +description = "Example Horizon server mod: greets players, announces newcomers, /online and /mined" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +horizon-mod-sdk = { path = "../.." } + +[lints] +workspace = true diff --git a/crates/horizon-mod-sdk/examples/welcome/horizon-mod.toml b/crates/horizon-mod-sdk/examples/welcome/horizon-mod.toml new file mode 100644 index 000000000..f8e73c482 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/welcome/horizon-mod.toml @@ -0,0 +1,8 @@ +id = "welcome" +name = "Welcome" +version = "0.1.0" +description = "Greets each player who joins, announces a newcomer to everyone, /online lists who is on, /mined counts the blocks you broke." +authors = ["Horizon"] +api = "0.3" +side = "server" +capabilities = ["players", "storage"] diff --git a/crates/horizon-mod-sdk/examples/welcome/src/lib.rs b/crates/horizon-mod-sdk/examples/welcome/src/lib.rs new file mode 100644 index 000000000..c45712c88 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/welcome/src/lib.rs @@ -0,0 +1,84 @@ +//! Example Horizon server mod (`docs/mods.md`, "Server mods"): greets each +//! player who joins, announces a newcomer to everyone (the players it has +//! seen are kept in `storage`), `/online` lists who is on and where, and +//! `/mined` counts the blocks the player broke since the server started. +use horizon_mod_sdk::{ + server::{BlockPos, Player, Registration, ServerMod, players}, + storage, +}; +use std::collections::HashMap; + +struct Welcome { + /// Ids of every player seen, one per line in storage key `seen`. + seen: Vec, + mined: HashMap, +} + +impl ServerMod for Welcome { + fn init() -> Result<(Self, Registration), String> { + let seen = storage::get("seen") + .map(|b| { + String::from_utf8_lossy(&b) + .lines() + .map(str::to_owned) + .collect() + }) + .unwrap_or_default(); + let hooks = Registration::new() + .command("online") + .command("mined") + .on_joins() + .on_blocks(); + Ok(( + Welcome { + seen, + mined: HashMap::new(), + }, + hooks, + )) + } + + fn player_joined(&mut self, player: &Player) { + let others = players::online().len() - 1; + players::tell( + &player.id, + &format!("Welcome, {}! {others} other player(s) online.", player.name), + ); + if !self.seen.contains(&player.id) { + self.seen.push(player.id.clone()); + let _ = storage::set("seen", self.seen.join("\n").as_bytes()); + players::broadcast(&format!("{} is here for the first time", player.name)); + } + } + + fn command( + &mut self, + player: &Player, + name: &str, + _args: &str, + ) -> Result, String> { + Ok(Some(match name { + "online" => players::online() + .iter() + .map(|p| { + format!( + "{} ({})", + p.name, + p.dimension.trim_start_matches("minecraft:") + ) + }) + .collect::>() + .join(", "), + _ => { + let n = self.mined.get(&player.id).copied().unwrap_or(0); + format!("You broke {n} block(s)") + } + })) + } + + fn block_broken(&mut self, player: &Player, _pos: BlockPos, _state: &str) { + *self.mined.entry(player.id.clone()).or_default() += 1; + } +} + +horizon_mod_sdk::export_server_mod!(Welcome); diff --git a/crates/horizon-mod-sdk/src/lib.rs b/crates/horizon-mod-sdk/src/lib.rs index 71c36cf80..1cffcc183 100644 --- a/crates/horizon-mod-sdk/src/lib.rs +++ b/crates/horizon-mod-sdk/src/lib.rs @@ -21,7 +21,8 @@ //! ``` //! //! Every interface but `log` is a capability: list the ones the mod uses in -//! `horizon-mod.toml` (`game-read`, `chat`, `hud`, `storage`). +//! `horizon-mod.toml` (`game-read`, `chat`, `hud`, `storage`; a server mod +//! `storage` and `players`). Server mods: [`server`]. wit_bindgen::generate!({ path: "wit", @@ -145,3 +146,152 @@ macro_rules! export_mod { }; }; } + +/// Server mods (manifest `side = "server"`, `api = "0.3"`, experimental): a +/// type implementing [`ServerMod`](server::ServerMod), exported with +/// [`export_server_mod!`]. It runs where the world is simulated, and reads +/// and messages the players with capability `players`. +pub mod server { + wit_bindgen::generate!({ + path: "wit", + world: "horizon-server-mod", + pub_export_macro: true, + export_macro_name: "__export_horizon_server_mod", + default_bindings_module: "horizon_mod_sdk::server", + with: { + "horizon:mods/log@0.1.0": crate::log, + "horizon:mods/storage@0.1.0": crate::storage, + }, + }); + + pub use exports::horizon::mods::server_events::{BlockPos, Guest as __Guest, Registration}; + pub use horizon::mods::players::{self, GameMode, Player}; + + /// The server's calls into a mod. Only the hooks [`Registration`] asks + /// for are called; the others may stay as their defaults. + pub trait ServerMod: Sized + 'static { + /// Once, after loading: the mod's state and the hooks it wants. An + /// error keeps the mod off and is logged. + fn init() -> Result<(Self, Registration), String>; + /// Every server tick, when [`Registration::tick`] is set. + fn tick(&mut self, _tick: u64) {} + /// When [`Registration::joins`] is set. + fn player_joined(&mut self, _player: &Player) {} + fn player_left(&mut self, _player: &Player) {} + /// A chat message a player sent, when [`Registration::chat`] is set. + fn chat(&mut self, _player: &Player, _text: &str) {} + /// `/name args` typed by `player`. `Ok(Some(text))` is their + /// feedback, `Err(text)` their error in red. + fn command( + &mut self, + _player: &Player, + _name: &str, + _args: &str, + ) -> Result, String> { + Err("This command does nothing".into()) + } + /// When [`Registration::blocks`] is set: `state` is what was there. + fn block_broken(&mut self, _player: &Player, _pos: BlockPos, _state: &str) {} + fn block_placed(&mut self, _player: &Player, _pos: BlockPos, _state: &str) {} + } + + impl Registration { + /// No commands and no hooks. + pub fn new() -> Self { + Self { + commands: Vec::new(), + tick: false, + joins: false, + chat: false, + blocks: false, + } + } + /// Adds `/name`. + pub fn command(mut self, name: &str) -> Self { + self.commands.push(name.into()); + self + } + pub fn on_tick(mut self) -> Self { + self.tick = true; + self + } + pub fn on_joins(mut self) -> Self { + self.joins = true; + self + } + pub fn on_chat(mut self) -> Self { + self.chat = true; + self + } + pub fn on_blocks(mut self) -> Self { + self.blocks = true; + self + } + } + impl Default for Registration { + fn default() -> Self { + Self::new() + } + } +} + +/// Exports a [`ServerMod`](server::ServerMod) as the component's +/// `server-events` interface, as [`export_mod!`] does for a client mod. +#[macro_export] +macro_rules! export_server_mod { + ($t:ty) => { + const _: () = { + use ::std::cell::RefCell; + use $crate::server::{BlockPos, Player, Registration, ServerMod}; + ::std::thread_local! { + static STATE: RefCell> = const { RefCell::new(None) }; + } + fn with(f: impl FnOnce(&mut $t)) { + STATE.with(|s| { + if let Some(m) = s.borrow_mut().as_mut() { + f(m) + } + }) + } + struct Export; + impl $crate::server::__Guest for Export { + fn init() -> Result { + let (m, registration) = <$t as ServerMod>::init()?; + STATE.with(|s| *s.borrow_mut() = Some(m)); + Ok(registration) + } + fn tick(tick: u64) { + with(|m| m.tick(tick)) + } + fn player_joined(player: Player) { + with(|m| m.player_joined(&player)) + } + fn player_left(player: Player) { + with(|m| m.player_left(&player)) + } + fn chat(player: Player, text: String) { + with(|m| m.chat(&player, &text)) + } + fn command( + player: Player, + name: String, + args: String, + ) -> Result, String> { + let mut out = Err("The mod is not running".to_string()); + with(|m| out = m.command(&player, &name, &args)); + out + } + fn block_broken(player: Player, pos: BlockPos, state: String) { + with(|m| m.block_broken(&player, pos, &state)) + } + fn block_placed(player: Player, pos: BlockPos, state: String) { + with(|m| m.block_placed(&player, pos, &state)) + } + } + #[cfg(target_arch = "wasm32")] + $crate::server::__export_horizon_server_mod!(Export); + #[cfg(not(target_arch = "wasm32"))] + let _ = ::init; + }; + }; +} diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit index 9f00a12b1..3a9027bba 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -111,6 +111,84 @@ interface events { chat: func(text: string); } +/// Capability `players`, server mods only (manifest `api = "0.3"`, +/// experimental): the players on the server, and messages to them. +interface players { + enum game-mode { + survival, + creative, + adventure, + spectator, + } + record player { + /// The player's UUID, `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`. + id: string, + name: string, + /// Feet position, in blocks. + x: f64, + y: f64, + z: f64, + /// `minecraft:overworld`, `minecraft:the_nether`, ... + dimension: string, + game-mode: game-mode, + /// Hit points as vanilla counts them: 20 is full health without effects. + health: f32, + } + /// The players online, in the order they joined. + online: func() -> list; + /// A system message to one player, after the mod's name; false when no + /// player with that id is online. Up to 8 messages per call. + tell: func(player: string, text: string) -> bool; + /// A system message to every player and the server's log, after the + /// mod's name. Counts toward the same 8 per call. + broadcast: func(text: string); +} + +/// What the server calls in a server mod (manifest `api = "0.3"`, +/// experimental). Only the hooks `init` asks for are ever called. The player +/// in each event is as the server saw them when it happened. +interface server-events { + use players.{player}; + + record registration { + /// Commands players may type, without the slash. A name vanilla + /// already uses is refused (vanilla's command runs). + commands: list, + /// Call `tick` every server tick (20 per second). + tick: bool, + /// Call `player-joined` and `player-left`. + joins: bool, + /// Call `chat` for each chat message a player sends. + chat: bool, + /// Call `block-broken` and `block-placed`. + blocks: bool, + } + record block-pos { + x: s32, + y: s32, + z: s32, + } + /// Once, after loading. An error keeps the mod off and is logged. + init: func() -> result; + /// Each server tick, with the server's tick counter. + tick: func(tick: u64); + /// A player joined the server; they are in `players.online` already. + player-joined: func(player: player); + /// A player left the server; they are no longer in `players.online`. + player-left: func(player: player); + /// A chat message a player sent, as plain text. + chat: func(player: player, text: string); + /// `/name args` typed by `player`: ok(some(text)) is their feedback, + /// err(text) their error in red. + command: func(player: player, name: string, args: string) -> result, string>; + /// A player broke the block at `pos` in their dimension: `state` is what + /// was there, as `minecraft:oak_log[axis=y]`. + block-broken: func(player: player, pos: block-pos, state: string); + /// A player placed `state` at `pos` in their dimension. + block-placed: func(player: player, pos: block-pos, state: string); +} + +/// A client mod: runs in the player's game. world horizon-mod { import log; import game; @@ -119,3 +197,13 @@ world horizon-mod { import storage; export events; } + +/// A server mod (manifest `side = "server"`, `api = "0.3"`, experimental): +/// runs where the world is simulated, on the dedicated server, a LAN host +/// and single player's own server. +world horizon-server-mod { + import log; + import storage; + import players; + export server-events; +} diff --git a/crates/horizon-mods/src/manifest.rs b/crates/horizon-mods/src/manifest.rs index 3a93b2512..1caf2038f 100644 --- a/crates/horizon-mods/src/manifest.rs +++ b/crates/horizon-mods/src/manifest.rs @@ -16,7 +16,10 @@ pub const API: &str = "0.1"; /// The manifest `api` lines this build loads. 0.2 is 0.1 plus content: /// `assets/` and `data/` in the `.hmod`, with blocks and items declared in /// `data//horizon/` (docs/modpacks.md). Code still links API 0.1. -pub const APIS: [&str; 2] = [API, "0.2"]; +/// 0.3 is a server mod (experimental): the `horizon-server-mod` world. +pub const APIS: [&str; 3] = [API, "0.2", SERVER_API]; +/// The line of server mods, experimental: `side = "server"`. +pub const SERVER_API: &str = "0.3"; /// Namespaces no mod may claim: vanilla's, the convention tags' (mods add /// to those, docs/mods.md) and the game's own. const RESERVED_NAMESPACES: [&str; 3] = ["minecraft", "c", "horizon"]; @@ -57,7 +60,7 @@ pub enum Side { /// Runs in the player's game only (HUD, keys, chat commands). #[default] Client, - /// Runs where the world is simulated (rules, blocks); not run yet. + /// Runs where the world is simulated (rules, blocks): `api = "0.3"`. Server, /// Both, and the server tells clients which version it expects. Both, @@ -75,15 +78,22 @@ pub enum Capability { /// New blocks and items from the mod's `data/` (API 0.2): no WIT /// interface, the game reads them before the world loads. Registries, + /// The players on the server and messages to them (server mods). + Players, } impl Capability { - pub const ALL: [Capability; 5] = [ + pub const ALL: [Capability; 6] = [ Capability::GameRead, Capability::Chat, Capability::Hud, Capability::Storage, Capability::Registries, + Capability::Players, ]; + /// Whether a server mod may have it: the others act on a local player. + pub fn on_server(self) -> bool { + matches!(self, Capability::Storage | Capability::Players) + } /// The WIT interface it grants, in `horizon:mods`. pub fn interface(self) -> &'static str { match self { @@ -92,6 +102,7 @@ impl Capability { Capability::Hud => "hud", Capability::Storage => "storage", Capability::Registries => "registries", + Capability::Players => "players", } } /// What the player reads before turning the mod on: "May ". @@ -102,6 +113,7 @@ impl Capability { Capability::Hud => "draw text on your screen", Capability::Storage => "save its own settings to disk", Capability::Registries => "add blocks and items to your worlds", + Capability::Players => "see who is on the server and message them", } } /// The capability a component import needs, `Ok(None)` for one every @@ -132,6 +144,7 @@ impl fmt::Display for Capability { Capability::Hud => "hud", Capability::Storage => "storage", Capability::Registries => "registries", + Capability::Players => "players", }; f.write_str(name) } @@ -162,6 +175,20 @@ impl Manifest { "{MANIFEST}: capability registries needs api = \"0.2\"" )); } + let server = m.side == Side::Server; + if server != (m.api == SERVER_API) { + return Err(format!( + "{MANIFEST}: a server mod is side = \"server\" with api = \"{SERVER_API}\", and only it" + )); + } + if let Some(c) = m + .capabilities + .iter() + .find(|c| c.on_server() != server && **c != Capability::Storage) + { + let side = if server { "client" } else { "server" }; + return Err(format!("{MANIFEST}: capability {c} is for {side} mods")); + } if !m.namespaces.is_empty() && !m.capabilities.contains(&Capability::Registries) { return Err(format!( "{MANIFEST}: namespaces are for content, which needs capability registries" @@ -378,12 +405,32 @@ capabilities = ["game-read", "hud"] fn refuses_bad_ids_and_apis() { let bad_id = EXAMPLE.replace("coords_hud", "Coords HUD"); assert!(Manifest::parse(&bad_id).unwrap_err().contains("is not")); - let bad_api = EXAMPLE.replace("api = \"0.1\"", "api = \"0.3\""); - assert!(Manifest::parse(&bad_api).unwrap_err().contains("API 0.3")); + let bad_api = EXAMPLE.replace("api = \"0.1\"", "api = \"0.4\""); + assert!(Manifest::parse(&bad_api).unwrap_err().contains("API 0.4")); let unknown = format!("{EXAMPLE}network = true\n"); assert!(Manifest::parse(&unknown).is_err()); } + #[test] + fn server_mods_are_api_0_3_with_server_capabilities() { + let server = |api: &str, side: &str, caps: &str| { + Manifest::parse(&format!( + "id = \"w\"\nname = \"W\"\nversion = \"1\"\napi = \"{api}\"\nside = \"{side}\"\ncapabilities = [{caps}]\n" + )) + }; + let m = server("0.3", "server", "\"players\", \"storage\"").unwrap(); + let imports = ["horizon:mods/players@0.1.0", "horizon:mods/storage@0.1.0"]; + assert_eq!(m.check_imports(imports), Ok(())); + for (api, side) in [("0.3", "client"), ("0.3", "both"), ("0.1", "server")] { + let e = server(api, side, "").unwrap_err(); + assert!(e.contains("a server mod is side"), "{e}"); + } + let e = server("0.3", "server", "\"hud\"").unwrap_err(); + assert!(e.contains("capability hud is for client mods"), "{e}"); + let e = server("0.1", "client", "\"players\"").unwrap_err(); + assert!(e.contains("capability players is for server mods"), "{e}"); + } + #[test] fn checks_extra_namespaces() { let content = "id = \"t_and_t\"\nname = \"T\"\nversion = \"1\"\napi = \"0.2\"\ncapabilities = [\"registries\"]\n"; diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index 52da641b4..e80dbdc9f 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -1,5 +1,9 @@ //! Loading and calling mods with wasmtime's component model. use crate::manifest::{Manifest, Package, Side}; +use server_bindings::{ + HorizonServerMod, exports::horizon::mods::server_events::Registration as ServerRegistration, + horizon::mods::players, +}; use std::{ path::{Path, PathBuf}, sync::Arc, @@ -16,6 +20,17 @@ mod bindings { world: "horizon-mod", }); } +/// The server mods' world: `log` and `storage` are the client world's. +mod server_bindings { + wasmtime::component::bindgen!({ + path: "../horizon-mod-sdk/wit", + world: "horizon-server-mod", + with: { + "horizon:mods/log": super::bindings::horizon::mods::log, + "horizon:mods/storage": super::bindings::horizon::mods::storage, + }, + }); +} pub use bindings::horizon::mods::{ game::{Clock, Player}, hud::{Corner, Line}, @@ -25,6 +40,12 @@ use bindings::{ exports::horizon::mods::events::Registration, horizon::mods::{chat, game, hud, log as mod_log, storage}, }; +pub use server_bindings::{ + exports::horizon::mods::server_events::BlockPos, + horizon::mods::players::{GameMode, Player as ServerPlayer}, +}; +type ClientEvents = bindings::exports::horizon::mods::events::Guest; +type ServerEvents = server_bindings::exports::horizon::mods::server_events::Guest; /// A mod's linear memory cap. const MEMORY: usize = 64 << 20; @@ -55,6 +76,26 @@ const STORAGE_WRITE_BUDGET: u64 = 1 << 20; pub struct Snapshot { pub player: Option, pub clock: Option, + /// The players on the server, for server mods. + pub players: Vec, +} + +/// Which mods a game starts: the window's game the client mods, the game +/// simulating the world the server mods, single player in the frame both. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Runs { + Client, + Server, + Both, +} +impl Runs { + fn starts(self, side: Side) -> bool { + match self { + Runs::Both => true, + Runs::Client => side != Side::Server, + Runs::Server => side == Side::Server, + } + } } /// What mods asked the game to show since the last [`Mods::drain`]. @@ -66,6 +107,20 @@ pub enum Output { Feedback { text: String, error: bool }, /// 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. + Tell { + name: String, + player: String, + text: String, + }, + /// `players.broadcast`: a line after the mod's name, to every player. + Broadcast { name: String, text: String }, + /// A server mod command's feedback, to the player who typed it. + Reply { + player: String, + text: String, + error: bool, + }, } /// A mod's text panel, drawn every frame until it changes. @@ -80,6 +135,9 @@ pub enum Status { /// Installed and turned off by the player. Off, Running, + /// Turned on, and run by another game: a server mod in the window while + /// the world runs on its server thread. + Elsewhere, /// Could not load or start, or stopped while running. Failed(String), } @@ -98,8 +156,33 @@ pub struct Entry { struct Running { store: Store, - exports: HorizonMod, - hooks: Registration, + hooks: Hooks, +} + +/// A running mod's exports and the hooks its `init` asked for. +enum Hooks { + Client(HorizonMod, Registration), + Server(HorizonServerMod, ServerRegistration), +} +impl Hooks { + fn client(&self) -> Option<&Registration> { + match self { + Hooks::Client(_, r) => Some(r), + Hooks::Server(..) => None, + } + } + fn server(&self) -> Option<&ServerRegistration> { + match self { + Hooks::Server(_, r) => Some(r), + Hooks::Client(..) => None, + } + } + fn commands(&self) -> &[String] { + match self { + Hooks::Client(_, r) => &r.commands, + Hooks::Server(_, r) => &r.commands, + } + } } struct State { @@ -129,13 +212,23 @@ pub struct Mods { } impl Mods { - /// Reads every mod at `paths` and starts those `enabled` says are on. - /// A command that `reserved` (vanilla's commands) or an earlier mod - /// already uses is refused. + /// Reads every mod at `paths` and starts those `enabled` says are on, + /// client and server mods alike. A command that `reserved` (vanilla's + /// commands) or an earlier mod already uses is refused. pub fn load( paths: &[PathBuf], enabled: impl Fn(&str) -> bool, reserved: impl Fn(&str) -> bool, + ) -> Mods { + Mods::load_for(Runs::Both, paths, enabled, reserved) + } + /// [`Mods::load`], starting only the mods `runs` says this game runs; the + /// others that are on are [`Status::Elsewhere`]. + pub fn load_for( + runs: Runs, + paths: &[PathBuf], + enabled: impl Fn(&str) -> bool, + reserved: impl Fn(&str) -> bool, ) -> Mods { let mut mods = Mods::default(); for path in paths { @@ -153,7 +246,9 @@ impl Mods { Ok(package) => { let on = enabled(&package.manifest.id); entry.manifest = Some(package.manifest.clone()); - if on { + if on && !runs.starts(package.manifest.side) { + entry.status = Status::Elsewhere; + } else if on { // Content is read before the world loads; a mod whose // content is refused stays off, with the reason. let content = crate::Content::read(path, &package.manifest); @@ -184,6 +279,8 @@ impl Mods { let mut linker = Linker::new(&engine); HorizonMod::add_to_linker::>(&mut linker, |s| s) .map_err(|e| e.to_string())?; + players::add_to_linker::>(&mut linker, |s| s) + .map_err(|e| e.to_string())?; self.engine = Some((engine, linker)); } Ok(self.engine.as_ref().expect("made above")) @@ -203,9 +300,6 @@ impl Mods { let Some(wasm) = &package.wasm else { return Ok(None); }; - if m.side == Side::Server { - return Err("server mods do not run yet".into()); - } // Two running mods with the same id would share one `data_dir` // (capability `storage`): the first loaded keeps the id. if self @@ -215,11 +309,13 @@ impl Mods { { return Err(format!("another running mod already uses id {}", m.id)); } + let server = m.side == Side::Server; let taken: Vec = self .entries .iter() .filter_map(|e| e.run.as_ref()) - .flat_map(|r| r.hooks.commands.iter().cloned()) + .filter(|r| r.hooks.server().is_some() == server) + .flat_map(|r| r.hooks.commands().iter().cloned()) .collect(); let snapshot = self.snapshot.clone(); let (engine, linker) = self.engine()?; @@ -252,13 +348,28 @@ impl Mods { let mut store = Store::new(engine, state); store.limiter(|s| &mut s.limits); store.set_fuel(FUEL_INIT).map_err(|e| e.to_string())?; - let exports = - HorizonMod::instantiate(&mut store, &component, linker).map_err(|e| reason(&e))?; - let mut hooks = exports - .horizon_mods_events() - .call_init(&mut store) - .map_err(|e| reason(&e))??; - hooks.commands.retain(|c| { + let mut hooks = if server { + let exports = HorizonServerMod::instantiate(&mut store, &component, linker) + .map_err(|e| reason(&e))?; + let r = exports + .horizon_mods_server_events() + .call_init(&mut store) + .map_err(|e| reason(&e))??; + Hooks::Server(exports, r) + } else { + let exports = + HorizonMod::instantiate(&mut store, &component, linker).map_err(|e| reason(&e))?; + let r = exports + .horizon_mods_events() + .call_init(&mut store) + .map_err(|e| reason(&e))??; + Hooks::Client(exports, r) + }; + let commands = match &mut hooks { + Hooks::Client(_, r) => &mut r.commands, + Hooks::Server(_, r) => &mut r.commands, + }; + commands.retain(|c| { let free = !reserved(c) && !taken.contains(c); if !free { log::warn!("Horizon: mod {} cannot take /{c}: already a command", m.id); @@ -266,17 +377,19 @@ impl Mods { free }); self.out.append(&mut store.data_mut().out); - Ok(Some(Running { - store, - exports, - hooks, - })) + Ok(Some(Running { store, hooks })) } /// True when at least one mod runs: the game skips its mod work otherwise. pub fn is_running(&self) -> bool { self.entries.iter().any(|e| e.run.is_some()) } + /// True when a server mod runs: the server skips its mod work otherwise. + pub fn runs_server(&self) -> bool { + self.entries + .iter() + .any(|e| e.run.as_ref().is_some_and(|r| r.hooks.server().is_some())) + } pub fn entries(&self) -> &[Entry] { &self.entries } @@ -289,8 +402,8 @@ impl Mods { fn each( &mut self, fuel: u64, - wants: impl Fn(&Registration) -> bool, - mut f: impl FnMut(&HorizonMod, &mut Store) -> wasmtime::Result<()>, + wants: impl Fn(&Hooks) -> bool, + mut f: impl FnMut(&Hooks, &mut Store) -> wasmtime::Result<()>, ) { for i in 0..self.entries.len() { if self.entries[i] @@ -302,13 +415,45 @@ impl Mods { } } } + /// [`Mods::each`] over the client mods. + fn each_client( + &mut self, + fuel: u64, + wants: impl Fn(&Registration) -> bool, + mut f: impl FnMut(&ClientEvents, &mut Store) -> wasmtime::Result<()>, + ) { + self.each( + fuel, + |h| h.client().is_some_and(&wants), + |h, s| match h { + Hooks::Client(m, _) => f(m.horizon_mods_events(), s), + Hooks::Server(..) => Ok(()), + }, + ); + } + /// [`Mods::each`] over the server mods. + fn each_server( + &mut self, + fuel: u64, + wants: impl Fn(&ServerRegistration) -> bool, + mut f: impl FnMut(&ServerEvents, &mut Store) -> wasmtime::Result<()>, + ) { + self.each( + fuel, + |h| h.server().is_some_and(&wants), + |h, s| match h { + Hooks::Server(m, _) => f(m.horizon_mods_server_events(), s), + Hooks::Client(..) => Ok(()), + }, + ); + } /// One call into mod `i`; a trap or an overrun turns the mod off. fn call( &mut self, i: usize, fuel: u64, - f: impl FnOnce(&HorizonMod, &mut Store) -> wasmtime::Result, + f: impl FnOnce(&Hooks, &mut Store) -> wasmtime::Result, ) -> Option { let entry = &mut self.entries[i]; let run = entry.run.as_mut()?; @@ -318,7 +463,7 @@ impl Mods { let result = run .store .set_fuel(fuel) - .and_then(|()| f(&run.exports, &mut run.store)); + .and_then(|()| f(&run.hooks, &mut run.store)); // An average over about the last 64 calls. entry.cost = (entry.cost * 63 + started.elapsed()) / 64; self.out.append(&mut run.store.data_mut().out); @@ -341,48 +486,37 @@ impl Mods { /// A game tick. pub fn tick(&mut self, tick: u64) { - self.each( - FUEL_TICK, - |h| h.tick, - |m, s| m.horizon_mods_events().call_tick(s, tick), - ); + self.each_client(FUEL_TICK, |h| h.tick, |m, s| m.call_tick(s, tick)); } /// A rendered frame, `seconds` after the last. pub fn frame(&mut self, seconds: f32) { - self.each( - FUEL_FRAME, - |h| h.frame, - |m, s| m.horizon_mods_events().call_frame(s, seconds), - ); + self.each_client(FUEL_FRAME, |h| h.frame, |m, s| m.call_frame(s, seconds)); } /// A chat line the player received, as plain text. pub fn chat(&mut self, text: &str) { - self.each( - FUEL_EVENT, - |h| h.chat, - |m, s| m.horizon_mods_events().call_chat(s, text), - ); + self.each_client(FUEL_EVENT, |h| h.chat, |m, s| m.call_chat(s, text)); } - /// Whether a running mod owns `/name`. + /// Whether a running client mod owns `/name`. pub fn has_command(&self, name: &str) -> bool { - self.command_owner(name).is_some() + self.command_owner(false, name).is_some() } - fn command_owner(&self, name: &str) -> Option { + fn command_owner(&self, server: bool, name: &str) -> Option { self.entries.iter().position(|e| { - e.run - .as_ref() - .is_some_and(|r| r.hooks.commands.iter().any(|c| c == name)) + e.run.as_ref().is_some_and(|r| { + r.hooks.server().is_some() == server && r.hooks.commands().iter().any(|c| c == name) + }) }) } - /// Runs `line` (without its slash) if a mod owns its command; false - /// when none does. + /// Runs `line` (without its slash) if a client mod owns its command; + /// false when none does. pub fn command(&mut self, line: &str) -> bool { let (name, args) = line.split_once(' ').unwrap_or((line, "")); - let Some(i) = self.command_owner(name) else { + let Some(i) = self.command_owner(false, name) else { return false; }; - let result = self.call(i, FUEL_EVENT, |m, s| { - m.horizon_mods_events().call_command(s, name, args) + let result = self.call(i, FUEL_EVENT, |h, s| match h { + Hooks::Client(m, _) => m.horizon_mods_events().call_command(s, name, args), + Hooks::Server(..) => Ok(Ok(None)), }); match result { Some(Ok(Some(text))) => self.out.push(Output::Feedback { text, error: false }), @@ -391,14 +525,88 @@ impl Mods { } true } - /// The commands running mods own, for suggestions. + /// The commands running client mods own, for suggestions. pub fn commands(&self) -> impl Iterator { + self.owned_commands(false) + } + fn owned_commands(&self, server: bool) -> impl Iterator { self.entries .iter() .filter_map(|e| e.run.as_ref()) - .flat_map(|r| r.hooks.commands.iter().map(String::as_str)) + .filter(move |r| r.hooks.server().is_some() == server) + .flat_map(|r| r.hooks.commands().iter().map(String::as_str)) } + /// A server tick. + pub fn server_tick(&mut self, tick: u64) { + self.each_server(FUEL_TICK, |h| h.tick, |m, s| m.call_tick(s, tick)); + } + /// `player` joined the server (they are in the snapshot's players). + pub fn player_joined(&mut self, player: &ServerPlayer) { + self.each_server( + FUEL_EVENT, + |h| h.joins, + |m, s| m.call_player_joined(s, player), + ); + } + /// `player` left the server (they are no longer in the snapshot's players). + pub fn player_left(&mut self, player: &ServerPlayer) { + self.each_server( + FUEL_EVENT, + |h| h.joins, + |m, s| m.call_player_left(s, player), + ); + } + /// A chat message `player` sent, as plain text. + pub fn player_chat(&mut self, player: &ServerPlayer, text: &str) { + self.each_server(FUEL_EVENT, |h| h.chat, |m, s| m.call_chat(s, player, text)); + } + /// `player` broke `state` at `pos`. + pub fn block_broken(&mut self, player: &ServerPlayer, pos: BlockPos, state: &str) { + self.each_server( + FUEL_EVENT, + |h| h.blocks, + |m, s| m.call_block_broken(s, player, pos, state), + ); + } + /// `player` placed `state` at `pos`. + pub fn block_placed(&mut self, player: &ServerPlayer, pos: BlockPos, state: &str) { + self.each_server( + FUEL_EVENT, + |h| h.blocks, + |m, s| m.call_block_placed(s, player, pos, state), + ); + } + /// The commands running server mods own, for the server's command tree. + pub fn server_commands(&self) -> impl Iterator { + self.owned_commands(true) + } + /// Runs `line` (without its slash), typed by `player`, if a server mod + /// owns its command; its feedback is an [`Output::Reply`]. False when + /// none does. + pub fn server_command(&mut self, player: &ServerPlayer, line: &str) -> bool { + let (name, args) = line.split_once(' ').unwrap_or((line, "")); + let Some(i) = self.command_owner(true, name) else { + return false; + }; + let result = self.call(i, FUEL_EVENT, |h, s| match h { + Hooks::Server(m, _) => m + .horizon_mods_server_events() + .call_command(s, player, name, args), + Hooks::Client(..) => Ok(Ok(None)), + }); + let reply = |text, error| Output::Reply { + player: player.id.clone(), + text, + error, + }; + match result { + Some(Ok(Some(text))) => self.out.push(reply(text, false)), + Some(Err(text)) => self.out.push(reply(text, true)), + Some(Ok(None)) | None => {} + } + true + } /// The running mods' HUD panels. pub fn panels(&self) -> impl Iterator { self.entries @@ -417,7 +625,7 @@ impl Mods { for i in 0..self.entries.len() { let entry = &self.entries[i]; let now = modified(&entry.path); - let was_on = entry.status != Status::Off; + let was_on = !matches!(entry.status, Status::Off | Status::Elsewhere); if now == entry.modified || !was_on { continue; } @@ -495,20 +703,51 @@ impl game::Host for State { self.snapshot.clock } } -impl chat::Host for State { - fn show(&mut self, text: String) { +impl State { + /// Queues a chat line unless the call already sent [`CHAT_PER_CALL`]. + fn say(&mut self, line: impl FnOnce(String) -> Output) -> bool { let shown = self .out .iter() - .filter(|o| matches!(o, Output::Chat { .. })) + .filter(|o| { + matches!( + o, + Output::Chat { .. } | Output::Tell { .. } | Output::Broadcast { .. } + ) + }) .count(); if shown < CHAT_PER_CALL { let name = self.name.clone(); - self.out.push(Output::Chat { - name, - text: clip(text), - }); + self.out.push(line(name)); } + shown < CHAT_PER_CALL + } +} +impl chat::Host for State { + fn show(&mut self, text: String) { + self.say(|name| Output::Chat { + name, + text: clip(text), + }); + } +} +impl players::Host for State { + fn online(&mut self) -> Vec { + self.snapshot.players.clone() + } + fn tell(&mut self, player: String, text: String) -> bool { + self.snapshot.players.iter().any(|p| p.id == player) + && self.say(|name| Output::Tell { + name, + player, + text: clip(text), + }) + } + fn broadcast(&mut self, text: String) { + self.say(|name| Output::Broadcast { + name, + text: clip(text), + }); } } impl hud::Host for State { diff --git a/crates/horizon-mods/src/testing.rs b/crates/horizon-mods/src/testing.rs index 4a62b3838..4fcb595a0 100644 --- a/crates/horizon-mods/src/testing.rs +++ b/crates/horizon-mods/src/testing.rs @@ -87,6 +87,7 @@ impl TestGame { self.mods.set_snapshot(Snapshot { player: self.player.clone(), clock: self.clock, + ..Snapshot::default() }); } diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index 48f77aaef..dd74591d6 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -1,7 +1,8 @@ //! Loads real mods built with the SDK: the coords-hud example and a guest //! that misbehaves on command. Needs `rustup target add wasm32-unknown-unknown`. use horizon_mods::{ - Clock, Corner, Mods, Output, Package, Player, Snapshot, Status, + BlockPos, Clock, Corner, GameMode, Mods, Output, Package, Player, Runs, ServerPlayer, Snapshot, + Status, manifest::componentize, testing::{Script, TestGame}, }; @@ -33,6 +34,8 @@ fn mods_dir() -> &'static Path { "-p", "coords-hud", "-p", + "welcome", + "-p", "horizon-mods-test-guest", "--target-dir", ]) @@ -46,9 +49,13 @@ fn mods_dir() -> &'static Path { let built = target.join("wasm32-unknown-unknown/release"); let dir = target.join("mods"); std::fs::create_dir_all(&dir).unwrap(); - let example = root.join("crates/horizon-mod-sdk/examples/coords-hud/horizon-mod.toml"); + let example = |name: &str| { + let path = format!("crates/horizon-mod-sdk/examples/{name}/horizon-mod.toml"); + std::fs::read_to_string(root.join(path)).unwrap() + }; let mods = [ - ("coords_hud", std::fs::read_to_string(example).unwrap()), + ("coords_hud", example("coords-hud")), + ("welcome", example("welcome")), ("horizon_mods_test_guest", GUEST_MANIFEST.to_string()), ]; for (name, manifest) in mods { @@ -80,6 +87,7 @@ fn player() -> Snapshot { game_time: 100, day_time: 24000 + 6000, }), + players: Vec::new(), } } @@ -475,3 +483,74 @@ fn a_test_script_reloads_and_expects_a_stop() { "the scratch copy and its storage are removed" ); } + +fn alex() -> ServerPlayer { + ServerPlayer { + id: "00000000-0000-4000-8000-000000000001".into(), + name: "Alex".into(), + x: 0.5, + y: 64.0, + z: 0.5, + dimension: "minecraft:the_nether".into(), + game_mode: GameMode::Survival, + health: 20.0, + } +} + +#[test] +fn a_server_mod_runs_only_where_the_world_does() { + // A fresh folder: what the mod stored in an earlier run is beside it. + let dir = mods_dir().join("server"); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("welcome.hmod"); + std::fs::copy(mods_dir().join("welcome.hmod"), &path).unwrap(); + let paths = std::slice::from_ref(&path); + let window = Mods::load_for(Runs::Client, paths, |_| true, |_| false); + assert_eq!(window.entries()[0].status, Status::Elsewhere); + assert!(!window.is_running()); + + let mut mods = Mods::load_for(Runs::Server, paths, |_| true, |c| c == "give"); + assert!(mods.runs_server()); + assert_eq!( + mods.server_commands().collect::>(), + ["online", "mined"] + ); + assert_eq!(mods.commands().count(), 0, "not the window's chat commands"); + let alex = alex(); + mods.set_snapshot(Snapshot { + players: vec![alex.clone()], + ..Snapshot::default() + }); + mods.player_joined(&alex); + let greeted = [ + Output::Tell { + name: "Welcome".into(), + player: alex.id.clone(), + text: "Welcome, Alex! 0 other player(s) online.".into(), + }, + Output::Broadcast { + name: "Welcome".into(), + text: "Alex is here for the first time".into(), + }, + ]; + assert_eq!(mods.drain(), greeted); + let stone = BlockPos { x: 1, y: 63, z: 0 }; + mods.block_broken(&alex, stone, "minecraft:stone"); + assert!(mods.server_command(&alex, "mined")); + assert!(mods.server_command(&alex, "online")); + let reply = |text: &str| Output::Reply { + player: alex.id.clone(), + text: text.into(), + error: false, + }; + assert_eq!( + mods.drain(), + [reply("You broke 1 block(s)"), reply("Alex (the_nether)")] + ); + assert!(!mods.server_command(&alex, "where")); + assert!( + !mods.command("online"), + "a server command isn't the window's" + ); +} diff --git a/docs/api/mods-reference.md b/docs/api/mods-reference.md index ca2fe9d7a..f179e99cc 100644 --- a/docs/api/mods-reference.md +++ b/docs/api/mods-reference.md @@ -1,7 +1,7 @@ # Mod API reference -The contract between Horizon and its mods: the WIT package `horizon:mods@0.1.0`, every interface, type, function and hook in it, and the capabilities a manifest may list. The guide is [mods.md](../mods.md); stability and versions: [stability.md](stability.md). Manifest `api` lines this game serves: `0.1`, `0.2`. +The contract between Horizon and its mods: the WIT package `horizon:mods@0.1.0`, every interface, type, function and hook in it, and the capabilities a manifest may list. The guide is [mods.md](../mods.md); stability and versions: [stability.md](stability.md). Manifest `api` lines this game serves: `0.1`, `0.2`, `0.3`. ## Capabilities @@ -12,12 +12,22 @@ The contract between Horizon and its mods: the WIT package `horizon:mods@0.1.0`, | `hud` | [`hud`](#hud) | draw text on your screen | | `storage` | [`storage`](#storage) | save its own settings to disk | | `registries` | data files (`assets/`, `data/`), no interface | add blocks and items to your worlds | +| `players` | [`players`](#players) | see who is on the server and message them | ## World `horizon-mod` +A client mod: runs in the player's game. + - Imports (what the game offers): `log`, `game`, `chat`, `hud`, `storage` - Exports (what the mod provides): `events` +## World `horizon-server-mod` + +A server mod (manifest `side = "server"`, `api = "0.3"`, experimental): runs where the world is simulated, on the dedicated server, a LAN host and single player's own server. + +- Imports (what the game offers): `log`, `storage`, `players` +- Exports (what the mod provides): `server-events` + ## `log` Access: always granted. @@ -139,3 +149,76 @@ What the game calls. Only the hooks `init` asks for are ever called. | `frame` | `func(seconds: f32)` | Each rendered frame, with the seconds since the last one. | | `command` | `func(name: string, args: string) -> result, string>` | `/name args`: ok(some(text)) is shown as feedback, err(text) in red. | | `chat` | `func(text: string)` | Each chat line the player receives, as plain text. | + +## `players` + +Access: capability `players`. + +Capability `players`, server mods only (manifest `api = "0.3"`, experimental): the players on the server, and messages to them. + +### enum `game-mode` + +| Case | | +| --- | --- | +| `survival` | | +| `creative` | | +| `adventure` | | +| `spectator` | | + +### record `player` + +| Field | Type | | +| --- | --- | --- | +| `id` | `string` | The player's UUID, `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`. | +| `name` | `string` | | +| `x` | `f64` | Feet position, in blocks. | +| `y` | `f64` | | +| `z` | `f64` | | +| `dimension` | `string` | `minecraft:overworld`, `minecraft:the_nether`, ... | +| `game-mode` | `game-mode` | | +| `health` | `f32` | Hit points as vanilla counts them: 20 is full health without effects. | + +| Function | Signature | What it does | +| --- | --- | --- | +| `online` | `func() -> list` | The players online, in the order they joined. | +| `tell` | `func(player: string, text: string) -> bool` | A system message to one player, after the mod's name; false when no player with that id is online. Up to 8 messages per call. | +| `broadcast` | `func(text: string)` | A system message to every player and the server's log, after the mod's name. Counts toward the same 8 per call. | + +## `server-events` + +Access: exported by the mod: the game calls it. + +What the server calls in a server mod (manifest `api = "0.3"`, experimental). Only the hooks `init` asks for are ever called. The player in each event is as the server saw them when it happened. + +### type `player` + +`type player = player` + +### record `registration` + +| Field | Type | | +| --- | --- | --- | +| `commands` | `list` | Commands players may type, without the slash. A name vanilla already uses is refused (vanilla's command runs). | +| `tick` | `bool` | Call `tick` every server tick (20 per second). | +| `joins` | `bool` | Call `player-joined` and `player-left`. | +| `chat` | `bool` | Call `chat` for each chat message a player sends. | +| `blocks` | `bool` | Call `block-broken` and `block-placed`. | + +### record `block-pos` + +| Field | Type | | +| --- | --- | --- | +| `x` | `s32` | | +| `y` | `s32` | | +| `z` | `s32` | | + +| Function | Signature | What it does | +| --- | --- | --- | +| `init` | `func() -> result` | Once, after loading. An error keeps the mod off and is logged. | +| `tick` | `func(tick: u64)` | Each server tick, with the server's tick counter. | +| `player-joined` | `func(player: player)` | A player joined the server; they are in `players.online` already. | +| `player-left` | `func(player: player)` | A player left the server; they are no longer in `players.online`. | +| `chat` | `func(player: player, text: string)` | A chat message a player sent, as plain text. | +| `command` | `func(player: player, name: string, args: string) -> result, string>` | `/name args` typed by `player`: ok(some(text)) is their feedback, err(text) their error in red. | +| `block-broken` | `func(player: player, pos: block-pos, state: string)` | A player broke the block at `pos` in their dimension: `state` is what was there, as `minecraft:oak_log[axis=y]`. | +| `block-placed` | `func(player: player, pos: block-pos, state: string)` | A player placed `state` at `pos` in their dimension. | diff --git a/docs/api/mods.md b/docs/api/mods.md index b382744e9..5db01a9b8 100644 --- a/docs/api/mods.md +++ b/docs/api/mods.md @@ -13,14 +13,14 @@ the player before the mod is turned on, and checked against the component's real | | Count | | --- | --- | -| Interfaces the game offers | 5: `log`, `game`, `chat`, `hud`, `storage` | -| Functions in them | 9 | -| Hooks a mod exports | 5: `init`, `tick`, `frame`, `command`, `chat` | -| Capabilities | 5: `game-read`, `chat`, `hud`, `storage`, `registries` | -| Manifest `api` lines served | 2: `0.1` (code), `0.2` (content) | -| SDK | the `Mod` trait (5 methods), `Registration` (4 builders), `export_mod!`, log helpers | +| Interfaces the game offers | 6: `log`, `game`, `chat`, `hud`, `storage`; `players` for server mods | +| Functions in them | 12 | +| Hooks a mod exports | 5: `init`, `tick`, `frame`, `command`, `chat`; a server mod 8: `init`, `tick`, `player-joined`, `player-left`, `chat`, `command`, `block-broken`, `block-placed` | +| Capabilities | 6: `game-read`, `chat`, `hud`, `storage`, `registries`, `players` | +| Manifest `api` lines served | 3: `0.1` (code), `0.2` (content), `0.3` (server mods, experimental) | +| SDK | the `Mod` trait (5 methods), `Registration` (4 builders), `export_mod!`, log helpers; `server::ServerMod` (8 methods), `server::Registration` (5 builders), `export_server_mod!` | | `cargo horizon-mod` | `new`, `build`, `run`, `test`, `check` | -| Example mods | `coords-hud` (code), `ruby-content` (content) | +| Example mods | `coords-hud` (code), `ruby-content` (content), `welcome` (server) | ## Guide @@ -46,6 +46,8 @@ call, 4 MiB of storage, fuel per call). - `crates/horizon-mod-sdk/examples/coords-hud`: coordinates, facing and time on the HUD; `/where`, `/coords`; storage. - `crates/horizon-mod-sdk/examples/ruby-content`: no code; a gem and a block of ruby from vanilla templates, with their recipes, loot, tags, models, textures and names. +- `crates/horizon-mod-sdk/examples/welcome`: a server mod; greets players who join, announces newcomers (kept in + storage), `/online` and `/mined`. - `crates/horizon-mods/tests/guest`: a mod that misbehaves on command (spins, panics, grows its memory), for the sandbox tests. @@ -74,15 +76,16 @@ scripting runtime in the game. ## Stability Preview ([stability.md](stability.md)): API 0.1 and content 0.2 are served together; a mod built for 0.1.0 keeps -loading on every 0.1.x game. Server mods come as their own line, `api = "0.3"`, experimental first. +loading on every 0.1.x game. Server mods are their own line, `api = "0.3"`, experimental: they may change in any +release. ## Not there yet What real mods need next, in the order modpacks and servers need it: -- **Server mods** (`api = "0.3"`): the same component running on the server thread and the dedicated server, with world events (block - broken or placed, entity spawned or killed, player joined or left), game rules and server commands with typed - arguments. +- **Server mods in the game** (`api = "0.3"`, [Server mods](../mods.md#server-mods-api-03-experimental)): the + contract, runtime and SDK are here; next the server thread, LAN host and dedicated server start them and call + their hooks, then entity events, game rules and server commands with typed arguments. - **World and blocks**: read blocks, block states and biomes in loaded chunks; change them through the server's block log, so clients and the parity harnesses see vanilla's updates. - **Items and inventories**: the player's inventory, held item and open container; item stacks with components. @@ -98,6 +101,8 @@ What real mods need next, in the order modpacks and servers need it: ## Changelog +- API 0.3 (server mods, experimental): world `horizon-server-mod`, capability `players`, the `server-events` + hooks; SDK `server::ServerMod`; example `welcome`. - SDK: `cargo horizon-mod test` and `horizon_mods::testing`, test scripts in TOML; the template has one. - API 0.2 (content): data-driven blocks and items, tags, `horizon:add_to`, terrain adaptation. - API 0.1.0: `log`, `game`, `chat`, `hud`, `storage`; `init`, `tick`, `frame`, `command`, `chat`. diff --git a/docs/api/stability.md b/docs/api/stability.md index 2d4476fc7..30d8c699c 100644 --- a/docs/api/stability.md +++ b/docs/api/stability.md @@ -88,7 +88,7 @@ Deprecations and breaking changes are in bold. The release notes of the game rel | --- | --- | --- | | Mod API: `log`, `game`, `chat`, `hud`, `storage`, `events` | preview | 0.1.0 | | Content mods (`registries`: data-driven blocks and items) | preview | manifest `api = "0.2"` | -| Server mods (events, world, server commands) | not started | manifest `api = "0.3"`, experimental first | +| Server mods: world `horizon-server-mod`, `players`, `server-events` | experimental | manifest `api = "0.3"` | | Script mods (Lua run by an interpreter mod, [mods.md](mods.md#ways-in)) | not started | | | `cargo horizon-mod` (`new`, `build`, `run`), `horizon-mod-sdk` | preview | 0.1.0 | | Shader API | not started | | diff --git a/docs/mods.md b/docs/mods.md index 326007e20..ffe64e88e 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -116,7 +116,7 @@ loading. Ordered by what the first native ports need: | `world-read` | blocks and biomes around the player, within the render distance | minimaps, schematics | | `render` | world-space lines, boxes and ghost blocks in a per-frame budget | Litematica-style placement, waypoints | | `registries` | new blocks, items, entities and recipes, mostly data: JSON models, textures, loot and recipes in the `.hmod`'s `assets/` and `data/` | server side; see [Multiplayer](#multiplayer) | -| `server` | world events (block break/place, entity spawn/death, player join), game rules, server commands | runs where the world is simulated | +| `server` | world events (entity spawn/death), game rules, world read/write, typed server commands | after [server mods 0.3](#server-mods-api-03-experimental)'s players, chat, blocks and commands | | `net` | a mod's own client↔server channel (custom payloads) | only between the two halves of the same mod | There is no file, socket, process or raw-input interface, on purpose. @@ -439,6 +439,38 @@ none. "top": "carve", "bottom": "none", "rigid_junctions": true, "inflate": true } } ``` +### Server mods (API 0.3, experimental) + +A server mod runs where the world is simulated: on the dedicated server, on a +LAN host and on single player's own server, never in a player's window. Its +manifest says `side = "server"` and `api = "0.3"` (and only a server mod may); +its component targets the WIT world `horizon-server-mod` instead of +`horizon-mod`. Experimental: it may change in any release +([stability](api/stability.md)). + +| Interface | Capability | Functions | +|---|---|---| +| `log` | always | as for client mods | +| `storage` | `storage` | as for client mods, in the server's `horizon-mods/` | +| `players` | `players` | `online()`: id, name, position, dimension, game mode, health of each player on; `tell(id, text)`, `broadcast(text)`: system messages after the mod's name, 8 per call | + +| Hook (export `server-events`) | When | +|---|---| +| `init() -> result` | once, after loading | +| `tick(tick)` | each server tick | +| `player-joined(player)`, `player-left(player)` | `registration.joins` | +| `chat(player, text)` | `registration.chat`: each chat message a player sends | +| `command(player, name, args)` | `/name args` typed by a player, for a command it registered; `ok(some)` is that player's feedback, `err` their red error | +| `block-broken(player, pos, state)`, `block-placed(player, pos, state)` | `registration.blocks`, with the state as `minecraft:oak_log[axis=y]` | + +Capabilities that act on a local player (`game-read`, `chat`, `hud`) are for +client mods; `players` is for server mods. In Rust: `impl +horizon_mod_sdk::server::ServerMod` and `export_server_mod!`; the example is +[`welcome`](../crates/horizon-mod-sdk/examples/welcome/src/lib.rs). The +runtime, the registry's `check` and the SDK run them today; the game starts +them once its server code calls these hooks (the next step), and until then a +server mod that is turned on shows as run elsewhere. + ## Versions and compatibility - The API is the WIT package `horizon:mods@0.1.0`. New functions and From e50a4c6443ef1a8dcb997ef79fc47ab759c36f04 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Sun, 25 Oct 2026 20:57:18 +0100 Subject: [PATCH 02/13] Play no place sound when a block item placement is refused Clicking with a torch or flower into a space that is already taken (or where the block cannot stand) made the server-thread client play the block's place sound when the server resent the refused target. BlockItem.place returns FAIL before playSound when canPlace() is false, and the client only hears its own predicted placement, so clear the pending place sound when no placement was predicted. --- crates/horizon-client/src/game/remote.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 03b48df3d..97edae862 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3905,6 +3905,10 @@ impl Game<'_> { if let Some(placed) = &placed { self.predict_place(placed, seq); self.with_hand(hand, Game::consume_held); + } else if let Some(r) = self.remote.as_mut() { + // BlockItem.place plays its sound only once the block is set: the + // server's resend of the target it refused is no placement. + r.placing = None; } if reacts || placed.is_some() { self.with_hand(hand, Game::swing_arm); From 9aa6d7723fd8297a91783c7fb3b6828b8205a81c Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Sun, 25 Oct 2026 21:52:43 +0100 Subject: [PATCH 03/13] Shulker bullets home on the guest the shulker targets A mob that sees a guest (a LAN guest, or the player of the server thread) holds Who::Player as its target, and what it does to that player runs with the guest swapped in. A shulker's bullet, though, keeps the target it was fired with until it lands, and the projectiles tick outside that swap: there Who::Player is the host's own player, so on a server thread the bullet found no target, stopped homing and fell onto the blocks. The bullet now carries the guest's entity id, as ShulkerBullet.finalTarget holds the targeted entity in vanilla (ShulkerAttackGoal.tick passes Shulker.getTarget()), so it homes on the guest among the projectiles' targets and its hit runs as that guest: 4 damage and Levitation. --- crates/horizon-client/src/game/creatures.rs | 24 +++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index f027a04fc..664f1f642 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -508,6 +508,17 @@ impl Game<'_> { Some(host) if !guests.is_empty() => std::mem::take(&mut host.mob_players), _ => Default::default(), }; + // The guests' entity ids by connection, for the shulker bullets fired + // at the guest a mob sees. + let guest_ids: Vec<(u32, u32)> = match self.lan.as_ref() { + Some(host) if !guests.is_empty() => host + .hub + .guests + .iter() + .map(|g| (g.conn, g.entity_id as u32)) + .collect(), + _ => Vec::new(), + }; let mut guest_events = Vec::new(); let level_random; { @@ -582,6 +593,19 @@ impl Game<'_> { let kept = m.tick(&w, &mut scratch, &mut events); horizon_client::mobs::take_mob_pushes(&mut events, from, &mut pushes); if let Some(conn) = seen_guest { + // ShulkerBullet.finalTarget is the guest's entity: the + // bullet homes on it while the projectiles tick, where + // `Who::Player` is the host's own player. + if let Some(&(_, id)) = guest_ids.iter().find(|g| g.0 == conn) { + for e in &mut events[from..] { + if let MobEvent::Projectile(p) = e + && let ProjectileKind::ShulkerBullet { target, .. } = &mut p.kind + && *target == Who::Player + { + *target = Who::Mob(id); + } + } + } let mut k = from; while k < events.len() { if super::lan_mobs::acts_on_player(&events[k]) { From 21019afc2bdfe37454fbe05a609de7ccffc8c5b4 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Sun, 25 Oct 2026 22:18:14 +0100 Subject: [PATCH 04/13] Vehicle storage menus edit the vehicle's own items A chest minecart, hopper minecart or chest boat's menu edits a stand-in container, which is meant to be copied back to the vehicle when the menu closes. close_container took the open container before calling close_cart_container, which then found nothing open and copied nothing: items taken out came back on the next open, and items put in vanished. Copy the stand-in back from the key close_container took. A server player's clicks in such a menu copy it back at once, since the menu is the vehicle's own inventory (ContainerEntity, AbstractMinecartContainer and ChestBoat implement the container the menu reads and writes). --- crates/horizon-client/src/game.rs | 3 +- crates/horizon-client/src/game/lan_actions.rs | 4 ++ crates/horizon-client/src/game/minecarts.rs | 37 +++++++++++++------ 3 files changed, 31 insertions(+), 13 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 1e6158bc4..021d8fa32 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5472,6 +5472,8 @@ impl Game<'_> { self.craft_size = 2; self.craft_table = None; if let Some(key) = self.container.take() { + // A cart's or chest boat's items go back to it. + self.close_cart_container(key); self.container_opener_event(key, false); self.post_block_game_event( "minecraft:container_close", @@ -5511,7 +5513,6 @@ impl Game<'_> { self.world.modified.insert((key.0 >> 4, key.2 >> 4)); } self.close_ender_chest(); - self.close_cart_container(); } /// `quickMoveStack` of the open plain menu for a shift-click. fn inventory_quick_move(&mut self, slot: usize) -> bool { diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 9d4d868e0..cd7d8035b 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1138,6 +1138,10 @@ impl Game<'_> { { self.container_changed(key); } + // A vehicle's menu edits the vehicle's own items. + if let Some(Slots::Block(key)) = slots { + self.store_cart_items(key); + } self.drop_guest_items(host, gi, drops); } S::ContainerClose(p) => { diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index 6b8b51dde..004b72ebf 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -1117,22 +1117,35 @@ impl Game<'_> { self.swing_arm(); true } - /// Closing a cart's container copies the items back. - pub(super) fn close_cart_container(&mut self) { - let Some(key) = self.container.filter(|k| k.1 == CART_KEY_Y) else { - return; - }; - let Some(BlockEntity::Chest(items)) = self.world.block_entities.remove(&key) else { + /// Closing the cart's container open under `key` copies the items back. + pub(super) fn close_cart_container(&mut self, key: (i32, i32, i32)) { + if key.1 != CART_KEY_Y { + return; + } + self.store_cart_items(key); + self.world.block_entities.remove(&key); + if let Some(c) = self.carts.iter().find(|c| c.id as i32 == key.2) + && c.kind == CartKind::Chest + { + let at = [c.position.x, c.position.y, c.position.z]; + let pitch = self.world.random.next_float() * 0.1 + 0.9; + self.audio + .play("minecraft:block.chest.close", Some(at), 0.5, pitch); + } + } + /// The menu of a chest or hopper minecart or a chest boat works on the + /// vehicle's own items (`ContainerEntity`): the placeholder under `key` + /// that the menu edits is copied back to the vehicle. + pub(super) fn store_cart_items(&mut self, key: (i32, i32, i32)) { + if key.1 != CART_KEY_Y { + return; + } + let Some(BlockEntity::Chest(items)) = self.world.block_entities.get(&key) else { return; }; + let items = items.clone(); if let Some(c) = self.carts.iter_mut().find(|c| c.id as i32 == key.2) { c.items = items; - let at = [c.position.x, c.position.y, c.position.z]; - if c.kind == CartKind::Chest { - let pitch = self.world.random.next_float() * 0.1 + 0.9; - self.audio - .play("minecraft:block.chest.close", Some(at), 0.5, pitch); - } } else if let Some(b) = self.boats.iter_mut().find(|b| b.id as i32 == key.2) { b.items = items; } From 2c0d9cc30efe46a2d1c39c9d06cb86b825ff840b Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Sun, 25 Oct 2026 21:37:13 +0100 Subject: [PATCH 05/13] Tick End gateways' server copies on a server without a window A used End gateway never worked again on the server thread or on a dedicated server. TheEndGatewayBlockEntity's server ticker (portalTick) ran only inside the client block-entity pass, which returns at once when there is no renderer, so the 40 tick cooldown that EndGatewayBlock.entityInside starts (triggerCooldown) never ran out. A Game without a renderer now runs portalTick on the gateways it keeps a server copy of, in block-ticking chunks as Level.tickBlockEntities does, and sends triggerCooldown's block event every 2400 ticks of age. --- .../src/game/block_entity_anims.rs | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/crates/horizon-client/src/game/block_entity_anims.rs b/crates/horizon-client/src/game/block_entity_anims.rs index 619fcd009..6df2ff02a 100644 --- a/crates/horizon-client/src/game/block_entity_anims.rs +++ b/crates/horizon-client/src/game/block_entity_anims.rs @@ -171,6 +171,11 @@ impl Game<'_> { /// client tick (`ClientLevel.tickBlockEntities`). pub(super) fn tick_block_entity_anims(&mut self) { let Some(r) = &self.renderer else { + // A server has no window, but its gateways still run their + // server ticker. + if self.remote.is_none() { + self.tick_gateway_servers(); + } return; }; // Sorted by position: the order they tick in, and a quick lookup. @@ -330,6 +335,31 @@ impl Game<'_> { } self.be_anims.present = positions; } + /// `TheEndGatewayBlockEntity.portalTick` (the server ticker) of the + /// gateways a server keeps a copy of, in block-ticking chunks + /// (`Level.tickBlockEntities`): the cooldown an entry started runs out, + /// and every 2400 ticks `triggerCooldown` sends its block event. + fn tick_gateway_servers(&mut self) { + let levels = self.tickets.levels(); + let mut positions: Vec<[i32; 3]> = self + .be_anims + .gateway_servers + .keys() + .copied() + .filter(|p| levels.block_ticking_at(p[0], p[2])) + .collect(); + positions.sort_unstable(); + for pos in positions { + let triggered = self + .be_anims + .gateway_servers + .get_mut(&pos) + .is_some_and(EndGateway::portal_tick); + if triggered { + self.block_entity_event(pos, 1, 0); + } + } + } /// `EndGatewayBlock.entityInside` on the server: whether the gateway at /// `pos` let the entity in (`triggerCooldown`, with its block event). pub(super) fn gateway_enter(&mut self, pos: [i32; 3]) -> bool { From c7432c21e152dfc566580a40917d092c227ac197 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Sun, 25 Oct 2026 22:39:25 +0100 Subject: [PATCH 06/13] Check a server player's moves with the box of its pose A player sprint-swimming up under a ceiling was sent back every tick on the server thread (and for LAN guests): the server never updated the player's pose, and handlePlayerPositionChange's collision check always used a standing 1.8-block box, so the 0.6-block swimming box the client moved with looked like it entered the ceiling. Player.tick ends with updatePlayerPose, and the check uses getBoundingBox, so run updatePlayerPose in the server player's tick and check moves with the pose's dimensions. Fixes #1899. --- crates/horizon-client/src/game/lan_actions.rs | 3 +++ crates/horizon-client/src/lan/hub.rs | 19 +++++++++++++------ 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 9d4d868e0..6dfc68c08 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -2111,6 +2111,9 @@ impl Game<'_> { let _ = w.tick_environment_damage(); let _ = w.apply_fire_contact(); let _ = w.server_hazards_tick(in_wall); + // Player.tick ends with updatePlayerPose: a swimmer, or a player + // crawling under a block, takes the short box its moves are checked with. + let _ = w.update_player_pose(); let mut events = std::mem::take(&mut w.player.events); // WitherRoseBlock.entityInside along those moves. for event in &events { diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index b462536b9..910911d80 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -2175,17 +2175,24 @@ impl Hub { if g.spectator() || g.sleeping { return (false, false); } - let height = if g.fall_flying { - 0.6 + // getBoundingBox: the box of the body's pose (swimming and crawling + // are 0.6 tall), so a swimmer under a ceiling isn't sent back. + let (half, height) = if g.fall_flying { + (0.3, 0.6) + } else if let Some(m) = &g.motion { + ( + f64::from(m.dimensions.width) / 2.0, + f64::from(m.dimensions.height), + ) } else if g.sneaking { - 1.5 + (0.3, 1.5) } else { - 1.8 + (0.3, 1.8) }; let at = |p: [f64; 3]| { Aabb::new( - Vec3::new(p[0] - 0.3, p[1], p[2] - 0.3), - Vec3::new(p[0] + 0.3, p[1] + height, p[2] + 0.3), + Vec3::new(p[0] - half, p[1], p[2] - half), + Vec3::new(p[0] + half, p[1] + height, p[2] + half), ) }; let (old, new) = (at(g.position), at(to)); From d143666e46d910ea7bbad51fa6765f26500c9e07 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Sun, 25 Oct 2026 22:14:43 +0100 Subject: [PATCH 07/13] Mark a server's player dead while its arrival in a level is loading A server's player on a trip into another level was skipped by tick_guests before its zero-health body was marked dead, so a death during the arrival (a /kill, damage) only counted once the destination had loaded. The client already showed the death screen, and a Respawn press in between was refused (guest_respawn wants a dead player) and then lost, leaving the player on the death screen until a second press. LivingEntity.hurt calls die at once, loaded or not: the death half of the guest tick is now its own guest_die, which also runs for a player on a trip. --- crates/horizon-client/src/game/lan_actions.rs | 123 +++++++++--------- 1 file changed, 65 insertions(+), 58 deletions(-) diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 9d4d868e0..409dcb8e5 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1777,6 +1777,10 @@ impl Game<'_> { continue; } if self.on_server_trip(conn) { + // LivingEntity.hurt kills at once (die), whether the level + // has loaded around the player or not: its respawn request + // is taken as soon as it comes. + self.guest_die(host, gi, conn); continue; } let play = host.play.entry(conn).or_default(); @@ -1851,69 +1855,72 @@ impl Game<'_> { self.guest_dig_feedback(host, conn); self.guest_pickups(host, gi); self.guest_orbs(host, gi); - if host.hub.guests[gi].health <= 0.0 && !host.hub.guests[gi].dead { - self.guest_forget_digging(host, conn); - // FishingHook.shouldStopFishing: its owner is dead. - if let Some(play) = host.play.get_mut(&conn) { - play.hook = None; - } + self.guest_die(host, gi, conn); + } + } + + /// `ServerPlayer.die` for a guest whose health has run out: the death + /// message, the loot and experience, the death screen. + fn guest_die(&mut self, host: &mut LanHost, gi: usize, conn: u32) { + if host.hub.guests[gi].health <= 0.0 && !host.hub.guests[gi].dead { + self.guest_forget_digging(host, conn); + // FishingHook.shouldStopFishing: its owner is dead. + if let Some(play) = host.play.get_mut(&conn) { + play.hook = None; } - let g = &mut host.hub.guests[gi]; - if g.health <= 0.0 && !g.dead { - g.dead = true; - g.last_death = Some(g.position.map(|v| v.floor() as i32)); - let (id, at) = (g.entity_id, g.position); - let reward = Experience { - level: g.xp_level, - progress: g.xp_progress, - total: g.xp_total, - } - .death_reward(self.ui.rules.bool("keep_inventory") || g.game_mode == SPECTATOR); - let (name, uuid) = (g.name.clone(), g.uuid); - // ServerPlayer.die: dropAllDeathLoot unless a spectator, from the eyes less 0.3. - let drops = (g.game_mode != SPECTATOR) - .then(|| [at[0], at[1] + g.eye_height() - 0.3, at[2]]); - let cause = host.play.get_mut(&conn).and_then(|p| p.death_cause.take()); - // ServerPlayer.die: with showDeathMessages, the message goes to - // the dying player's death screen and to everyone the team lets - // see it; without it, the death screen gets an empty one. - let message = if self.ui.rules.bool("show_death_messages") { - let me = self.player_text(&name, uuid); - let text = match cause { - Some(key) => horizon_client::text::Text::translate(&key, &[me]), - None if at[1] < f64::from(horizon_client::chunk::MIN_Y - 64) => { - horizon_client::text::Text::translate("death.attack.outOfWorld", &[me]) - } - None => self.guest_death_message(conn, me), - }; - let message = horizon_client::lan::data::component_nbt(&text.component()); - let team = self.score.board.players_team(&name); - if horizon_client::scoreboard::own_death_message_shown(team) { - host.hub.system_message(message.clone()); - if self.options.dedicated.is_some() { - super::dedicated::log( - "INFO", - &format!("System chat: {}", text.plain()), - ); - } else if self.player.is_some() { - self.system_message(text); - } + } + let g = &mut host.hub.guests[gi]; + if g.health <= 0.0 && !g.dead { + g.dead = true; + g.last_death = Some(g.position.map(|v| v.floor() as i32)); + let (id, at) = (g.entity_id, g.position); + let reward = Experience { + level: g.xp_level, + progress: g.xp_progress, + total: g.xp_total, + } + .death_reward(self.ui.rules.bool("keep_inventory") || g.game_mode == SPECTATOR); + let (name, uuid) = (g.name.clone(), g.uuid); + // ServerPlayer.die: dropAllDeathLoot unless a spectator, from the eyes less 0.3. + let drops = + (g.game_mode != SPECTATOR).then(|| [at[0], at[1] + g.eye_height() - 0.3, at[2]]); + let cause = host.play.get_mut(&conn).and_then(|p| p.death_cause.take()); + // ServerPlayer.die: with showDeathMessages, the message goes to + // the dying player's death screen and to everyone the team lets + // see it; without it, the death screen gets an empty one. + let message = if self.ui.rules.bool("show_death_messages") { + let me = self.player_text(&name, uuid); + let text = match cause { + Some(key) => horizon_client::text::Text::translate(&key, &[me]), + None if at[1] < f64::from(horizon_client::chunk::MIN_Y - 64) => { + horizon_client::text::Text::translate("death.attack.outOfWorld", &[me]) } - message - } else { - literal("") + None => self.guest_death_message(conn, me), }; - host.hub.send_to( - conn, - &C::PlayerCombatKill(play::PlayerCombatKill { id, message }), - ); - // LivingEntity.die: the death animation, the dying player included. - host.hub.entity_event(id, 3, at); - if let Some(eyes) = drops { - self.as_guest(host, conn, |game| game.drop_inventory(eyes)); + let message = horizon_client::lan::data::component_nbt(&text.component()); + let team = self.score.board.players_team(&name); + if horizon_client::scoreboard::own_death_message_shown(team) { + host.hub.system_message(message.clone()); + if self.options.dedicated.is_some() { + super::dedicated::log("INFO", &format!("System chat: {}", text.plain())); + } else if self.player.is_some() { + self.system_message(text); + } } - self.spawn_orbs(at, reward); + message + } else { + literal("") + }; + host.hub.send_to( + conn, + &C::PlayerCombatKill(play::PlayerCombatKill { id, message }), + ); + // LivingEntity.die: the death animation, the dying player included. + host.hub.entity_event(id, 3, at); + if let Some(eyes) = drops { + self.as_guest(host, conn, |game| game.drop_inventory(eyes)); } + self.spawn_orbs(at, reward); } } From bbc57aa838c52a7120722a0bf4ea2df2f644c473 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Sun, 25 Oct 2026 21:59:37 +0100 Subject: [PATCH 08/13] Save furnace, brewing stand and crafter edits made through a server menu A server player's clicks in a furnace, brewing stand or crafter menu wrote the block entity's slots but never marked it changed, so the chunk was not saved: an idle furnace (nothing burning, so its own tick changes nothing) given or emptied through its menu rolled back on reopen or chunk unload, losing or duplicating the items. Comparators kept the old reading too. When the click changed the container's slots, call container_changed (BlockEntity.setChanged, reached through Slot.setChanged in vanilla's AbstractContainerMenu.doClick and quickMoveStack), as chest-like menus already do. --- crates/horizon-client/src/game/lan_crafting.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/horizon-client/src/game/lan_crafting.rs b/crates/horizon-client/src/game/lan_crafting.rs index f74935522..d3c4b1825 100644 --- a/crates/horizon-client/src/game/lan_crafting.rs +++ b/crates/horizon-client/src/game/lan_crafting.rs @@ -291,6 +291,11 @@ impl Game<'_> { let at = host.hub.guests[gi].position; self.award_furnace_recipes(pos, at); } + // Slot.setChanged on a changed container slot: BlockEntity.setChanged, + // so the chunk is saved and comparators read the block again. + if (0..items.len()).any(|k| menu.slot(k) != items[k].as_ref()) { + self.container_changed(pos); + } host.play.entry(conn).or_default().crafting.machine = Some((p.container, menu)); host.hub.inventory_clicked(conn, p, &self.world, &changed); true From a6548089c4677e1cf11a03a6f52cff63ba116f2b Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Sun, 25 Oct 2026 23:09:19 +0100 Subject: [PATCH 09/13] Count the death roll in ticks so the dead camera eases instead of shaking The camera's death roll and zoom (GameRenderer.bobHurt, Camera.modifyFovBasedOnDeathOrFluid) read deathTime + partialTick. Horizon derived deathTime from the wall clock since the death message, which the server thread path never set: there deathTime stayed 0, so every frame used 0 + partialTick and the view rolled from 0 to 0.2 degrees and snapped back twenty times a second (with a matching zoom pulse) instead of settling at vanilla's 3.6 degrees. In frame, the wall-clock ticks were not in step with the frame's partial tick either. deathTime is now the tick counter LivingEntity.tickDeath keeps: the in-frame tick already counted it, and the server thread path now resets it when the death screen opens and counts it once per client tick. horizon-ctl state reports it as player.death_time. --- crates/horizon-client/src/game/agent.rs | 2 ++ crates/horizon-client/src/game/fov.rs | 14 +++++++------- crates/horizon-client/src/game/remote.rs | 7 +++++++ 3 files changed, 16 insertions(+), 7 deletions(-) diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 0d2d218ab..79d13be84 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -476,6 +476,8 @@ impl Game<'_> { "absorption": p.health.absorption(), // The hurt animation's ticks left (the camera's hurt tilt). "hurt_time": p.health.hurt_animation_time, + // LivingEntity.deathTime while dead (the camera's death roll). + "death_time": self.death_time(), "air": p.air, "food": p.health.food.food, "saturation": p.health.food.saturation, diff --git a/crates/horizon-client/src/game/fov.rs b/crates/horizon-client/src/game/fov.rs index 27d3fb61e..95e2e1e6e 100644 --- a/crates/horizon-client/src/game/fov.rs +++ b/crates/horizon-client/src/game/fov.rs @@ -64,14 +64,14 @@ impl Game<'_> { }); self.view.tick(eye, target); } - /// The player's `deathTime` while dead or dying. - fn death_time(&self) -> Option { + /// The player's `deathTime` while dead or dying: whole ticks counted by + /// `LivingEntity.tickDeath`, so `deathTime + partialTicks` in + /// `Camera.extractRenderState` rises smoothly across frames. + pub(super) fn death_time(&self) -> Option { let p = self.player.as_ref()?; - p.health.dead_or_dying().then(|| { - self.ui - .died_at - .map_or(0, |t| (t.elapsed().as_secs_f32() * 20.0) as i32) - }) + p.health + .dead_or_dying() + .then(|| self.ui.death_time.min(i32::MAX as u32) as i32) } /// The fluid at the camera, as `Camera.getFluidInCamera` reports it. pub(super) fn camera_fluid(&self, camera: [f64; 3]) -> CameraFluid { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 03b48df3d..4d48e7af5 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -2155,6 +2155,7 @@ impl Game<'_> { self.apply_remote_health(); if p.health <= 0.0 && self.screen != Screen::Dead && self.player.is_some() { self.screen = Screen::Dead; + self.ui.death_time = 0; self.capture(false); } } @@ -2171,6 +2172,7 @@ impl Game<'_> { // screen, whatever health was last sent. if me && self.screen != Screen::Dead && self.player.is_some() { self.screen = Screen::Dead; + self.ui.death_time = 0; self.capture(false); } } @@ -3137,6 +3139,11 @@ impl Game<'_> { ); let was_flying = player.flying; self.sync_player_body(); + // LivingEntity.tickDeath: the local player counts its deathTime once + // per client tick while dead (the camera's death roll and zoom). + if self.screen == Screen::Dead { + self.ui.death_time = self.ui.death_time.saturating_add(1); + } let Some(player) = self.player.as_mut() else { return Ok(()); }; From 2d088739e5fb1e1b28347770a5ae35ca6c00c95a Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Sun, 25 Oct 2026 23:40:17 +0000 Subject: [PATCH 10/13] Fix dropped items following fluid currents Sample item immersion and apply shared entity currents before and after movement, matching vanilla tick order. Cover item-sized fluid scans and flowing-water movement. Co-Authored-By: Codex gpt-6.1-sol --- crates/horizon-client/src/entities.rs | 16 +- crates/horizon-client/src/entities/fluids.rs | 226 +++++++++++++++++++ crates/horizon-client/src/game.rs | 8 +- crates/horizon-client/src/game/remote.rs | 2 +- tools/test_entity_fluid_parity.py | 9 + 5 files changed, 252 insertions(+), 9 deletions(-) create mode 100644 crates/horizon-client/src/entities/fluids.rs diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs index 65536d710..6e8089e9d 100644 --- a/crates/horizon-client/src/entities.rs +++ b/crates/horizon-client/src/entities.rs @@ -10,6 +10,8 @@ use crate::{ use horizon_core::geometry::{Aabb, Vec3}; use horizon_world::block_collision::BlockCollisionRegistry; +mod fluids; + #[derive(Clone, Debug)] pub struct ItemEntity { pub health: i32, @@ -165,18 +167,16 @@ impl ItemEntity { facts: &BlockFacts, collision: &BlockCollisionRegistry<'_>, no_physics: bool, + fluids: &crate::motion::FluidResources, ) -> bool { self.ticks += 1; self.previous = self.position; if self.pickup_delay > 0 && self.pickup_delay != u32::MAX { self.pickup_delay -= 1; } - let eye = world.block( - self.position.x.floor() as i32, - (self.position.y + 0.1).floor() as i32, - self.position.z.floor() as i32, - ); - let in_water = facts.get(eye).fluid == Fluid::Water; + // Entity.baseTick pushes before ItemEntity applies buoyancy and moves. + let (water_height, lava_height) = self.update_fluids(world, fluids); + let in_water = water_height > f64::from(0.1f32); if in_water { // ItemEntity.setUnderwaterMovement self.velocity = Vec3::new( @@ -184,7 +184,7 @@ impl ItemEntity { self.velocity.y + if self.velocity.y < 0.06 { 5.0e-4 } else { 0.0 }, self.velocity.z * 0.99, ); - } else if facts.get(eye).fluid == Fluid::Lava { + } else if lava_height > f64::from(0.1f32) { self.velocity = Vec3::new( self.velocity.x * 0.95, self.velocity.y + if self.velocity.y < 0.06 { 5.0e-4 } else { 0.0 }, @@ -245,6 +245,8 @@ impl ItemEntity { } } self.age += 1; + // ItemEntity.tick refreshes immersion and pushes again after moving. + self.update_fluids(world, fluids); self.age < 6000 && self.position.y > -128.0 } /// `ItemEntity.isMergable` at `age`: a stack below its size whose pickup diff --git a/crates/horizon-client/src/entities/fluids.rs b/crates/horizon-client/src/entities/fluids.rs new file mode 100644 index 000000000..1d202e129 --- /dev/null +++ b/crates/horizon-client/src/entities/fluids.rs @@ -0,0 +1,226 @@ +//! Dropped-item immersion and currents through the shared vanilla fluid helpers. +use super::ItemEntity; +use crate::{ + motion::{FluidResources, LAVA, WATER}, + world::World, +}; +use horizon_core::{ + geometry::{Aabb, Direction, Vec3}, + position::BlockPos, +}; +use horizon_world::{ + entity_fluid::{ + CurrentTarget, EntityFluidInteraction, FluidInteractionWorld, FluidMembership, + FluidSections, FluidTagId, + }, + fluid::{FluidHeightWorld, FluidKind, FluidState}, + fluid_flow::{FluidFlowWorld, flow_at}, + registry::BlockStateId, +}; +type Error = std::convert::Infallible; +struct ItemFluidWorld<'a> { + item: &'a mut ItemEntity, + world: &'a World, + fluids: &'a FluidResources, +} +impl ItemEntity { + pub(super) fn update_fluids(&mut self, world: &World, fluids: &FluidResources) -> (f64, f64) { + let mut interaction = EntityFluidInteraction::new([WATER, LAVA]); + let mut scene = ItemFluidWorld { + item: self, + world, + fluids, + }; + if interaction.update(&mut scene, false, 4096).is_err() { + return (0.0, 0.0); + } + let water_height = interaction.fluid_height(&scene, WATER); + let lava_height = interaction.fluid_height(&scene, LAVA); + let _ = interaction.apply_current(&mut scene, WATER, 0.014); + let _ = interaction.apply_current( + &mut scene, + LAVA, + if world.fast_lava { + 0.007 + } else { + 0.0023333333333333335 + }, + ); + (water_height, lava_height) + } +} +struct Tags; +impl FluidMembership for Tags { + fn fluid_in_tag(&self, kind: FluidKind, tag: FluidTagId) -> bool { + if tag == WATER { + matches!(kind, FluidKind::Water | FluidKind::FlowingWater) + } else { + matches!(kind, FluidKind::Lava | FluidKind::FlowingLava) + } + } +} +impl FluidMembership for ItemFluidWorld<'_> { + fn fluid_in_tag(&self, kind: FluidKind, tag: FluidTagId) -> bool { + Tags.fluid_in_tag(kind, tag) + } +} +impl CurrentTarget for ItemFluidWorld<'_> { + type Error = Error; + fn is_player_class(&self) -> bool { + false + } + fn velocity(&mut self) -> Result { + Ok(self.item.velocity) + } + fn add_delta_movement(&mut self, delta: Vec3) -> Result<(), Error> { + let v = self.item.velocity; + let sum = Vec3::new(v.x + delta.x, v.y + delta.y, v.z + delta.z); + if delta.is_finite() && sum.is_finite() { + self.item.velocity = sum; + } + Ok(()) + } +} +impl FluidInteractionWorld for ItemFluidWorld<'_> { + type Error = Error; + type Chunk = (); + fn interaction_box(&mut self) -> Result, Error> { + Ok(Some( + self.item.bounds().deflate(Vec3::new(0.001, 0.001, 0.001)), + )) + } + fn loaded_chunk(&mut self, x: i32, z: i32) -> Result, Error> { + Ok(self.world.chunks.contains_key(&(x, z)).then_some(())) + } + fn chunk_sections(&mut self, _: ()) -> Result, Error> { + static SECTIONS: [bool; crate::chunk::SECTIONS] = [true; crate::chunk::SECTIONS]; + Ok(FluidSections { + minimum_section_y: crate::chunk::MIN_Y >> 4, + has_fluid: &SECTIONS, + }) + } + fn bounding_box_min_y(&self) -> f64 { + self.item.position.y + } + fn block_x(&self) -> i32 { + self.item.position.x.floor() as i32 + } + fn eye_y(&mut self) -> Result { + Ok(self.item.position.y + f64::from(0.2125f32)) + } + fn block_z(&self) -> i32 { + self.item.position.z.floor() as i32 + } + fn fluid_state(&mut self, p: BlockPos) -> Result { + Ok(self.fluids.fluid(self.world.block(p.x, p.y, p.z))) + } + fn fluid_height(&mut self, f: FluidState, p: BlockPos) -> Result { + f.height_at(self, [p.x, p.y, p.z]) + } + fn camera_height(&mut self, f: FluidState, p: BlockPos) -> Result { + f.camera_height_at(self, [p.x, p.y, p.z]) + } + fn flow(&mut self, f: FluidState, p: BlockPos) -> Result { + flow_at(self, f, p) + } +} +impl FluidHeightWorld for ItemFluidWorld<'_> { + type Error = Error; + fn fluid(&mut self, p: [i32; 3]) -> Result { + Ok(self.fluids.fluid(self.world.block(p[0], p[1], p[2]))) + } + fn sturdy_down(&mut self, p: [i32; 3]) -> Result { + let state = self.world.block(p[0], p[1], p[2]); + Ok(self.fluids.sturdy(state, Direction::Down)) + } +} +impl FluidFlowWorld for ItemFluidWorld<'_> { + type Error = Error; + type Block = BlockStateId; + fn fluid(&mut self, p: BlockPos) -> Result { + Ok(self.fluids.fluid(self.world.block(p.x, p.y, p.z))) + } + fn block(&mut self, p: BlockPos) -> Result { + Ok(self.world.block(p.x, p.y, p.z)) + } + fn blocks_fluid_flow(&self, s: BlockStateId) -> bool { + self.fluids.blocks_flow(s) + } + fn is_ice_class(&self, s: BlockStateId) -> bool { + self.fluids.ice(s) + } + fn is_face_sturdy( + &mut self, + s: BlockStateId, + _: BlockPos, + d: Direction, + ) -> Result { + Ok(self.fluids.sturdy(s, d)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn items_follow_flowing_water_but_still_water_has_no_horizontal_push() { + let root = std::path::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 = crate::assets::Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); + let facts = crate::blocks::BlockFacts::load(&root, assets.registry).unwrap(); + let fluids = FluidResources::new(&assets, &facts).unwrap(); + let collision = crate::collisions::load(&root, assets.registry).unwrap(); + let mut world = World::test_scene(&assets, &render, 3).unwrap(); + let stone = assets.registry.default_state("minecraft:stone").unwrap(); + let water = assets.registry.default_state("minecraft:water").unwrap(); + let mut state = assets.registry.state(water).unwrap().clone(); + state.properties.insert("level".into(), "1".into()); + let flowing = assets.registry.resolve(&state).unwrap(); + for x in 19..=21 { + for z in 19..=21 { + world.set(x, 3, z, stone).unwrap(); + world.set(x, 4, z, water).unwrap(); + } + } + let at = Vec3::new(20.5, 4.0, 20.5); + let item = ItemEntity { + id: 1, + health: 5, + fire_ticks: 0, + stack: crate::items::ItemStack { + item: "minecraft:sugar_cane".into(), + count: 1, + damage: 0, + extra: None, + }, + thrower: None, + position: at, + previous: at, + velocity: Vec3::ZERO, + on_ground: false, + age: 0, + pickup_delay: 0, + bob_offset: 0.0, + ticks: 0, + }; + let mut still = item.clone(); + assert!(still.tick(&world, &facts, &collision, false, &fluids)); + assert_eq!(still.position.x, at.x); + assert_eq!(still.velocity.x, 0.0); + world.set(21, 4, 20, flowing).unwrap(); + let mut carried = item; + assert!(carried.tick(&world, &facts, &collision, false, &fluids)); + // First push is damped by buoyancy before motion, second follows drag. + assert!((carried.position.x - at.x - 0.014 * 0.99).abs() < 1e-12); + assert!((carried.velocity.x - (0.014 * 0.99 * 0.98 + 0.014)).abs() < 1e-12); + for _ in 0..20 { + carried.tick(&world, &facts, &collision, false, &fluids); + } + assert!(carried.position.x > at.x + 0.5); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index f5803ad08..133381b27 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2238,7 +2238,13 @@ impl Game<'_> { let speed = self.world.random.next_float() * 0.2 + 0.1; item.move_towards_closest_space(&self.world, self.res.facts(), speed); } - let alive = item.tick(&self.world, self.res.facts(), self.collision, no_physics); + let alive = item.tick( + &self.world, + self.res.facts(), + self.collision, + no_physics, + &self.res.motion().fluids, + ); cells.moved(i, item.previous, item.position); // ItemEntity.tick: merge every 2 ticks while moving between // blocks, every 40 otherwise, before the lifetime check. diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 2636b0064..7ebccf351 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3464,7 +3464,7 @@ impl Game<'_> { // ticks), and only the server removes it. let (world, facts, collision) = (&self.world, self.res.facts(), self.collision); for d in self.dropped.iter_mut().filter(|_| running) { - d.tick(world, facts, collision, false); + d.tick(world, facts, collision, false, &self.res.motion().fluids); } head_lerps.retain(|_, (_, steps)| *steps > 0); for (item, ticks, at, eye, pitch, yaw) in using { diff --git a/tools/test_entity_fluid_parity.py b/tools/test_entity_fluid_parity.py index b37a3e11d..f8cbf918d 100644 --- a/tools/test_entity_fluid_parity.py +++ b/tools/test_entity_fluid_parity.py @@ -29,6 +29,15 @@ def corpus(): if v[k] is not None:v[k]=[bits(n) for n in v[k]] return v def row(ops,player=False,order=(0,1,2)):return dict(ops=ops,player=player,order=order) + # Dropped items: the 0.25-wide box is deflated by Entity before scanning. + # Cover surface grazing, buoyancy depth, cell boundaries and repeated pushes. + for x in [.5, 1.0, 15.99]: + for y in [0, .1, .7, 8/9-.1, 8/9-.001, 8/9, 1]: + for flow in [(0,0,0),(1,0,0),(-1,0,1),(0,-1,0)]: + update=op(bounds=[x-.124,y+.001,.376,x+.124,y+.249,.624], + base_y=y,eye=y+.2125,block=[int(x),int(y),0], + default=cell(flow=flow)) + yield row([update,op(mode='apply'),update,op(mode='apply')]) values=[-float('inf'),-1,-.0,0,.1,.39999998,.4,.40000004,8/9,1,2,float('inf'),float('nan')] for kind in range(5): for height in values: From 7dfd4c628070d391b3dd16020517eaf64555854d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 01:04:20 +0100 Subject: [PATCH 11/13] Share the player's water and lava tags with dropped items The item's fluid world had its own copy of the FluidTags.WATER/LAVA membership the player's immersion uses; motion now exports that one. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/entities/fluids.rs | 14 ++------------ crates/horizon-client/src/motion.rs | 2 +- crates/horizon-client/src/motion/fluids.rs | 11 ++++++----- 3 files changed, 9 insertions(+), 18 deletions(-) diff --git a/crates/horizon-client/src/entities/fluids.rs b/crates/horizon-client/src/entities/fluids.rs index 1d202e129..fffa0ae2b 100644 --- a/crates/horizon-client/src/entities/fluids.rs +++ b/crates/horizon-client/src/entities/fluids.rs @@ -1,7 +1,7 @@ //! Dropped-item immersion and currents through the shared vanilla fluid helpers. use super::ItemEntity; use crate::{ - motion::{FluidResources, LAVA, WATER}, + motion::{FluidResources, FluidTags, LAVA, WATER}, world::World, }; use horizon_core::{ @@ -49,19 +49,9 @@ impl ItemEntity { (water_height, lava_height) } } -struct Tags; -impl FluidMembership for Tags { - fn fluid_in_tag(&self, kind: FluidKind, tag: FluidTagId) -> bool { - if tag == WATER { - matches!(kind, FluidKind::Water | FluidKind::FlowingWater) - } else { - matches!(kind, FluidKind::Lava | FluidKind::FlowingLava) - } - } -} impl FluidMembership for ItemFluidWorld<'_> { fn fluid_in_tag(&self, kind: FluidKind, tag: FluidTagId) -> bool { - Tags.fluid_in_tag(kind, tag) + FluidTags.fluid_in_tag(kind, tag) } } impl CurrentTarget for ItemFluidWorld<'_> { diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 5918bccd9..734a13176 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -44,7 +44,7 @@ use std::{ pub(crate) mod environment; mod fluids; -pub use fluids::{FluidResources, LAVA, PlayerFluids, WATER}; +pub use fluids::{FluidResources, FluidTags, LAVA, PlayerFluids, WATER}; pub struct MotionResources { pub attributes: Arc, diff --git a/crates/horizon-client/src/motion/fluids.rs b/crates/horizon-client/src/motion/fluids.rs index 89affeb64..894e6d907 100644 --- a/crates/horizon-client/src/motion/fluids.rs +++ b/crates/horizon-client/src/motion/fluids.rs @@ -103,10 +103,10 @@ fn is_tagged(kind: FluidKind, tag: FluidTagId) -> bool { } impl PlayerMotion { pub fn fluid_height(&self, tag: FluidTagId) -> f64 { - self.fluids.interaction.fluid_height(&Membership, tag) + self.fluids.interaction.fluid_height(&FluidTags, tag) } pub fn is_eye_in_fluid(&self, tag: FluidTagId) -> bool { - self.fluids.interaction.is_eye_in_fluid(&Membership, tag) + self.fluids.interaction.is_eye_in_fluid(&FluidTags, tag) } /// `LocalPlayer.isUnderWater`: `wasUnderwater`, the eye sample `Player.tick` /// takes before the base tick (`Entity.isUnderWater` also needs the body @@ -116,11 +116,12 @@ impl PlayerMotion { } /// `Entity.isInLava`. pub fn is_in_lava(&self) -> bool { - !self.fluids.first_tick && self.fluids.interaction.is_in_fluid(&Membership, LAVA) + !self.fluids.first_tick && self.fluids.interaction.is_in_fluid(&FluidTags, LAVA) } } -struct Membership; -impl FluidMembership for Membership { +/// Which fluids `FluidTags.WATER` and `FluidTags.LAVA` hold. +pub struct FluidTags; +impl FluidMembership for FluidTags { fn fluid_in_tag(&self, kind: FluidKind, tag: FluidTagId) -> bool { is_tagged(kind, tag) } From bb3a289caaa091b9ffd910e51780bacb31f0ac4c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 01:07:48 +0100 Subject: [PATCH 12/13] Read the click's changed slots for the machine's setChanged The menu op already lists the slots the click changed; a container slot among them is the Slot.setChanged that saves the block entity. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/lan_crafting.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/lan_crafting.rs b/crates/horizon-client/src/game/lan_crafting.rs index d3c4b1825..db6235c4d 100644 --- a/crates/horizon-client/src/game/lan_crafting.rs +++ b/crates/horizon-client/src/game/lan_crafting.rs @@ -293,7 +293,7 @@ impl Game<'_> { } // Slot.setChanged on a changed container slot: BlockEntity.setChanged, // so the chunk is saved and comparators read the block again. - if (0..items.len()).any(|k| menu.slot(k) != items[k].as_ref()) { + if changed.iter().any(|&s| s < items.len()) { self.container_changed(pos); } host.play.entry(conn).or_default().crafting.machine = Some((p.container, menu)); From b12c89650ed0d7d0f02c7e2bf2a475c3b962e9a3 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 11:46:27 +0100 Subject: [PATCH 13/13] Mod API levels: server mods' players functions are level 1; the registry's lockfile Main gained players.online, tell and broadcast (#1833) after 0.2.69, so they take level 1 with render.set-minimap. horizon-mod-registry's own Cargo.lock picks up wasmparser. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-mod-registry/Cargo.lock | 24 ++++++++++++++++++++++++ crates/horizon-mods/src/api_level.rs | 7 +++++-- docs/api/stability.md | 2 +- 3 files changed, 30 insertions(+), 3 deletions(-) diff --git a/crates/horizon-mod-registry/Cargo.lock b/crates/horizon-mod-registry/Cargo.lock index e93f5b3b5..f80068fcc 100644 --- a/crates/horizon-mod-registry/Cargo.lock +++ b/crates/horizon-mod-registry/Cargo.lock @@ -401,6 +401,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" dependencies = [ "foldhash", + "serde", + "serde_core", ] [[package]] @@ -442,6 +444,7 @@ dependencies = [ "serde_json", "sha2", "toml", + "wasmparser", "zip", ] @@ -649,6 +652,8 @@ checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", "hashbrown", + "serde", + "serde_core", ] [[package]] @@ -921,6 +926,12 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + [[package]] name = "serde" version = "1.0.229" @@ -1326,6 +1337,19 @@ dependencies = [ "wit-bindgen", ] +[[package]] +name = "wasmparser" +version = "0.254.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5ff8685b587722894b6f25958fc608d315b93b8d23647bfb567664e7006d757" +dependencies = [ + "bitflags", + "hashbrown", + "indexmap", + "semver", + "serde", +] + [[package]] name = "webpki-roots" version = "0.26.11" diff --git a/crates/horizon-mods/src/api_level.rs b/crates/horizon-mods/src/api_level.rs index a81cf27bc..e7b72c20b 100644 --- a/crates/horizon-mods/src/api_level.rs +++ b/crates/horizon-mods/src/api_level.rs @@ -10,10 +10,10 @@ pub const LEVEL: u32 = 1; /// Every function the game offers mods, as `interface.function`, with its -/// level. Level 0 is the contract of Horizon 0.2.67 and 0.2.68. A new +/// 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); 29] = [ +pub const FUNCTIONS: [(&str, u32); 32] = [ ("log.write", 0), ("game.get-player", 0), ("game.get-clock", 0), @@ -43,6 +43,9 @@ pub const FUNCTIONS: [(&str, u32); 29] = [ ("render.frame-stats", 0), ("render.set-zoom", 0), ("render.set-minimap", 1), + ("players.online", 1), + ("players.tell", 1), + ("players.broadcast", 1), ]; /// A function's level; None for one this Horizon doesn't have. diff --git a/docs/api/stability.md b/docs/api/stability.md index cea3415d7..65cfc0c13 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 and 0.2.68, level 1 adds `render.set-minimap`. 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`. 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: