Merge main (save.rs tests: the POI tests beside #2073's loot test)

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