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