Mod API 0.3: capability world for server mods (blocks, biomes)
Server mods get interface world: get-block(dimension, x, y, z) reads a
loaded chunk's block state as "minecraft:oak_log[axis=y]", get-biome its
biome ("minecraft:plains"), and
set-blocks(dimension, changes) sets up to 4096 blocks per call, checked at
once, made as /setblock makes them (place_state: neighbours, light, block
entities, every client told through the block log) after the call, before
that dimension's next tick.
Reads cost no copy: for a mod call the game lends Mods the levels' chunk
maps (moved out with mem::take and put back after), only while a running
mod has world. Writes for a level that isn't ticking (another dimension,
in-frame) wait for it, up to 65,536.
Test scripts get blocks (setup) and expect.blocks; cargo horizon-mod check
reports a trial run's block writes. Example beacons: /beacon builds a
glowstone pillar beside the player, /ground reads the block underfoot and the biome.
parse_state is now a free function so the mod path shares it.
Docs: docs/mods.md (the capability, script keys), docs/api/mods.md and the
regenerated reference.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Generated
+7
@@ -205,6 +205,13 @@ version = "0.22.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||
|
||||
[[package]]
|
||||
name = "beacons"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"horizon-mod-sdk",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bit-set"
|
||||
version = "0.10.0"
|
||||
|
||||
+1
-1
@@ -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", "crates/horizon-mod-sdk/examples/welcome", "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", "crates/horizon-mod-sdk/examples/beacons", "xtask"]
|
||||
resolver = "2"
|
||||
|
||||
[workspace.package]
|
||||
|
||||
@@ -242,6 +242,11 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> {
|
||||
format!("{}: {text}", if error { "error" } else { "feedback" })
|
||||
}
|
||||
Output::Stopped { reason, .. } => return Err(format!("it stopped: {reason}")),
|
||||
Output::SetBlocks {
|
||||
dimension, blocks, ..
|
||||
} => {
|
||||
format!("set {} block(s) in {dimension}", blocks.len())
|
||||
}
|
||||
});
|
||||
}
|
||||
match failed(&mods) {
|
||||
|
||||
@@ -106,6 +106,19 @@ pub(super) struct Levels {
|
||||
parked: HashMap<Dim, Parked>,
|
||||
}
|
||||
|
||||
impl Levels {
|
||||
/// The chunks of each level not in place (capability `world` lends
|
||||
/// them to server mods for a call).
|
||||
#[cfg_attr(not(feature = "mods"), allow(dead_code))]
|
||||
pub(super) fn parked_chunks(
|
||||
&mut self,
|
||||
) -> impl Iterator<Item = (Dim, &mut horizon_client::chunk_map::ChunkMap)> {
|
||||
self.parked
|
||||
.iter_mut()
|
||||
.map(|(d, p)| (*d, &mut p.world.chunks))
|
||||
}
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// A new level for `dim`, opened from the save (`MinecraftServer.createLevels`).
|
||||
fn open_level(&self, dim: Dim) -> Result<Parked> {
|
||||
@@ -295,6 +308,8 @@ impl Game<'_> {
|
||||
};
|
||||
self.update_dedicated_streaming();
|
||||
self.update_world();
|
||||
// What server mods set in this level since its last tick.
|
||||
self.apply_mod_block_writes();
|
||||
result = if paused {
|
||||
self.tick_lan(true);
|
||||
Ok(())
|
||||
|
||||
@@ -49,6 +49,14 @@ pub(super) struct ModsState {
|
||||
/// What players did this tick, for server mods at its end.
|
||||
#[cfg(feature = "mods")]
|
||||
pub(super) events: Vec<ModEvent>,
|
||||
/// A running server mod has capability `world`: its calls get the
|
||||
/// levels' chunks to read.
|
||||
#[cfg(feature = "mods")]
|
||||
pub(super) world: bool,
|
||||
/// Blocks server mods set, by dimension, made before that level's next
|
||||
/// tick.
|
||||
#[cfg(feature = "mods")]
|
||||
pub(super) block_writes: Vec<(String, horizon_mods::BlockChange)>,
|
||||
}
|
||||
impl ModsState {
|
||||
/// The chat's command tree: vanilla's, plus the running mods' commands.
|
||||
@@ -213,6 +221,7 @@ impl Game<'_> {
|
||||
/// The Mods page's rows, from what loaded.
|
||||
fn list_mods(&mut self) {
|
||||
self.mods.server = self.mods.mods.runs_server();
|
||||
self.mods.world = self.mods.mods.wants_world();
|
||||
let dev = &self.mods.dev;
|
||||
self.settings.mods.installed = self
|
||||
.mods
|
||||
@@ -399,8 +408,10 @@ impl Game<'_> {
|
||||
}
|
||||
Text::literal(line).with_color(text::RED)
|
||||
}
|
||||
server
|
||||
@ (Output::Tell { .. } | Output::Broadcast { .. } | Output::Reply { .. }) => {
|
||||
server @ (Output::Tell { .. }
|
||||
| Output::Broadcast { .. }
|
||||
| Output::Reply { .. }
|
||||
| Output::SetBlocks { .. }) => {
|
||||
self.route_server_output(host.as_deref_mut(), server);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -19,33 +19,7 @@ pub const HELP: &[&str] = &[
|
||||
impl Game<'_> {
|
||||
/// Parse `name[k=v,...]` into a registry state (defaults for missing properties).
|
||||
fn parse_state(&self, text: &str) -> Result<BlockStateId> {
|
||||
let (name, props) = match text.split_once('[') {
|
||||
Some((n, rest)) => (n, rest.trim_end_matches(']')),
|
||||
None => (text, ""),
|
||||
};
|
||||
let name = if name.contains(':') {
|
||||
name.to_owned()
|
||||
} else {
|
||||
format!("minecraft:{name}")
|
||||
};
|
||||
let registry = &self.pack.assets.registry;
|
||||
let default = registry
|
||||
.default_state(&name)
|
||||
.ok_or_else(|| format!("unknown block {name}"))?;
|
||||
let mut state = registry
|
||||
.state(default)
|
||||
.ok_or("missing default state")?
|
||||
.clone();
|
||||
for pair in props.split(',').filter(|p| !p.is_empty()) {
|
||||
let (k, v) = pair
|
||||
.split_once('=')
|
||||
.ok_or_else(|| format!("bad property {pair}"))?;
|
||||
if !state.properties.contains_key(k) {
|
||||
return Err(format!("{name} has no property {k}").into());
|
||||
}
|
||||
state.properties.insert(k.to_owned(), v.to_owned());
|
||||
}
|
||||
Ok(registry.resolve(&state)?)
|
||||
parse_state(self.pack.assets.registry, text)
|
||||
}
|
||||
pub(super) fn render_command(&mut self, words: &[&str]) -> Result<Option<Value>> {
|
||||
let int = |i: usize| -> Result<i32> {
|
||||
@@ -137,3 +111,36 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse `name[k=v,...]` into a registry state (defaults for missing properties).
|
||||
pub(super) fn parse_state(
|
||||
registry: &horizon_world::registry::BlockRegistry,
|
||||
text: &str,
|
||||
) -> Result<BlockStateId> {
|
||||
let (name, props) = match text.split_once('[') {
|
||||
Some((n, rest)) => (n, rest.trim_end_matches(']')),
|
||||
None => (text, ""),
|
||||
};
|
||||
let name = if name.contains(':') {
|
||||
name.to_owned()
|
||||
} else {
|
||||
format!("minecraft:{name}")
|
||||
};
|
||||
let default = registry
|
||||
.default_state(&name)
|
||||
.ok_or_else(|| format!("unknown block {name}"))?;
|
||||
let mut state = registry
|
||||
.state(default)
|
||||
.ok_or("missing default state")?
|
||||
.clone();
|
||||
for pair in props.split(',').filter(|p| !p.is_empty()) {
|
||||
let (k, v) = pair
|
||||
.split_once('=')
|
||||
.ok_or_else(|| format!("bad property {pair}"))?;
|
||||
if !state.properties.contains_key(k) {
|
||||
return Err(format!("{name} has no property {k}").into());
|
||||
}
|
||||
state.properties.insert(k.to_owned(), v.to_owned());
|
||||
}
|
||||
Ok(registry.resolve(&state)?)
|
||||
}
|
||||
|
||||
@@ -47,19 +47,72 @@ impl Game<'_> {
|
||||
) -> bool {
|
||||
false
|
||||
}
|
||||
pub(super) fn apply_mod_block_writes(&mut self) {}
|
||||
}
|
||||
|
||||
#[cfg(feature = "mods")]
|
||||
mod run {
|
||||
use super::{Game, LanHost, ModEvent, Who};
|
||||
use horizon_client::chunk_map::ChunkMap;
|
||||
use horizon_client::{
|
||||
command::args::GameMode as Mode,
|
||||
lan::data::component_nbt,
|
||||
text::{self, Text},
|
||||
};
|
||||
use horizon_mods::{BlockPos, GameMode, Output, ServerPlayer};
|
||||
use horizon_mods::{BlockPos, GameMode, Output, ServerPlayer, WorldView};
|
||||
use horizon_protocol::packets::play::{self, Clientbound as C};
|
||||
use horizon_world::registry::BlockStateId;
|
||||
use horizon_world::registry::{BlockRegistry, BlockStateId};
|
||||
|
||||
/// Blocks queued for levels that don't tick (another dimension, in-frame)
|
||||
/// are kept up to this many; the oldest go first.
|
||||
const MAX_QUEUED_WRITES: usize = 1 << 16;
|
||||
|
||||
/// Capability `world`'s view during a call: the levels' chunks, moved out
|
||||
/// of the game for the call and back after it (no copy).
|
||||
struct LentWorld {
|
||||
registry: &'static BlockRegistry,
|
||||
biomes: std::sync::Arc<horizon_client::biome::Biomes>,
|
||||
dims: Vec<(&'static str, ChunkMap)>,
|
||||
}
|
||||
impl WorldView for LentWorld {
|
||||
fn block(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option<String> {
|
||||
let (_, chunks) = self.dims.iter().find(|(d, _)| *d == dimension)?;
|
||||
let chunk = chunks.get(&(x >> 4, z >> 4))?;
|
||||
Some(state_string(self.registry, chunk.block(x & 15, y, z & 15)))
|
||||
}
|
||||
fn biome(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option<String> {
|
||||
let (_, chunks) = self.dims.iter().find(|(d, _)| *d == dimension)?;
|
||||
let chunk = chunks.get(&(x >> 4, z >> 4))?;
|
||||
Some(self.biomes.get(chunk.biome(x, y, z)).name.clone())
|
||||
}
|
||||
fn has_dimension(&self, dimension: &str) -> bool {
|
||||
matches!(
|
||||
dimension,
|
||||
"minecraft:overworld" | "minecraft:the_nether" | "minecraft:the_end"
|
||||
)
|
||||
}
|
||||
fn check_state(&self, state: &str) -> Result<(), String> {
|
||||
crate::game::render_control::parse_state(self.registry, state)
|
||||
.map(drop)
|
||||
.map_err(|e| format!("{state}: {e}"))
|
||||
}
|
||||
}
|
||||
|
||||
/// `minecraft:oak_log[axis=y]`.
|
||||
fn state_string(registry: &BlockRegistry, state: BlockStateId) -> String {
|
||||
let Some(s) = registry.state(state) else {
|
||||
return "minecraft:air".into();
|
||||
};
|
||||
if s.properties.is_empty() {
|
||||
return s.name.clone();
|
||||
}
|
||||
let props: Vec<String> = s
|
||||
.properties
|
||||
.iter()
|
||||
.map(|(k, v)| format!("{k}={v}"))
|
||||
.collect();
|
||||
format!("{}[{}]", s.name, props.join(","))
|
||||
}
|
||||
|
||||
/// `UUID.toString()`.
|
||||
fn uuid_string(u: u128) -> String {
|
||||
@@ -144,6 +197,7 @@ mod run {
|
||||
let players = self.server_players(None);
|
||||
let snapshot = self.mod_snapshot_with(players.clone());
|
||||
self.mods.mods.set_snapshot(snapshot);
|
||||
self.lend_world();
|
||||
let before = std::mem::take(&mut self.mods.players);
|
||||
for p in before
|
||||
.iter()
|
||||
@@ -197,8 +251,80 @@ mod run {
|
||||
}
|
||||
}
|
||||
self.mods.mods.server_tick(self.ticks);
|
||||
self.return_world();
|
||||
self.mods.players = players;
|
||||
self.show_mod_output();
|
||||
self.apply_mod_block_writes();
|
||||
}
|
||||
|
||||
/// Lends the levels' chunks to capability `world` for the calls up to
|
||||
/// [`Game::return_world`], when a running server mod has it.
|
||||
fn lend_world(&mut self) {
|
||||
if !self.mods.world {
|
||||
return;
|
||||
}
|
||||
let mut dims = vec![(self.dim.id(), std::mem::take(&mut self.world.chunks))];
|
||||
for (dim, chunks) in self.levels.parked_chunks() {
|
||||
dims.push((dim.id(), std::mem::take(chunks)));
|
||||
}
|
||||
let registry = self.pack.assets.registry;
|
||||
let biomes = self.res.biomes().clone();
|
||||
self.mods.mods.lend_world(Box::new(LentWorld {
|
||||
registry,
|
||||
biomes,
|
||||
dims,
|
||||
}));
|
||||
}
|
||||
|
||||
/// Puts back the chunks [`Game::lend_world`] lent.
|
||||
fn return_world(&mut self) {
|
||||
let Some(view) = self.mods.mods.take_world() else {
|
||||
return;
|
||||
};
|
||||
let view: Box<dyn std::any::Any> = view;
|
||||
let Ok(lent) = view.downcast::<LentWorld>() else {
|
||||
return;
|
||||
};
|
||||
let mut dims = lent.dims;
|
||||
if let Some(i) = dims.iter().position(|(d, _)| *d == self.dim.id()) {
|
||||
self.world.chunks = dims.swap_remove(i).1;
|
||||
}
|
||||
for (dim, chunks) in self.levels.parked_chunks() {
|
||||
if let Some(i) = dims.iter().position(|(d, _)| *d == dim.id()) {
|
||||
*chunks = dims.swap_remove(i).1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes the blocks server mods set in the level in place, in order,
|
||||
/// as `/setblock` does. Those of other dimensions wait for their level.
|
||||
pub(in crate::game) fn apply_mod_block_writes(&mut self) {
|
||||
if self.mods.block_writes.is_empty() {
|
||||
return;
|
||||
}
|
||||
let dim = self.dim.id();
|
||||
let (now, later): (Vec<_>, Vec<_>) = std::mem::take(&mut self.mods.block_writes)
|
||||
.into_iter()
|
||||
.partition(|(d, _)| d == dim);
|
||||
self.mods.block_writes = later;
|
||||
let registry = self.pack.assets.registry;
|
||||
for (_, b) in now {
|
||||
let state = match crate::game::render_control::parse_state(registry, &b.state) {
|
||||
Ok(state) => state,
|
||||
Err(e) => {
|
||||
log::warn!("Horizon: a server mod set {}: {e}", b.state);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if let Err(e) = self.place_state([b.x, b.y, b.z], state, false) {
|
||||
log::debug!(
|
||||
"Horizon: a server mod's block at {} {} {}: {e:?}",
|
||||
b.x,
|
||||
b.y,
|
||||
b.z
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A player broke (or placed) `state` at `pos`: the player acting now.
|
||||
@@ -240,8 +366,11 @@ mod run {
|
||||
};
|
||||
let snapshot = self.mod_snapshot_with(players);
|
||||
self.mods.mods.set_snapshot(snapshot);
|
||||
self.lend_world();
|
||||
let owned = self.mods.mods.server_command(&me, line);
|
||||
self.return_world();
|
||||
self.show_mod_output();
|
||||
self.apply_mod_block_writes();
|
||||
owned
|
||||
}
|
||||
|
||||
@@ -266,10 +395,14 @@ mod run {
|
||||
};
|
||||
let snapshot = self.mod_snapshot_with(players);
|
||||
self.mods.mods.set_snapshot(snapshot);
|
||||
if !self.mods.mods.server_command(&me, line) {
|
||||
self.lend_world();
|
||||
let owned = self.mods.mods.server_command(&me, line);
|
||||
self.return_world();
|
||||
if !owned {
|
||||
return false;
|
||||
}
|
||||
self.route_mod_output(Some(host));
|
||||
self.apply_mod_block_writes();
|
||||
true
|
||||
}
|
||||
|
||||
@@ -349,6 +482,21 @@ mod run {
|
||||
self.tell_server_player(host.as_deref_mut(), &p.id, line);
|
||||
}
|
||||
}
|
||||
Output::SetBlocks {
|
||||
name,
|
||||
dimension,
|
||||
blocks,
|
||||
} => {
|
||||
let queued = &mut self.mods.block_writes;
|
||||
queued.extend(blocks.into_iter().map(|b| (dimension.clone(), b)));
|
||||
if queued.len() > MAX_QUEUED_WRITES {
|
||||
let over = queued.len() - MAX_QUEUED_WRITES;
|
||||
queued.drain(..over);
|
||||
log::warn!(
|
||||
"Horizon: mod {name} set more blocks than wait for their level: {over} dropped"
|
||||
);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "beacons"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
description = "Example Horizon server mod: /beacon lights a pillar beside you, /ground says what you stand on"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
horizon-mod-sdk = { path = "../.." }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,8 @@
|
||||
id = "beacons"
|
||||
name = "Beacons"
|
||||
version = "0.1.0"
|
||||
description = "/beacon lights a pillar of glowstone beside you; /ground says what you are standing on, and in which biome."
|
||||
authors = ["Horizon"]
|
||||
api = "0.3"
|
||||
side = "server"
|
||||
capabilities = ["players", "world"]
|
||||
@@ -0,0 +1,87 @@
|
||||
//! Example Horizon server mod (`docs/mods.md`, "Server mods") with
|
||||
//! capability `world`: `/beacon` lights a pillar of glowstone two blocks east
|
||||
//! of the player, `/ground` reads the block under their feet and the biome.
|
||||
use horizon_mod_sdk::server::{BlockChange, Player, Registration, ServerMod, players, world};
|
||||
|
||||
/// How tall `/beacon` builds.
|
||||
const HEIGHT: i32 = 4;
|
||||
|
||||
struct Beacons;
|
||||
|
||||
/// The block the player stands in: their feet, floored.
|
||||
fn feet(player: &Player) -> (i32, i32, i32) {
|
||||
(
|
||||
player.x.floor() as i32,
|
||||
player.y.floor() as i32,
|
||||
player.z.floor() as i32,
|
||||
)
|
||||
}
|
||||
|
||||
/// The pillar beside `player`: `HEIGHT` blocks of glowstone, from their feet up.
|
||||
fn pillar(player: &Player) -> Vec<BlockChange> {
|
||||
let (x, y, z) = feet(player);
|
||||
(0..HEIGHT)
|
||||
.map(|dy| BlockChange {
|
||||
x: x + 2,
|
||||
y: y + dy,
|
||||
z,
|
||||
state: "minecraft:glowstone".into(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl ServerMod for Beacons {
|
||||
fn init() -> Result<(Self, Registration), String> {
|
||||
Ok((
|
||||
Beacons,
|
||||
Registration::new().command("beacon").command("ground"),
|
||||
))
|
||||
}
|
||||
|
||||
fn command(
|
||||
&mut self,
|
||||
player: &Player,
|
||||
name: &str,
|
||||
_args: &str,
|
||||
) -> Result<Option<String>, String> {
|
||||
let (x, y, z) = feet(player);
|
||||
if name == "beacon" {
|
||||
world::set_blocks(&player.dimension, &pillar(player))?;
|
||||
players::broadcast(&format!(
|
||||
"{} lit a beacon at {} {y} {z}",
|
||||
player.name,
|
||||
x + 2
|
||||
));
|
||||
return Ok(None);
|
||||
}
|
||||
let below = world::get_block(&player.dimension, x, y - 1, z)
|
||||
.ok_or("The ground under you isn't loaded")?;
|
||||
let biome = world::get_biome(&player.dimension, x, y, z).unwrap_or_default();
|
||||
Ok(Some(format!("You are standing on {below} in {biome}")))
|
||||
}
|
||||
}
|
||||
|
||||
horizon_mod_sdk::export_server_mod!(Beacons);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_pillar_stands_two_blocks_east() {
|
||||
let p = Player {
|
||||
id: String::new(),
|
||||
name: "Alex".into(),
|
||||
x: -0.5,
|
||||
y: 64.0,
|
||||
z: 3.2,
|
||||
dimension: "minecraft:overworld".into(),
|
||||
game_mode: horizon_mod_sdk::server::GameMode::Survival,
|
||||
health: 20.0,
|
||||
};
|
||||
let blocks = pillar(&p);
|
||||
assert_eq!(blocks.len(), HEIGHT as usize);
|
||||
assert_eq!((blocks[0].x, blocks[0].y, blocks[0].z), (1, 64, 3));
|
||||
assert_eq!(blocks[3].y, 67);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
# /ground reads the block under the player and the biome; /beacon sets four blocks of glowstone two to the east.
|
||||
|
||||
[[step]]
|
||||
join = "Alex"
|
||||
blocks = [{ x = 0, y = 63, z = 0, state = "minecraft:grass_block[snowy=false]" }]
|
||||
command = "ground"
|
||||
expect.feedback = "You are standing on minecraft:grass_block[snowy=false] in minecraft:plains"
|
||||
|
||||
[[step]]
|
||||
command = "beacon"
|
||||
expect.broadcast = ["Alex lit a beacon at 2 64 0"]
|
||||
expect.blocks = [
|
||||
{ x = 2, y = 64, z = 0, state = "minecraft:glowstone" },
|
||||
{ x = 2, y = 67, z = 0, state = "minecraft:glowstone" },
|
||||
{ x = 2, y = 68, z = 0, state = "minecraft:air" },
|
||||
]
|
||||
|
||||
# Anywhere the script set nothing is air.
|
||||
[[step]]
|
||||
player = { x = 10.5, z = 10.5 }
|
||||
command = "ground"
|
||||
expect.feedback = "You are standing on minecraft:air in minecraft:plains"
|
||||
@@ -166,6 +166,7 @@ pub mod server {
|
||||
|
||||
pub use exports::horizon::mods::server_events::{BlockPos, Guest as __Guest, Registration};
|
||||
pub use horizon::mods::players::{self, GameMode, Player};
|
||||
pub use horizon::mods::world::{self, BlockChange};
|
||||
|
||||
/// The server's calls into a mod. Only the hooks [`Registration`] asks
|
||||
/// for are called; the others may stay as their defaults.
|
||||
|
||||
@@ -144,6 +144,33 @@ interface players {
|
||||
broadcast: func(text: string);
|
||||
}
|
||||
|
||||
/// Capability `world`, server mods only (manifest `api = "0.3"`,
|
||||
/// experimental): the blocks of the server's loaded chunks, and changes to
|
||||
/// them through the server's own block updates.
|
||||
interface %world {
|
||||
record block-change {
|
||||
x: s32,
|
||||
y: s32,
|
||||
z: s32,
|
||||
/// `minecraft:oak_log[axis=y]`; properties left out take the block's
|
||||
/// defaults, `minecraft:stone` alone is the default state.
|
||||
state: string,
|
||||
}
|
||||
/// The block state at a position in a dimension (`minecraft:overworld`,
|
||||
/// ...), as `minecraft:oak_log[axis=y]`, as of this call: none where the
|
||||
/// server has no chunk loaded there.
|
||||
get-block: func(dimension: string, x: s32, y: s32, z: s32) -> option<string>;
|
||||
/// The biome at a position (`minecraft:plains`, ...), as the server
|
||||
/// stores it (one per 4 x 4 x 4 cell): none where no chunk is loaded.
|
||||
get-biome: func(dimension: string, x: s32, y: s32, z: s32) -> option<string>;
|
||||
/// Sets blocks as `/setblock` does: the old block entity removed,
|
||||
/// neighbours and shapes updated, light, and every player told. Every
|
||||
/// state is checked now (an error queues nothing); the changes are made
|
||||
/// in order after this call returns, before that dimension's next tick;
|
||||
/// one in a chunk not loaded then is skipped. At most 4096 per call.
|
||||
set-blocks: func(dimension: string, blocks: list<block-change>) -> result<_, 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.
|
||||
@@ -205,5 +232,6 @@ world horizon-server-mod {
|
||||
import log;
|
||||
import storage;
|
||||
import players;
|
||||
import %world;
|
||||
export server-events;
|
||||
}
|
||||
|
||||
@@ -80,19 +80,26 @@ pub enum Capability {
|
||||
Registries,
|
||||
/// The players on the server and messages to them (server mods).
|
||||
Players,
|
||||
/// Blocks in the server's loaded chunks, and changes to them (server
|
||||
/// mods; client mods later, where the game runs the world).
|
||||
World,
|
||||
}
|
||||
impl Capability {
|
||||
pub const ALL: [Capability; 6] = [
|
||||
pub const ALL: [Capability; 7] = [
|
||||
Capability::GameRead,
|
||||
Capability::Chat,
|
||||
Capability::Hud,
|
||||
Capability::Storage,
|
||||
Capability::Registries,
|
||||
Capability::Players,
|
||||
Capability::World,
|
||||
];
|
||||
/// 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)
|
||||
matches!(
|
||||
self,
|
||||
Capability::Storage | Capability::Players | Capability::World
|
||||
)
|
||||
}
|
||||
/// The WIT interface it grants, in `horizon:mods`.
|
||||
pub fn interface(self) -> &'static str {
|
||||
@@ -103,6 +110,7 @@ impl Capability {
|
||||
Capability::Storage => "storage",
|
||||
Capability::Registries => "registries",
|
||||
Capability::Players => "players",
|
||||
Capability::World => "world",
|
||||
}
|
||||
}
|
||||
/// What the player reads before turning the mod on: "May <this>".
|
||||
@@ -114,6 +122,7 @@ impl Capability {
|
||||
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",
|
||||
Capability::World => "read and change the world's blocks",
|
||||
}
|
||||
}
|
||||
/// The capability a component import needs, `Ok(None)` for one every
|
||||
@@ -145,6 +154,7 @@ impl fmt::Display for Capability {
|
||||
Capability::Storage => "storage",
|
||||
Capability::Registries => "registries",
|
||||
Capability::Players => "players",
|
||||
Capability::World => "world",
|
||||
};
|
||||
f.write_str(name)
|
||||
}
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
//! 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,
|
||||
HorizonServerMod,
|
||||
exports::horizon::mods::server_events::Registration as ServerRegistration,
|
||||
horizon::mods::{players, world as mod_world},
|
||||
};
|
||||
use std::{
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
sync::{Arc, Mutex},
|
||||
time::{Duration, Instant, SystemTime},
|
||||
};
|
||||
use wasmtime::{
|
||||
@@ -25,6 +26,7 @@ mod server_bindings {
|
||||
wasmtime::component::bindgen!({
|
||||
path: "../horizon-mod-sdk/wit",
|
||||
world: "horizon-server-mod",
|
||||
additional_derives: [PartialEq],
|
||||
with: {
|
||||
"horizon:mods/log": super::bindings::horizon::mods::log,
|
||||
"horizon:mods/storage": super::bindings::horizon::mods::storage,
|
||||
@@ -43,6 +45,7 @@ use bindings::{
|
||||
pub use server_bindings::{
|
||||
exports::horizon::mods::server_events::BlockPos,
|
||||
horizon::mods::players::{GameMode, Player as ServerPlayer},
|
||||
horizon::mods::world::BlockChange,
|
||||
};
|
||||
type ClientEvents = bindings::exports::horizon::mods::events::Guest;
|
||||
type ServerEvents = server_bindings::exports::horizon::mods::server_events::Guest;
|
||||
@@ -55,6 +58,8 @@ const FUEL_INIT: u64 = 2_000_000_000;
|
||||
const FUEL_TICK: u64 = 50_000_000;
|
||||
const FUEL_FRAME: u64 = 10_000_000;
|
||||
const FUEL_EVENT: u64 = 100_000_000;
|
||||
/// Blocks a mod may set per `world.set-blocks` call.
|
||||
pub const BLOCKS_PER_CALL: usize = 4096;
|
||||
/// Chat lines a mod may show per call, HUD lines and their length.
|
||||
const CHAT_PER_CALL: usize = 8;
|
||||
const HUD_LINES: usize = 16;
|
||||
@@ -121,8 +126,32 @@ pub enum Output {
|
||||
text: String,
|
||||
error: bool,
|
||||
},
|
||||
/// `world.set-blocks`: changes to make in `dimension`, in order, each
|
||||
/// state checked by the [`WorldView`] lent for the call.
|
||||
SetBlocks {
|
||||
name: String,
|
||||
dimension: String,
|
||||
blocks: Vec<BlockChange>,
|
||||
},
|
||||
}
|
||||
|
||||
/// The game's world as capability `world` reads it during a call: the
|
||||
/// game lends one with [`Mods::lend_world`] and takes it back after.
|
||||
pub trait WorldView: std::any::Any + Send {
|
||||
/// The block state at a position, `minecraft:oak_log[axis=y]`; `None`
|
||||
/// where no chunk of that dimension is loaded.
|
||||
fn block(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option<String>;
|
||||
/// The biome at a position, `minecraft:plains`; `None` as for blocks.
|
||||
fn biome(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option<String>;
|
||||
/// Whether `dimension` is one the server has.
|
||||
fn has_dimension(&self, dimension: &str) -> bool;
|
||||
/// `Err` (why) for a state string that names no block state.
|
||||
fn check_state(&self, state: &str) -> Result<(), String>;
|
||||
}
|
||||
|
||||
/// The view lent for the current calls, shared by every mod's store.
|
||||
type WorldSlot = Arc<Mutex<Option<Box<dyn WorldView>>>>;
|
||||
|
||||
/// A mod's text panel, drawn every frame until it changes.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Panel {
|
||||
@@ -199,6 +228,7 @@ struct State {
|
||||
/// needs its own budget.
|
||||
storage_budget: u64,
|
||||
limits: StoreLimits,
|
||||
world: WorldSlot,
|
||||
}
|
||||
|
||||
/// The installed mods and the engine running them. `Mods::default()` is
|
||||
@@ -209,9 +239,33 @@ pub struct Mods {
|
||||
entries: Vec<Entry>,
|
||||
snapshot: Arc<Snapshot>,
|
||||
out: Vec<Output>,
|
||||
world: WorldSlot,
|
||||
}
|
||||
|
||||
impl Mods {
|
||||
/// Whether a running mod may use capability `world`: only then is a
|
||||
/// view worth lending.
|
||||
pub fn wants_world(&self) -> bool {
|
||||
self.entries.iter().any(|e| {
|
||||
e.status == Status::Running
|
||||
&& e.manifest
|
||||
.as_ref()
|
||||
.is_some_and(|m| m.capabilities.contains(&crate::Capability::World))
|
||||
})
|
||||
}
|
||||
/// Lends the game's world to capability `world` for the calls until
|
||||
/// [`Mods::take_world`]; with none lent, `get-block` finds nothing and
|
||||
/// `set-blocks` checks only its count.
|
||||
pub fn lend_world(&mut self, view: Box<dyn WorldView>) {
|
||||
if let Ok(mut slot) = self.world.lock() {
|
||||
*slot = Some(view);
|
||||
}
|
||||
}
|
||||
/// The view [`Mods::lend_world`] lent, back to the game.
|
||||
pub fn take_world(&mut self) -> Option<Box<dyn WorldView>> {
|
||||
self.world.lock().ok()?.take()
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -281,6 +335,8 @@ impl Mods {
|
||||
.map_err(|e| e.to_string())?;
|
||||
players::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)
|
||||
.map_err(|e| e.to_string())?;
|
||||
mod_world::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)
|
||||
.map_err(|e| e.to_string())?;
|
||||
self.engine = Some((engine, linker));
|
||||
}
|
||||
Ok(self.engine.as_ref().expect("made above"))
|
||||
@@ -318,6 +374,7 @@ impl Mods {
|
||||
.flat_map(|r| r.hooks.commands().iter().cloned())
|
||||
.collect();
|
||||
let snapshot = self.snapshot.clone();
|
||||
let world = self.world.clone();
|
||||
let (engine, linker) = self.engine()?;
|
||||
let component =
|
||||
Component::new(engine, wasm).map_err(|e| format!("not a component: {e}"))?;
|
||||
@@ -344,6 +401,7 @@ impl Mods {
|
||||
.memory_size(MEMORY)
|
||||
.instances(16)
|
||||
.build(),
|
||||
world,
|
||||
};
|
||||
let mut store = Store::new(engine, state);
|
||||
store.limiter(|s| &mut s.limits);
|
||||
@@ -731,6 +789,40 @@ impl chat::Host for State {
|
||||
});
|
||||
}
|
||||
}
|
||||
impl mod_world::Host for State {
|
||||
fn get_block(&mut self, dimension: String, x: i32, y: i32, z: i32) -> Option<String> {
|
||||
let view = self.world.lock().ok()?;
|
||||
view.as_ref()?.block(&dimension, x, y, z)
|
||||
}
|
||||
fn get_biome(&mut self, dimension: String, x: i32, y: i32, z: i32) -> Option<String> {
|
||||
let view = self.world.lock().ok()?;
|
||||
view.as_ref()?.biome(&dimension, x, y, z)
|
||||
}
|
||||
fn set_blocks(&mut self, dimension: String, blocks: Vec<BlockChange>) -> Result<(), String> {
|
||||
if blocks.len() > BLOCKS_PER_CALL {
|
||||
return Err(format!(
|
||||
"{} blocks: at most {BLOCKS_PER_CALL} per call",
|
||||
blocks.len()
|
||||
));
|
||||
}
|
||||
if let Some(view) = self.world.lock().ok().as_ref().and_then(|v| v.as_ref()) {
|
||||
if !view.has_dimension(&dimension) {
|
||||
return Err(format!("no dimension {dimension}"));
|
||||
}
|
||||
for b in &blocks {
|
||||
view.check_state(&b.state)?;
|
||||
}
|
||||
}
|
||||
if !blocks.is_empty() {
|
||||
self.out.push(Output::SetBlocks {
|
||||
name: self.name.clone(),
|
||||
dimension,
|
||||
blocks,
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl players::Host for State {
|
||||
fn online(&mut self) -> Vec<ServerPlayer> {
|
||||
self.snapshot.players.clone()
|
||||
|
||||
@@ -29,6 +29,54 @@ pub struct TestGame {
|
||||
/// Every name that joined, for their id.
|
||||
names: Vec<String>,
|
||||
tick: u64,
|
||||
/// Capability `world`'s Overworld: the blocks a script set or the mod
|
||||
/// changed; every other block, and the other dimensions, are air. Every
|
||||
/// biome is the dimension's plainest: plains, nether wastes, the end.
|
||||
pub world: std::collections::BTreeMap<(i32, i32, i32), String>,
|
||||
}
|
||||
|
||||
/// The world a script's mod reads: [`TestGame::world`], copied for a step.
|
||||
struct ScriptWorld(std::collections::BTreeMap<(i32, i32, i32), String>);
|
||||
|
||||
impl crate::WorldView for ScriptWorld {
|
||||
fn block(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option<String> {
|
||||
let here = (dimension == "minecraft:overworld")
|
||||
.then(|| self.0.get(&(x, y, z)).cloned())
|
||||
.flatten();
|
||||
Some(here.unwrap_or_else(|| "minecraft:air".into()))
|
||||
}
|
||||
fn biome(&self, dimension: &str, _x: i32, _y: i32, _z: i32) -> Option<String> {
|
||||
let biome = match dimension {
|
||||
"minecraft:overworld" => "minecraft:plains",
|
||||
"minecraft:the_nether" => "minecraft:nether_wastes",
|
||||
"minecraft:the_end" => "minecraft:the_end",
|
||||
_ => return None,
|
||||
};
|
||||
Some(biome.into())
|
||||
}
|
||||
fn has_dimension(&self, dimension: &str) -> bool {
|
||||
matches!(
|
||||
dimension,
|
||||
"minecraft:overworld" | "minecraft:the_nether" | "minecraft:the_end"
|
||||
)
|
||||
}
|
||||
fn check_state(&self, state: &str) -> Result<(), String> {
|
||||
// No registry here: the shape only (the game checks the names).
|
||||
let name = state.split('[').next().unwrap_or_default();
|
||||
let plain = |t: &str| {
|
||||
!t.is_empty()
|
||||
&& t.bytes()
|
||||
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"_.-/".contains(&b))
|
||||
};
|
||||
let ok = match name.split_once(':') {
|
||||
Some((ns, path)) => plain(ns) && plain(path),
|
||||
None => plain(name),
|
||||
};
|
||||
let closed = !state.contains('[') || state.ends_with(']');
|
||||
(ok && closed)
|
||||
.then_some(())
|
||||
.ok_or_else(|| format!("{state} is not a block state"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a script starts: standing at 0.5 64 0.5 in the Overworld, facing
|
||||
@@ -71,6 +119,7 @@ impl TestGame {
|
||||
players: Vec::new(),
|
||||
names: Vec::new(),
|
||||
tick: 0,
|
||||
world: Default::default(),
|
||||
};
|
||||
copy_mod(hmod, ©)?;
|
||||
game.start()?;
|
||||
@@ -309,9 +358,10 @@ pub struct ClockSet {
|
||||
}
|
||||
|
||||
/// One step. Its parts happen in this order: `reload`, `title-screen`,
|
||||
/// `join`, `player`, `clock`, `ticks`, `frames`, `chat`, `command`, `break`,
|
||||
/// `place`, `leave`; then `expect` is checked against what the mod showed
|
||||
/// during the step. For a server mod, `player`, `chat`, `command`, `break`
|
||||
/// `blocks`, `join`, `player`, `clock`, `ticks`, `frames`, `chat`, `command`,
|
||||
/// `break`, `place`, `leave`; then the blocks the mod set are made, and
|
||||
/// `expect` is checked against what the mod showed and changed during the
|
||||
/// step. For a server mod, `player`, `chat`, `command`, `break`
|
||||
/// and `place` are the doing of the player named by `as`, or of the first
|
||||
/// player on.
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
@@ -338,6 +388,10 @@ pub struct Step {
|
||||
#[serde(rename = "break")]
|
||||
broken: Option<BlockSet>,
|
||||
place: Option<BlockSet>,
|
||||
/// Blocks of the Overworld before the rest of the step (capability
|
||||
/// `world`); every other block is air.
|
||||
#[serde(default)]
|
||||
blocks: Vec<BlockSet>,
|
||||
#[serde(default)]
|
||||
expect: Expect,
|
||||
}
|
||||
@@ -360,6 +414,9 @@ pub struct Expect {
|
||||
/// The panel's lines (`[]`: no panel) and its corner.
|
||||
panel: Option<Vec<String>>,
|
||||
corner: Option<String>,
|
||||
/// Blocks of the Overworld after the step, the mod's changes made
|
||||
/// (capability `world`).
|
||||
blocks: Option<Vec<BlockSet>>,
|
||||
/// The mod is turned off during this step, for a reason holding this text.
|
||||
/// Without it, a mod that stops fails the test.
|
||||
stopped: Option<String>,
|
||||
@@ -464,6 +521,11 @@ impl Step {
|
||||
game.player = None;
|
||||
game.clock = None;
|
||||
}
|
||||
for b in &self.blocks {
|
||||
game.world.insert((b.x, b.y, b.z), b.state.clone());
|
||||
}
|
||||
game.mods
|
||||
.lend_world(Box::new(ScriptWorld(game.world.clone())));
|
||||
if let Some(name) = &self.join {
|
||||
game.join(name);
|
||||
}
|
||||
@@ -528,7 +590,19 @@ impl Step {
|
||||
{
|
||||
return Err(format!("{name} is not on the server"));
|
||||
}
|
||||
game.mods.take_world();
|
||||
let out = game.drain();
|
||||
for o in &out {
|
||||
if let Output::SetBlocks {
|
||||
dimension, blocks, ..
|
||||
} = o
|
||||
&& dimension == "minecraft:overworld"
|
||||
{
|
||||
for b in blocks {
|
||||
game.world.insert((b.x, b.y, b.z), b.state.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
let stopped = out.iter().find_map(|o| match o {
|
||||
Output::Stopped { reason, .. } => Some(reason.as_str()),
|
||||
_ => None,
|
||||
@@ -612,6 +686,18 @@ impl Step {
|
||||
.unwrap_or_default();
|
||||
same("panel", want, &got)?;
|
||||
}
|
||||
if let Some(want) = &e.blocks {
|
||||
for b in want {
|
||||
let got = game.world.get(&(b.x, b.y, b.z));
|
||||
let got = got.map_or("minecraft:air", String::as_str);
|
||||
if got != b.state {
|
||||
return Err(format!(
|
||||
"block at {} {} {}: expected {}, got {got}",
|
||||
b.x, b.y, b.z, b.state
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(want) = &e.corner {
|
||||
let got = game.panel().map(|p| corner_name(p.corner).to_string());
|
||||
same("corner", &Some(want.clone()), &got)?;
|
||||
|
||||
@@ -36,6 +36,8 @@ fn mods_dir() -> &'static Path {
|
||||
"-p",
|
||||
"welcome",
|
||||
"-p",
|
||||
"beacons",
|
||||
"-p",
|
||||
"horizon-mods-test-guest",
|
||||
"--target-dir",
|
||||
])
|
||||
@@ -56,6 +58,7 @@ fn mods_dir() -> &'static Path {
|
||||
let mods = [
|
||||
("coords_hud", example("coords-hud")),
|
||||
("welcome", example("welcome")),
|
||||
("beacons", example("beacons")),
|
||||
("horizon_mods_test_guest", GUEST_MANIFEST.to_string()),
|
||||
];
|
||||
for (name, manifest) in mods {
|
||||
@@ -412,7 +415,12 @@ capabilities = ["registries"]
|
||||
fn the_examples_test_scripts_pass() {
|
||||
let examples = Path::new(env!("CARGO_MANIFEST_DIR")).join("../horizon-mod-sdk/examples");
|
||||
let mut ran = 0;
|
||||
for (example, hmod) in [("coords-hud", "coords_hud"), ("welcome", "welcome")] {
|
||||
let examples_and_files = [
|
||||
("coords-hud", "coords_hud"),
|
||||
("welcome", "welcome"),
|
||||
("beacons", "beacons"),
|
||||
];
|
||||
for (example, hmod) in examples_and_files {
|
||||
for entry in std::fs::read_dir(examples.join(example).join("tests")).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
let script = Script::parse(&std::fs::read_to_string(&path).unwrap()).unwrap();
|
||||
@@ -423,7 +431,24 @@ fn the_examples_test_scripts_pass() {
|
||||
ran += 1;
|
||||
}
|
||||
}
|
||||
assert_eq!(ran, 4);
|
||||
assert_eq!(ran, 5);
|
||||
}
|
||||
|
||||
/// Capability `world` without a world lent (the registry's trial run):
|
||||
/// `get-block` finds nothing, `set-blocks` checks its count and queues.
|
||||
#[test]
|
||||
fn a_server_mod_without_a_world_reads_nothing() {
|
||||
let mut game = TestGame::load(&mods_dir().join("beacons.hmod")).unwrap();
|
||||
game.join("Alex");
|
||||
let alex = game.players[0].clone();
|
||||
assert!(game.player_command(&alex, "ground"));
|
||||
let out = game.drain();
|
||||
assert!(
|
||||
out.iter()
|
||||
.any(|o| matches!(o, Output::Reply { text, error: true, .. }
|
||||
if text == "The ground under you isn't loaded")),
|
||||
"{out:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -13,6 +13,7 @@ The contract between Horizon and its mods: the WIT package `horizon:mods@0.1.0`,
|
||||
| `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` | [`world`](#world) | read and change the world's blocks |
|
||||
|
||||
## World `horizon-mod`
|
||||
|
||||
@@ -25,7 +26,7 @@ A client mod: runs in the player's game.
|
||||
|
||||
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`
|
||||
- Imports (what the game offers): `log`, `storage`, `players`, `world`
|
||||
- Exports (what the mod provides): `server-events`
|
||||
|
||||
## `log`
|
||||
@@ -184,6 +185,27 @@ Capability `players`, server mods only (manifest `api = "0.3"`, experimental): t
|
||||
| `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. |
|
||||
|
||||
## `world`
|
||||
|
||||
Access: capability `world`.
|
||||
|
||||
Capability `world`, server mods only (manifest `api = "0.3"`, experimental): the blocks of the server's loaded chunks, and changes to them through the server's own block updates.
|
||||
|
||||
### record `block-change`
|
||||
|
||||
| Field | Type | |
|
||||
| --- | --- | --- |
|
||||
| `x` | `s32` | |
|
||||
| `y` | `s32` | |
|
||||
| `z` | `s32` | |
|
||||
| `state` | `string` | `minecraft:oak_log[axis=y]`; properties left out take the block's defaults, `minecraft:stone` alone is the default state. |
|
||||
|
||||
| Function | Signature | What it does |
|
||||
| --- | --- | --- |
|
||||
| `get-block` | `func(dimension: string, x: s32, y: s32, z: s32) -> option<string>` | The block state at a position in a dimension (`minecraft:overworld`, ...), as `minecraft:oak_log[axis=y]`, as of this call: none where the server has no chunk loaded there. |
|
||||
| `get-biome` | `func(dimension: string, x: s32, y: s32, z: s32) -> option<string>` | The biome at a position (`minecraft:plains`, ...), as the server stores it (one per 4 x 4 x 4 cell): none where no chunk is loaded. |
|
||||
| `set-blocks` | `func(dimension: string, blocks: list<block-change>) -> result<_, string>` | Sets blocks as `/setblock` does: the old block entity removed, neighbours and shapes updated, light, and every player told. Every state is checked now (an error queues nothing); the changes are made in order after this call returns, before that dimension's next tick; one in a chunk not loaded then is skipped. At most 4096 per call. |
|
||||
|
||||
## `server-events`
|
||||
|
||||
Access: exported by the mod: the game calls it.
|
||||
|
||||
+7
-5
@@ -84,11 +84,11 @@ release.
|
||||
What real mods need next, in the order modpacks and servers need it:
|
||||
|
||||
- **More for server mods** (`api = "0.3"`, [Server mods](../mods.md#server-mods-api-03-experimental)): they run
|
||||
on the server thread, a LAN host and the dedicated server today, with joins, chat, commands and players' block
|
||||
breaking and placing; next entity events, game rules, server commands with typed arguments sent to clients'
|
||||
command trees.
|
||||
- **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.
|
||||
on the server thread, a LAN host and the dedicated server today, with joins, chat, commands, players' block
|
||||
breaking and placing, and `world` (read blocks and biomes, set blocks as `/setblock` does); next entity events, game rules,
|
||||
server commands with typed arguments sent to clients' command trees.
|
||||
- **World and blocks**: blocks, block states and biomes are there for server mods (`world`); next block entities,
|
||||
and `world` for client mods (raycasts, single player and LAN hosts).
|
||||
- **Items and inventories**: the player's inventory, held item and open container; item stacks with components.
|
||||
- **Entities**: query and change entities near a position; spawn from a mod's own entity types (data first).
|
||||
- **Block entities and menus**: ticking machines with slots and their screens.
|
||||
@@ -102,6 +102,8 @@ What real mods need next, in the order modpacks and servers need it:
|
||||
|
||||
## Changelog
|
||||
|
||||
- API 0.3: capability `world` (`get-block`, `get-biome`, `set-blocks`); example `beacons`; test scripts' `blocks` and
|
||||
`expect.blocks`.
|
||||
- Server mods run in the game: single player (server thread and in-frame), LAN hosts, the dedicated server.
|
||||
- API 0.3 (server mods, experimental): world `horizon-server-mod`, capability `players`, the `server-events`
|
||||
hooks; SDK `server::ServerMod`; example `welcome`.
|
||||
|
||||
+17
-1
@@ -278,6 +278,7 @@ A step's parts happen in this order:
|
||||
| --- | --- |
|
||||
| `reload = true` | stops the mod and starts it again, as a rebuild does in the game: its memory starts over, its `storage` stays |
|
||||
| `title-screen = true` | no player and no clock until a step sets them |
|
||||
| `blocks = [{ x = 0, y = 63, z = 0, state = "minecraft:stone" }]` | server mods with `world`: those blocks of the Overworld, before the rest of the step (every other block is air, every biome the dimension's plainest: plains, nether wastes, the end) |
|
||||
| `player = { x = 3.0, ... }`, `clock = { day-time = 0 }` | changes those fields (`x y z yaw pitch health food dimension`, `game-time day-time`) |
|
||||
| `ticks = n`, `frames = n` | that many ticks (the game's tick counter and the clock move on), then frames 1/60 s apart |
|
||||
| `chat = "<Steve> hi"` | a chat line the player receives |
|
||||
@@ -303,6 +304,7 @@ checked:
|
||||
| `feedback = "..."`, `error = "..."` | the command's answer, shown plain or in red |
|
||||
| `panel = ["..."]`, `corner = "top-left"` | its HUD panel's lines (`[]`: no panel) and corner |
|
||||
| `told = ["Alex: Welcome!"]`, `broadcast = ["..."]` | server mods: every `players.tell` (as `name: text`) and `players.broadcast`, in order |
|
||||
| `blocks = [{ x = 2, y = 64, z = 0, state = "minecraft:glowstone" }]` | server mods with `world`: those blocks of the Overworld after the step, the mod's `set-blocks` made (the script checks a state's shape; the game checks its name) |
|
||||
| `stopped = "panic"` | the mod was turned off, for a reason holding this text; without it, a mod that traps, panics or overruns fails the test |
|
||||
|
||||
Unknown keys are errors, so a typo never passes silently. The same runner is
|
||||
@@ -465,6 +467,7 @@ its component targets the WIT world `horizon-server-mod` instead of
|
||||
| `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 |
|
||||
| `world` | `world` | `get-block(dimension, x, y, z)`: the state in a loaded chunk, `minecraft:oak_log[axis=y]`; `get-biome(dimension, x, y, z)`: `minecraft:plains`, ...; `set-blocks(dimension, changes)`: up to 4096 per call, checked at once, made as `/setblock` makes them (neighbours, light, block entities, every player told) after the call, before that dimension's next tick |
|
||||
|
||||
| Hook (export `server-events`) | When |
|
||||
|---|---|
|
||||
@@ -478,7 +481,20 @@ its component targets the WIT world `horizon-server-mod` instead of
|
||||
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).
|
||||
[`welcome`](../crates/horizon-mod-sdk/examples/welcome/src/lib.rs), and with
|
||||
`world`, [`beacons`](../crates/horizon-mod-sdk/examples/beacons/src/lib.rs).
|
||||
|
||||
**Capability `world`.** Reads are of the server's loaded chunks as they are
|
||||
during the call: the game lends a server mod's call the levels' chunk maps
|
||||
(moved, not copied, and only while a running mod has `world`), so a read
|
||||
costs a map lookup and no copy of the world. A dimension with no chunk loaded
|
||||
at a position reads as none. Writes go through the same code as `/setblock`,
|
||||
so block updates, light, block entities and every client (LAN guests,
|
||||
dedicated server players) see them as vanilla's; the parity harnesses test
|
||||
that code. Changes for a dimension whose level isn't ticking wait for it
|
||||
(in-frame single player ticks only the player's), up to 65,536 blocks; a
|
||||
change in a chunk that isn't loaded when it is made is skipped, as `/setblock`
|
||||
refuses one.
|
||||
|
||||
**Where they run.** The game that simulates the world starts the server mods
|
||||
that are on, and only that one:
|
||||
|
||||
Reference in New Issue
Block a user