Merge remote-tracking branch 'upstream/main' into tmp-resolve-2298

This commit is contained in:
Carlos Nunez
2026-10-26 14:13:17 -04:00
38 changed files with 1166 additions and 214 deletions
@@ -23,6 +23,7 @@ fn stack(spec: &str) -> LootStack {
map: false,
exploration: None,
ominous_amplifier: None,
stew_effects: Vec::new(),
};
for e in parts {
let (name, level) = e.rsplit_once(':').unwrap_or((e, "1"));
+20 -3
View File
@@ -1228,13 +1228,19 @@ pub fn campfire_particles<'a>(
if r.next_float() < 0.11 {
let count = next_int(r, 2) + 2;
for _ in 0..count {
make_campfire_smoke(engine, pos, signal);
make_campfire_smoke(engine, pos, signal, false);
}
}
}
}
/// `CampfireBlock.makeParticles` (always visible, overriding the limiter).
pub fn make_campfire_smoke(engine: &mut ParticleEngine, pos: [i32; 3], signal: bool) {
/// `CampfireBlock.makeParticles` (always visible, overriding the limiter);
/// `smoking` adds the plain smoke puff at the logs.
pub fn make_campfire_smoke(
engine: &mut ParticleEngine,
pos: [i32; 3],
signal: bool,
smoking: bool,
) {
let r = engine.random();
let sign = |r: &mut LegacyRandom| if r.next_boolean() { 1.0 } else { -1.0 };
let dx = r.next_double() / 3.0;
@@ -1248,6 +1254,17 @@ pub fn make_campfire_smoke(engine: &mut ParticleEngine, pos: [i32; 3], signal: b
T::CampfireCosySmoke
};
engine.create(&ParticleOptions::simple(ty), [x, y, z], [0.0, 0.07, 0.0]);
if smoking {
let r = engine.random();
let dx = r.next_double() / 4.0 * sign(r);
let dz = r.next_double() / 4.0 * sign(r);
let at = [
f64::from(pos[0]) + 0.5 + dx,
f64::from(pos[1]) + 0.4,
f64::from(pos[2]) + 0.5 + dz,
];
engine.create(&ParticleOptions::simple(T::Smoke), at, [0.0, 0.005, 0.0]);
}
}
#[cfg(test)]
+6
View File
@@ -28,6 +28,9 @@ pub struct BiomeInfo {
pub spawn_costs: HashMap<String, crate::mobs::spawn_selection::SpawnCost>,
/// The `gameplay/creature_world_gen_spawn_probability` attribute.
pub creature_probability: f32,
/// The `gameplay/increased_fire_burnout` attribute (jungles, swamps, peaks,
/// mushroom fields).
pub increased_fire_burnout: bool,
pub name: String,
pub temperature: f32,
pub downfall: f32,
@@ -128,6 +131,9 @@ impl Biomes {
attributes["minecraft:gameplay/creature_world_gen_spawn_probability"]
.as_f64()
.unwrap_or(0.1) as f32,
increased_fire_burnout: attributes["minecraft:gameplay/increased_fire_burnout"]
.as_bool()
.unwrap_or(false),
temperature,
downfall,
precipitation: v["has_precipitation"].as_bool().unwrap_or(true),
+12 -1
View File
@@ -166,12 +166,23 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 {
if d >= end { return 1.0; }
return (d - start) / (end - start);
}
// CRUMBLING_UV_BEGIN
fn crumbling_uv(uv: vec2<f32>, packed_origin: vec2<f32>, sprite_size: vec2<f32>, dimensions: vec2<u32>) -> vec2<f32> {
let size = vec2<f32>(dimensions);
// Undo stage_light's 16-bit quantization before adding local texels. Otherwise
// different stages can fall on opposite sides of a nearest-sampling boundary.
let origin = round(packed_origin * size);
let extent = max(round(sprite_size * size), vec2(1.0));
let local = min(floor(fract(uv) * extent), extent - vec2(1.0));
return (origin + local + vec2(0.5)) / size;
}
// CRUMBLING_UV_END
@fragment fn fs_entity(in: Out, @builtin(front_facing) front: bool) -> @location(0) vec4<f32> {
var uv = in.uv;
if in.overlay == 6u { uv.y = in.wrap.x + fract(in.uv.y) * in.wrap.y; }
if in.overlay == 11u || in.overlay == 12u {
// Each crack's stage sprite origin comes in its light bytes (breaking::stage_light).
uv = in.wrap + fract(in.uv) * globals.crumbling_sprite.zw;
uv = crumbling_uv(in.uv, in.wrap, globals.crumbling_sprite.zw, textureDimensions(atlas));
}
var color = textureSample(atlas, atlas_sampler, uv) * select(in.back_color, in.color, front);
if in.overlay == 9u || in.overlay == 10u {
+158 -53
View File
@@ -19,6 +19,7 @@ mod books;
mod bossbars;
mod breezes;
mod campfire;
mod campfire_douse;
mod cartography;
mod chat;
mod client_ambient;
@@ -556,6 +557,11 @@ struct GameLevel<'w> {
loot: Option<std::sync::Arc<horizon_world::loot::LootData>>,
registry: &'static horizon_world::registry::BlockRegistry,
rules: horizon_world::level::GameRules,
/// `Difficulty.getId()` (peaceful 0 .. hard 3).
difficulty: i32,
/// The feet of the players who keep fire spreading around them: the local
/// player and the LAN guests in this level, spectators aside.
fire_players: Vec<[f64; 3]>,
/// Block loot random sequences (`ServerLevel.getRandomSequence`).
rand_sequences: &'w mut horizon_client::random_sequences::RandomSequences,
pending: &'w mut spill::Pending,
@@ -565,6 +571,9 @@ struct GameLevel<'w> {
random_tick_sections: &'w mut horizon_client::random_tick_sections::RandomTickSections,
/// Players with each chest open (a trapped chest's signal).
lid_openers: &'w HashMap<(i32, i32, i32), i32>,
/// `Level.isClientSide`: a client's copy of the level (a guest of a LAN
/// world, a window on its server thread, a dedicated server's client).
client_side: bool,
}
struct PlayerCollision {
y: f64,
@@ -654,6 +663,9 @@ impl GameLevel<'_> {
}
}
impl LevelAccess for GameLevel<'_> {
fn is_client_side(&self) -> bool {
self.client_side
}
fn world_surface(&self, x: i32, z: i32) -> i32 {
self.world.world_surface(x, z, |s| self.facts.is_air(s))
}
@@ -719,6 +731,34 @@ impl LevelAccess for GameLevel<'_> {
fn game_rules(&self) -> horizon_world::level::GameRules {
self.rules
}
fn difficulty(&self) -> i32 {
self.difficulty
}
/// `ServerLevel.canSpreadFireAround`: a player (not a spectator) closer
/// than the `fire_spread_radius_around_player` rule to the block's corner
/// (`ChunkMap.anyPlayerCloseEnoughTo`); -1 spreads everywhere.
fn can_spread_fire_around(&self, pos: BlockPos) -> bool {
let radius = self.rules.fire_spread_radius_around_player;
radius == -1
|| self.fire_players.iter().any(|p| {
let d = [
p[0] - f64::from(pos.x),
p[1] - f64::from(pos.y),
p[2] - f64::from(pos.z),
];
d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < f64::from(radius) * f64::from(radius)
})
}
fn increased_fire_burnout(&self, pos: BlockPos) -> bool {
self.world
.chunks
.get(&(pos.x >> 4, pos.z >> 4))
.is_some_and(|chunk| {
self.biomes
.get(chunk.biome(pos.x, pos.y, pos.z))
.increased_fire_burnout
})
}
fn block_state(&self, pos: BlockPos) -> BlockStateId {
self.world.block(pos.x, pos.y, pos.z)
}
@@ -857,7 +897,16 @@ impl LevelAccess for GameLevel<'_> {
fn emit(&mut self, event: LevelEvent) {
match event {
// Block.dropResources draws its loot and spots right away.
LevelEvent::DropResources { pos, state } => self.drop_resources_now(pos, state),
// `popResource` only drops server-side (`!level.isClientSide`):
// a client's moveBlocks (a piston's block event) skips it.
LevelEvent::DropResources { pos, state } if !self.client_side => {
self.drop_resources_now(pos, state)
}
LevelEvent::DropResources { .. } => {}
// `ClientLevel.playSeededSound` plays only when the excluded
// player is this client's own: the block's `playSound(null, ...)`
// (a piston's move, a note) reaches it from the server instead.
LevelEvent::Sound { .. } if self.client_side => {}
// Block.popResource of the block's own item (tall flowers, flower beds).
LevelEvent::BlockEvent {
pos,
@@ -2469,6 +2518,19 @@ impl Game<'_> {
Dim::End => LevelDimension::End,
};
let rules = self.level_rules();
let fire_players: Vec<[f64; 3]> = self
.player
.iter()
.filter(|_| !spectator)
.map(|p| [p.position.x, p.position.y, p.position.z])
.chain(self.lan.iter().flat_map(|h| {
h.hub
.guests
.iter()
.filter(|g| h.hub.here(g) && !g.spectator())
.map(|g| g.position)
}))
.collect();
let blockers = Blockers {
mobs: &self.mobs,
armor_stands: &self.armor_stands,
@@ -2499,12 +2561,15 @@ impl Game<'_> {
loot: horizon_client::structure_blocks::loot_data(&self.options.resources),
registry: self.pack.assets.registry,
rules,
difficulty: i32::from(self.ui.difficulty),
fire_players,
rand_sequences: &mut self.rand_sequences,
pending: &mut self.pending,
spill: &mut self.spill,
tickets: self.tickets.levels(),
random_tick_sections: &mut self.random_tick_sections,
lid_openers: &self.lid_openers,
client_side: self.remote.is_some(),
};
let result = f(self.res.behaviours(), &mut level, &mut self.block_ticks);
self.flush_spill();
@@ -2566,14 +2631,15 @@ impl Game<'_> {
(p.position.z.floor() as i32) >> 4,
));
}
let sources = (self.options.dedicated.is_some() || !players.is_empty()).then(|| {
horizon_client::ticket_levels::Sources {
players,
forced: self.streaming.forced.iter().copied().collect(),
view_distance: self.settings.render_distance.clamp(2, 32),
simulation_distance: self.settings.simulation_distance.max(2),
}
});
let sources =
(!self.options.execution_role.is_client() || !players.is_empty()).then(|| {
horizon_client::ticket_levels::Sources {
players,
forced: self.streaming.forced.iter().copied().collect(),
view_distance: self.settings.render_distance.clamp(2, 32),
simulation_distance: self.settings.simulation_distance.max(2),
}
});
self.tickets.update(sources);
}
/// `ServerLevel.startTickingChunk`: a loaded chunk's saved ticks are
@@ -3568,6 +3634,10 @@ impl Game<'_> {
self.swing_arm();
return Ok(true);
}
if self.use_campfire_douse(hit.pos, held.as_ref())? {
self.swing_arm();
return Ok(true);
}
match self.use_respawn_anchor(hit.pos, held.as_ref())? {
respawn_anchor::AnchorUse::Charged => {
self.swing_arm();
@@ -4264,8 +4334,9 @@ impl Game<'_> {
if running {
self.world.game_time += 1;
if self.ui.rules.bool("advance_weather") {
self.world.weather.tick(&mut self.world.random);
self.world.weather.tick_timers(&mut self.world.random);
}
self.world.weather.tick_levels();
self.tick_weather_effects();
}
if self.ticks.is_multiple_of(6000) {
@@ -9671,8 +9742,9 @@ impl Game<'_> {
rain.extend(snow_vertices);
rain
}
/// Player.startSleepInBed: night or thunder, no monsters within 8 blocks;
/// the bed becomes the respawn point either way.
/// ServerPlayer.startSleepInBed: in reach, not obstructed, night or thunder,
/// and (outside creative) no monsters within 8 blocks; the bed becomes the
/// respawn point either way.
fn try_sleep(&mut self, pos: [i32; 3]) {
let Some(p) = self.player.as_ref() else {
return;
@@ -9687,22 +9759,40 @@ impl Game<'_> {
.state(state)
.map(|s| s.properties.clone())
.unwrap_or_default();
let head = if props.get("part").map(String::as_str) == Some("foot") {
let d = facing_offset(props.get("facing").map_or("north", String::as_str));
[pos[0] + d[0], pos[1], pos[2] + d[2]]
// The head and the foot: the block faces from the foot to the head.
let d = facing_offset(props.get("facing").map_or("north", String::as_str));
let (head, foot) = if props.get("part").map(String::as_str) == Some("foot") {
([pos[0] + d[0], pos[1], pos[2] + d[2]], pos)
} else {
pos
(pos, [pos[0] - d[0], pos[1], pos[2] - d[2]])
};
let dist = ((p.position.x - f64::from(head[0]) - 0.5).powi(2)
+ (p.position.z - f64::from(head[2]) - 0.5).powi(2))
.sqrt();
if dist > 3.0 {
// ServerPlayer.bedInRange / isReachableBedBlock: within 3 blocks
// sideways and 2 vertically of the head or the foot.
let reachable = |bed: [i32; 3]| {
(p.position.x - f64::from(bed[0]) - 0.5).abs() <= 3.0
&& (p.position.y - f64::from(bed[1])).abs() <= 2.0
&& (p.position.z - f64::from(bed[2]) - 0.5).abs() <= 3.0
};
if !reachable(head) && !reachable(foot) {
self.message = Some((
"You may not rest now; the bed is too far away".into(),
Instant::now(),
));
return;
}
// ServerPlayer.bedBlocked: Player.freeAt (not suffocating) for the
// blocks above the head and the foot, as `in_wall` reads suffocating.
let blocked = [head, foot].iter().any(|bed| {
let f = self
.res
.facts()
.get(self.world.block(bed[0], bed[1] + 1, bed[2]));
f.full_collision && f.solid_render
});
if blocked {
self.message = Some(("This bed is obstructed".into(), Instant::now()));
return;
}
// In reach (bedInRange), day or night: setRespawnPosition(
// RespawnConfig(the head, the player's yaw), not forced). It replaces
// an anchor or a spawnpoint; respawning checks the bed is still there
@@ -9732,13 +9822,15 @@ impl Game<'_> {
));
return;
}
let monsters = self.mobs.iter().any(|m| {
m.hostile()
&& m.alive()
&& (m.position.x - p.position.x).abs() < 8.0
&& (m.position.y - p.position.y).abs() < 5.0
&& (m.position.z - p.position.z).abs() < 8.0
});
// Creative players skip the monster check (`!this.isCreative()`).
let monsters = !self.creative
&& self.mobs.iter().any(|m| {
m.hostile()
&& m.alive()
&& (m.position.x - p.position.x).abs() < 8.0
&& (m.position.y - p.position.y).abs() < 5.0
&& (m.position.z - p.position.z).abs() < 8.0
});
if monsters {
self.message = Some((
"You may not rest now; there are monsters nearby".into(),
@@ -9788,14 +9880,20 @@ impl Game<'_> {
}
}
// ServerLevel.tick: once enough of the players have slept 100 ticks,
// skip to morning, clear the weather and wake everyone.
// skip to morning if `advance_time` is on, wake everyone, and
// resetWeatherCycle if `advance_weather` is on and it is raining.
if self.enough_slept() {
let t = self.world.day_time;
self.world.day_time = t + 24000 - t.rem_euclid(24000);
self.world.weather.raining = false;
self.world.weather.thundering = false;
self.world.weather.rain_time = 0;
self.world.weather.thunder_time = 0;
if self.ui.rules.bool("advance_time") {
let t = self.world.day_time;
self.world.day_time = t + 24000 - t.rem_euclid(24000);
}
// Level.isRaining: the rain level is above 0.2.
if self.ui.rules.bool("advance_weather") && self.world.weather.levels(1.0).0 > 0.2 {
self.world.weather.raining = false;
self.world.weather.thundering = false;
self.world.weather.rain_time = 0;
self.world.weather.thunder_time = 0;
}
if self.sleeping.is_some() {
self.wake_up();
}
@@ -11604,16 +11702,17 @@ impl ApplicationHandler for Game<'_> {
}
self.extras_mouse(button, pressed);
self.mod_mouse_key(button, pressed);
match self.settings.keys.translate_mouse(button) {
Some(Err(b)) => self.play_mouse(b, pressed)?,
Some(Ok(k)) if pressed => {
self.keys.insert(k);
self.key_pressed(k)?;
for mapped in self.settings.keys.translate_mouse_all(button) {
match mapped {
Err(b) => self.play_mouse(b, pressed)?,
Ok(k) if pressed => {
self.keys.insert(k);
self.key_pressed(k)?;
}
Ok(k) => {
self.keys.remove(&k);
}
}
Some(Ok(k)) => {
self.keys.remove(&k);
}
None => {}
}
}
Screen::Inventory | Screen::Creative
@@ -11861,18 +11960,24 @@ impl ApplicationHandler for Game<'_> {
{
self.smooth_camera = !self.smooth_camera;
}
// Key binds: act as the default key of the bound mapping.
let key = match self.settings.keys.translate(key) {
Some(Ok(k)) => k,
Some(Err(button)) => {
if self.screen == Screen::Playing && !event.repeat {
self.play_mouse(button, event.state == ElementState::Pressed)?;
// Key binds: act as the default key of every mapping bound
// to it (KeyMapping.set drives them all).
for mapped in self.settings.keys.translate_all(key) {
match mapped {
Ok(k) => {
self.mapped_key(
k,
event.state == ElementState::Pressed,
event.repeat,
)?;
}
Err(button) => {
if self.screen == Screen::Playing && !event.repeat {
self.play_mouse(button, event.state == ElementState::Pressed)?;
}
}
return Ok(());
}
None => return Ok(()),
};
self.mapped_key(key, event.state == ElementState::Pressed, event.repeat)?;
}
}
WindowEvent::RedrawRequested => {
self.observe_fullscreen();
@@ -0,0 +1,53 @@
//! `CampfireBlock.useItemOn`: an item in `#minecraft:douses_campfires` (the
//! shovels) put on a lit campfire puts it out.
use super::Game;
use horizon_client::{Result, animate_tick::make_campfire_smoke, items::ItemStack};
impl Game<'_> {
/// `CampfireBlock.useItemOn` with `held` in the hand that acts, the block
/// at `pos` clicked: true when it doused a lit campfire (SUCCESS).
pub(super) fn use_campfire_douse(
&mut self,
pos: [i32; 3],
held: Option<&ItemStack>,
) -> Result<bool> {
let Some(tool) = held.filter(|s| {
self.res
.items()
.item_tags
.get("minecraft:douses_campfires")
.is_some_and(|members| members.contains(&*s.item))
}) else {
return Ok(false);
};
let registry = self.pack.assets.registry;
let Some(mut state) = registry
.state(self.world.block(pos[0], pos[1], pos[2]))
.filter(|s| matches!(&*s.name, "minecraft:campfire" | "minecraft:soul_campfire"))
.filter(|s| s.properties.get("lit").map(String::as_str) == Some("true"))
.cloned()
else {
return Ok(false);
};
// Level event 1009 (SOUND_EXTINGUISH_FIRE) goes to every player.
self.level_event_at(1009, pos, 0);
// CampfireBlock.douse: the acting client's own smoke (twenty puffs),
// then the block change game event from the player.
if self.lan_acting.is_none() {
let signal = state.properties.get("signal_fire").map(String::as_str) == Some("true");
for _ in 0..20 {
make_campfire_smoke(&mut self.particles, pos, signal, true);
}
}
self.post_block_game_event("minecraft:block_change", pos, self.sculk_actor(), None);
state.properties.insert("lit".into(), "false".into());
if let Ok(unlit) = registry.resolve(&state) {
self.level_set(pos, unlit)?;
}
let used = tool.clone();
self.damage_held(1);
// ServerPlayerGameMode.useItemOn: the action was consumed.
self.trigger_block("minecraft:item_used_on_block", pos, &used);
Ok(true)
}
}
+1
View File
@@ -782,6 +782,7 @@ impl Game<'_> {
max_snow_accumulation_height: r.int("max_snow_accumulation_height"),
spawn_mobs: r.bool("spawn_mobs"),
spawn_monsters: r.bool("spawn_monsters"),
fire_spread_radius_around_player: r.int("fire_spread_radius_around_player"),
}
}
/// Apply rules mirrored in other state (natural regeneration, difficulty).
+5 -1
View File
@@ -1547,7 +1547,10 @@ impl Game<'_> {
}
}
self.hurt_armor(amount);
self.thorns(from);
// The thorns hurt the entity that caused the hit, if there is one.
if let Some(a) = attacker.or(owner) {
self.thorns(a);
}
}
if raised {
self.after_block(outcome, amount, attacker, projectile);
@@ -3302,6 +3305,7 @@ fn to_loot(stack: &ItemStack) -> horizon_world::loot::LootStack {
map: false,
exploration: None,
ominous_amplifier: None,
stew_effects: Vec::new(),
}
}
/// A generated loot stack as a Horizon item stack.
@@ -725,6 +725,11 @@ impl Game<'_> {
match self.world.block_entities.get_mut(&p) {
Some(BlockEntity::Jukebox(j)) => j.record = stack,
Some(BlockEntity::Lectern(l)) => l.book = stack,
Some(BlockEntity::Campfire(c)) => {
if let Some(cell) = c.items.get_mut(slot) {
*cell = stack;
}
}
Some(e) => {
if let Some(cell) = e.slots_mut().get_mut(slot) {
*cell = stack;
+17 -7
View File
@@ -1687,10 +1687,12 @@ impl Game<'_> {
.play("minecraft:entity.ender_dragon.growl", Some(at), 2.5, pitch);
}
}
// checkCrystals: heal 1 every 10 ticks from the nearest crystal within 32.
// checkCrystals: heal 1 every 10 ticks from the nearest crystal, found
// among those touching the dragon's box grown by 32.
let d = self.dragon.as_mut().expect("dragon");
if d.nearest_crystal.is_some() && d.ticks % 10 == 0 && d.health < MAX_HEALTH {
d.health += 1.0;
// LivingEntity.setHealth clamps to the maximum.
d.health = (d.health + 1.0).min(MAX_HEALTH);
}
if d.random.next_int_bound(10).unwrap_or(1) == 0 {
let p = d.position;
@@ -3173,16 +3175,24 @@ impl Game<'_> {
let _ = self.activate_exit_portal();
self.fight.dirty = true;
}
/// `EnderDragon.checkCrystals`' search: the nearest crystal within 32
/// blocks on each axis.
/// `EnderDragon.checkCrystals`' search: the nearest crystal whose box
/// meets the dragon's box grown by 32.
fn nearest_crystal_to(&self, p: Vec3) -> Option<usize> {
// The dragon's 16 by 8 box.
let reach = Aabb::new(
Vec3::new(p.x - 8.0, p.y, p.z - 8.0),
Vec3::new(p.x + 8.0, p.y + 8.0, p.z + 8.0),
)
.inflate(Vec3::new(32.0, 32.0, 32.0));
self.crystals
.iter()
.enumerate()
.filter(|(_, c)| {
(c.position.x - p.x).abs() <= 32.0
&& (c.position.y - p.y).abs() <= 32.0
&& (c.position.z - p.z).abs() <= 32.0
// An end crystal's 2 by 2 box.
reach.intersects(Aabb::new(
Vec3::new(c.position.x - 1.0, c.position.y, c.position.z - 1.0),
Vec3::new(c.position.x + 1.0, c.position.y + 2.0, c.position.z + 1.0),
))
})
.min_by(|a, b| {
let da = (a.1.position.x - p.x).powi(2)
@@ -255,23 +255,26 @@ impl Game<'_> {
let _ = self.wind_burst(feet, radius, knockback, false, false);
}
}
/// Thorns on worn armor when a mob at `from` hits the player.
pub(super) fn thorns(&mut self, from: [f64; 3]) {
let attacker = self
.mobs
.iter()
.enumerate()
.filter(|(_, m)| m.alive())
.min_by(|a, b| {
let d = |m: &horizon_client::mobs::Mob| {
(m.position.x - from[0]).powi(2)
+ (m.position.y - from[1]).powi(2)
+ (m.position.z - from[2]).powi(2)
};
d(a.1).total_cmp(&d(b.1))
})
.map(|(i, _)| i);
let Some(attacker) = attacker else { return };
/// Thorns on worn armor when the mob `attacker` hits the player: the
/// `affected: attacker` effect of `Enchantment.doPostAttack` hurts the
/// entity that caused the hit.
pub(super) fn thorns(&mut self, attacker: u32) {
let Some(index) = self.mobs.iter().position(|m| m.id == attacker && m.alive()) else {
return;
};
for damage in self.thorns_damage() {
let m = &mut self.mobs[index];
m.hurt(damage, None, &mut self.world.random);
let center = [m.position.x, m.position.y, m.position.z];
self.audio
.play("minecraft:enchant.thorns.hit", Some(center), 1.0, 1.0);
}
}
/// The victim's side of thorns: for each worn piece whose chance comes up,
/// the damage to deal the attacker (`DamageEntity` min 1, max 5) and the
/// piece's wear (`ChangeItemDamage` 2).
pub(super) fn thorns_damage(&mut self) -> Vec<f32> {
let mut hits = Vec::new();
for slot in 0..4 {
let Some(stack) = self.armor[slot].clone() else {
continue;
@@ -299,15 +302,7 @@ impl Game<'_> {
if !ok {
continue;
}
// DamageEntity(min 1, max 5) and ChangeItemDamage(2).
let damage = 1.0 + self.world.random.next_float() * 4.0;
let center = {
let m = &mut self.mobs[attacker];
m.hurt(damage, None, &mut self.world.random);
[m.position.x, m.position.y, m.position.z]
};
self.audio
.play("minecraft:enchant.thorns.hit", Some(center), 1.0, 1.0);
hits.push(1.0 + self.world.random.next_float() * 4.0);
if let Some(s) = self.armor[slot].as_mut() {
s.damage += 2;
if self
@@ -320,6 +315,7 @@ impl Game<'_> {
}
}
}
hits
}
/// `ExperienceOrb.repairPlayerItems`: returns the experience left over.
pub(super) fn mending(&mut self, amount: u32) -> u32 {
+30 -11
View File
@@ -972,6 +972,13 @@ impl Game<'_> {
for m in &mut self.mobs {
m.needs_sync = false;
}
// `runBlockEvents`' broadcast precedes the tick's block changes
// (`ChunkHolder.broadcastChanges` in `tick_level` below): the
// guest re-runs a piston's `triggerEvent` while its level still
// has the blocks as they were before the move.
for (pos, b0, b1, state) in std::mem::take(&mut self.lan_block_events) {
host.hub.block_event(pos, b0, b1, state);
}
let entities = states.as_slice();
let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]);
let events = {
@@ -1208,17 +1215,29 @@ impl Game<'_> {
return;
}
for e in events {
if let horizon_world::level::LevelEvent::LevelEvent { id, pos, data } = e {
// The acting guest does not predict the egg's teleport
// particles, bone meal's growth, or anvil result sounds
// (these levelEvent calls name no excluded player).
let except = if matches!(*id, 2015 | 1505 | 1029 | 1030) {
None
} else {
self.lan_acting
};
self.lan_events
.push((*id, [pos.x, pos.y, pos.z], *data, except));
match e {
horizon_world::level::LevelEvent::LevelEvent { id, pos, data } => {
// The acting guest does not predict the egg's teleport
// particles, bone meal's growth, or anvil result sounds
// (these levelEvent calls name no excluded player).
let except = if matches!(*id, 2015 | 1505 | 1029 | 1030) {
None
} else {
self.lan_acting
};
self.lan_events
.push((*id, [pos.x, pos.y, pos.z], *data, except));
}
// `ServerLevel.runBlockEvents` broadcasts a handled block
// event (`ClientboundBlockEventPacket`): the guest re-runs
// the block's `triggerEvent` — a piston's `moveBlocks` is
// what animates the move there. `state` is the block the
// event named, read before it ran (the packet's `block`).
horizon_world::level::LevelEvent::BlockEntityEvent { pos, state, a, b } => {
self.lan_block_events
.push(([pos.x, pos.y, pos.z], *a, *b, state.0));
}
_ => {}
}
}
}
+19 -6
View File
@@ -245,14 +245,18 @@ impl Game<'_> {
if hurt && strength > 0.0 {
g.knock_back_player(f64::from(strength), xd, zd);
}
hurt
// The victim's thorns, dealt to the attacker below.
let thorns = if hurt { g.thorns_damage() } else { Vec::new() };
(hurt, thorns)
};
let hurt = self.ui.rules.bool("pvp")
&& harm
&& match victim {
let (hurt, thorns) = if self.ui.rules.bool("pvp") && harm {
match victim {
Victim::Host => land(self),
Victim::Guest(conn) => self.guest_struck_by(host, conn, land).unwrap_or(false),
};
Victim::Guest(conn) => self.guest_struck_by(host, conn, land).unwrap_or_default(),
}
} else {
Default::default()
};
if hurt && s.crit {
let target = match victim {
Victim::Host => self.player.as_ref().map(|p| (host.host_entity, p)),
@@ -272,6 +276,15 @@ impl Game<'_> {
);
}
}
// `Enchantment.doPostAttack`: thorns hurt the attacking player.
for damage in thorns {
match s.attacker {
None => self.hurt_player_by("minecraft:thorns", damage),
Some(conn) => {
self.guest_hit_by(host, conn, |g| g.hurt_player_by("minecraft:thorns", damage));
}
}
}
let sound = match (hurt, s.crit, s.scale > 0.9) {
(false, ..) => "minecraft:entity.player.attack.nodamage",
(true, true, _) => "minecraft:entity.player.attack.crit",
+16 -6
View File
@@ -3,8 +3,8 @@
//! The game's tick code reads one level: the one in place, held in `Game`'s
//! own fields (the world, its streaming and save, block ticks, entities).
//! A server (the dedicated server and single player's server thread) keeps
//! the other dimensions' levels here and ticks each one that has players by
//! swapping it into place (`enter_level`), the way `as_guest` swaps a player
//! the other dimensions' levels here and ticks each one with players or forced
//! chunks by swapping it into place (`enter_level`), the way `as_guest` swaps a player
//! in, so the tick code runs unchanged, one level at a time. The in-frame
//! game holds one level, which follows its player (`enter_dimension`).
//!
@@ -293,8 +293,8 @@ impl Game<'_> {
}
/// One server tick (`MinecraftServer.tickServer`): each level with
/// players in turn (`tickChildren`), its chunks streamed and loaded and
/// its world ticked. The first pass reads the network and runs the
/// players or forced chunks in turn (`tickChildren`), its chunks streamed
/// and loaded and its world ticked. The first pass reads the network and runs the
/// tick's shared parts (the clock, the weather, functions, the autosave);
/// the next ones only their level. While `paused`, only the connections
/// run.
@@ -396,7 +396,7 @@ impl Game<'_> {
/// The levels this server tick runs, in `MinecraftServer.levels` order
/// (the Overworld, the Nether, the End): every level with a player in
/// it or a `/pregen` task, or the Overworld while nobody is online.
/// it, forced chunks or a `/pregen` task, or the Overworld while idle.
pub(super) fn levels_to_tick(&self) -> Vec<Dim> {
let guests = self
.lan
@@ -405,7 +405,17 @@ impl Game<'_> {
let mut dims: Vec<Dim> = [Dim::Overworld, Dim::Nether, Dim::End]
.into_iter()
.filter(|d| {
guests.iter().any(|g| g.dimension == d.id()) || self.pregen_level() == Some(*d)
let forced = if *d == self.dim {
!self.streaming.forced.is_empty()
} else {
self.levels
.parked
.get(d)
.is_some_and(|p| !p.streaming.forced.is_empty())
};
guests.iter().any(|g| g.dimension == d.id())
|| forced
|| self.pregen_level() == Some(*d)
})
.collect();
if dims.is_empty() {
+13 -17
View File
@@ -162,11 +162,9 @@ impl Game<'_> {
converted: Vec::new(),
});
}
/// `spawnFire`: fire at the strike point and `extra` random neighbours.
/// `spawnFire`: fire at the strike point and `extra` random neighbours,
/// wherever `BaseFireBlock.getState` fire can survive.
fn bolt_fire(&mut self, at: [f64; 3], extra: i32) {
if self.ui.difficulty < 2 {
return;
}
let base = [
at[0].floor() as i32,
at[1].floor() as i32,
@@ -183,18 +181,13 @@ impl Game<'_> {
if !self.res.facts().is_air(state) {
continue;
}
// BaseFireBlock.getState: soul fire on soul soil and sand.
let below = self.res.facts().get(self.world.block(p[0], p[1] - 1, p[2]));
let name = if matches!(&*below.name, "minecraft:soul_soil" | "minecraft:soul_sand") {
"minecraft:soul_fire"
} else {
"minecraft:fire"
};
// FireBlock.canSurvive: a sturdy floor (flammable neighbours aside).
if below.sturdy_full >> 1 & 1 == 0 {
continue;
}
if let Some(fire) = self.pack.assets.registry.default_state(name) {
// BaseFireBlock.getState and FireBlock/SoulFireBlock.canSurvive.
let at = BlockPos::new(p[0], p[1], p[2]);
let fire = self.with_level(|b, level, ticks| {
let fire = b.fire_state_for(level, ticks, at);
b.can_survive(level, ticks, at, fire).then_some(fire)
});
if let Some(fire) = fire {
let _ = self.level_set(p, fire);
}
}
@@ -219,7 +212,10 @@ impl Game<'_> {
pitch,
);
if !b.visual_only {
self.bolt_fire(b.at, 4);
// Only Normal and Hard start fires with the strike itself.
if self.ui.difficulty >= 2 {
self.bolt_fire(b.at, 4);
}
self.strike_rod(b.at);
}
}
+4 -2
View File
@@ -159,8 +159,10 @@ impl Containers<'_> {
});
}
let entity = self.world.block_entities.get(&pos)?;
// A beehive keeps bees, not items: it is no `Container`.
if matches!(entity, BlockEntity::Beehive(_)) {
// A beehive keeps bees, not items, and a campfire cooks its own: neither
// is a `Container` (HopperBlockEntity.getContainerAt), so a dropper drops
// in front of them and a hopper leaves them alone.
if matches!(entity, BlockEntity::Beehive(_) | BlockEntity::Campfire(_)) {
return None;
}
let kind = match (entity, name) {
+29 -12
View File
@@ -1697,19 +1697,30 @@ impl Game<'_> {
}
}
C::BlockChangedAck(p) => self.end_predictions(p.sequence),
// ClientLevel.blockEvent: BlockEntity.triggerEvent (chest lids,
// shulker boxes, bells) when the block is still the one it names.
// Level.blockEvent on the client level: the block's triggerEvent
// runs on the client's copy of whatever is at pos (a piston's
// moveBlocks builds the moving block entities it animates, a note
// block plays); what it doesn't handle reaches the client copy of
// the block entity (chest lids, shulker boxes).
C::BlockEvent(p) => {
let state = self.world.block(p.pos[0], p.pos[1], p.pos[2]);
let block = &self.res.facts().get(state).name;
let named = self.remote.as_ref().and_then(|r| {
r.builtin
.get("minecraft:block")?
.name(p.block)
.map(str::to_owned)
let pos = horizon_core::position::BlockPos::new(p.pos[0], p.pos[1], p.pos[2]);
let triggered = self.with_level(|b, level, ticks| {
b.client_block_event(level, ticks, pos, i32::from(p.b0), i32::from(p.b1))
});
if named.as_deref() == Some(&**block) {
self.block_entity_event(p.pos, i32::from(p.b0), i32::from(p.b1));
self.sync_moving_pistons();
self.process_level_events()?;
if !triggered {
let state = self.world.block(p.pos[0], p.pos[1], p.pos[2]);
let block = &self.res.facts().get(state).name;
let named = self.remote.as_ref().and_then(|r| {
r.builtin
.get("minecraft:block")?
.name(p.block)
.map(str::to_owned)
});
if named.as_deref() == Some(&**block) {
self.block_entity_event(p.pos, i32::from(p.b0), i32::from(p.b1));
}
}
}
// ClientLevel.levelEvent: LevelEventHandler, as this client's own
@@ -3162,8 +3173,14 @@ impl Game<'_> {
self.border.tick();
self.player_border();
self.tick_remote_entities(running);
// ClientLevel.tickBlockEntities: chest lids, shulker boxes, bells.
// ClientLevel.tickBlockEntities: chest lids, shulker boxes, bells,
// and the moving pistons a block event's client-side moveBlocks made
// (their progress advances between the server's block updates).
self.tick_block_entity_anims();
self.with_level(|b, level, ticks| {
b.client_tick_block_entities(level, ticks);
});
self.sync_moving_pistons();
self.tick_hand();
self.tick_particles();
self.tick_client_ambient();
+2
View File
@@ -32,6 +32,8 @@ fn entity_shader() -> String {
crate::overlay::wgsl_constants() + include_str!("entity.wgsl")
}
#[cfg(test)]
mod crumbling_tests;
mod entity_batch;
mod weather;
use entity_batch::EntityBatch;
@@ -0,0 +1,191 @@
use wgpu::util::DeviceExt;
/// Sample the production WGSL with the production nearest/no-mipmap atlas sampler.
#[test]
#[ignore = "requires a Vulkan/Metal/DX12 adapter"]
fn crack_samples_stay_aligned_between_stages() {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
let adapter =
pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default()))
.unwrap();
eprintln!("crack sampling adapter: {:?}", adapter.get_info());
let (device, queue) =
pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).unwrap();
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct Case {
uv: [f32; 2],
stage: u32,
extent: u32,
}
let mut cases = Vec::new();
let mut expected = Vec::<[u32; 2]>::new();
// Include exact texel boundaries, their neighbours, negative projected UVs,
// wrapping and the far sprite edge. Origins straddle the packing error's sign change.
for extent in [16, 32] {
for x in [32, 2080, 4064] {
for y in [0, 32] {
for i in -32..=32 {
for delta in [-0.0001, 0.0, 0.0001] {
let uv = [i as f32 / 16.0 + delta, 0.5 - delta];
cases.push(Case {
uv,
stage: crate::breaking::stage_light([
x as f32 / 4096.0,
y as f32 / 64.0,
]),
extent,
});
expected.push(uv.map(|v| {
(((v - v.floor()) * extent as f32).floor() as u32).min(extent - 1)
}));
}
}
}
}
}
let math = include_str!("../entity.wgsl")
.split("// CRUMBLING_UV_BEGIN")
.nth(1)
.unwrap()
.split("// CRUMBLING_UV_END")
.next()
.unwrap();
let source = format!(
"{math}\n{}",
r#"
struct Case { uv: vec2<f32>, stage: u32, extent: u32 }
@group(0) @binding(0) var<storage, read> cases: array<Case>;
@group(0) @binding(1) var<storage, read_write> results: array<vec4<u32>>;
@group(0) @binding(2) var atlas: texture_2d<f32>;
@group(0) @binding(3) var atlas_sampler: sampler;
@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id: vec3<u32>) {
if id.x >= arrayLength(&cases) { return; }
let c = cases[id.x];
let origin = vec2(f32(c.stage & 65535u), f32(c.stage >> 16u)) / 65535.0;
let dimensions = textureDimensions(atlas);
let uv = crumbling_uv(c.uv, origin, vec2(f32(c.extent)) / vec2<f32>(dimensions), dimensions);
// Keep the old addressing as a control: the fixture must reproduce its stage jitter.
let old_uv = origin + fract(c.uv) * vec2(f32(c.extent)) / vec2<f32>(dimensions);
results[id.x] = vec4<u32>(
vec2<u32>(round(textureSampleLevel(atlas, atlas_sampler, uv, 0.0).rg * 255.0)),
vec2<u32>(round(textureSampleLevel(atlas, atlas_sampler, old_uv, 0.0).rg * 255.0)));
}"#
);
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Crack sampling regression"),
source: wgpu::ShaderSource::Wgsl(source.into()),
});
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: None,
layout: None,
module: &shader,
entry_point: Some("main"),
compilation_options: Default::default(),
cache: None,
});
// Every sprite repeats the same coordinate pattern, so moving a stage's
// atlas origin must leave every sampled local texel unchanged.
let pixels: Vec<u8> = (0..64)
.flat_map(|y| (0..4096).flat_map(move |x| [(x % 32) as u8, (y % 32) as u8, 0, 255]))
.collect();
let atlas = device.create_texture_with_data(
&queue,
&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d {
width: 4096,
height: 64,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
},
wgpu::util::TextureDataOrder::LayerMajor,
&pixels,
);
let view = atlas.create_view(&Default::default());
let sampler = device.create_sampler(&wgpu::SamplerDescriptor::default());
let input = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: None,
contents: bytemuck::cast_slice(&cases),
usage: wgpu::BufferUsages::STORAGE,
});
let size = (expected.len() * 16) as u64;
let output = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size,
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
mapped_at_creation: false,
});
let readback = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size,
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &pipeline.get_bind_group_layout(0),
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: input.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: output.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::TextureView(&view),
},
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::Sampler(&sampler),
},
],
});
let mut encoder = device.create_command_encoder(&Default::default());
{
let mut pass = encoder.begin_compute_pass(&Default::default());
pass.set_pipeline(&pipeline);
pass.set_bind_group(0, &group, &[]);
pass.dispatch_workgroups((cases.len() as u32).div_ceil(64), 1, 1);
}
encoder.copy_buffer_to_buffer(&output, 0, &readback, 0, size);
queue.submit([encoder.finish()]);
let (tx, rx) = std::sync::mpsc::channel();
readback.map_async(wgpu::MapMode::Read, .., move |r| tx.send(r).unwrap());
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
rx.recv().unwrap().unwrap();
let mapped = readback.get_mapped_range(..).unwrap();
let actual: &[[u32; 4]] = bytemuck::cast_slice(&mapped);
for (i, (actual, expected)) in actual.iter().zip(&expected).enumerate() {
assert_eq!(
&actual[..2],
expected,
"case {i}, uv={:?}, stage={}, extent={}",
cases[i].uv,
cases[i].stage,
cases[i].extent
);
}
let old_mismatches = actual
.iter()
.zip(&expected)
.filter(|(a, e)| &a[2..] != e.as_slice())
.count();
assert!(
old_mismatches > 0,
"fixture must detect the original sampling bug"
);
eprintln!(
"{} crack texture samples matched; old addressing mismatched {old_mismatches}",
cases.len()
);
}
+64 -19
View File
@@ -275,6 +275,20 @@ impl Default for KeyBinds {
}
}
}
/// Each default key once, in order: two mappings that share a default key
/// (Advancements and the debug profiler both on L) are one press of it, not
/// two (the second would close the screen the first opened). Vanilla clicks
/// both mappings, but the profiler one only acts with F3 held.
fn distinct<T: PartialEq>(keys: Vec<T>) -> Vec<T> {
let mut out = Vec::with_capacity(keys.len());
for k in keys {
if !out.contains(&k) {
out.push(k);
}
}
out
}
impl KeyBinds {
pub fn get(&self, name: &str) -> &str {
self.keys
@@ -320,49 +334,80 @@ impl KeyBinds {
}
/// The mapping a physical input triggers (first in list order).
pub fn mapping_for(&self, key: &str) -> Option<&'static str> {
MAPPINGS.iter().map(|m| m.0).find(|n| self.get(n) == key)
self.mappings_for(key).next()
}
/// Every mapping a physical input triggers, in list order: like
/// `KeyMapping.set`/`click`, one key drives all the mappings bound to it.
pub fn mappings_for<'a>(&'a self, key: &'a str) -> impl Iterator<Item = &'static str> + 'a {
MAPPINGS
.iter()
.map(|m| m.0)
.filter(move |n| self.get(n) == key)
}
/// Translate a physical key into the default key of the mapping it is
/// bound to, so game code written against vanilla defaults follows the
/// player's bindings. `None` means the key now does nothing; mouse
/// mappings bound to keys come back as `Err(button)`.
/// mappings bound to keys come back as `Err(button)`. The first of
/// [`KeyBinds::translate_all`].
pub fn translate(&self, key: KeyCode) -> Option<Result<KeyCode, MouseButton>> {
self.translate_all(key).into_iter().next()
}
/// The default keys of every mapping `key` is bound to (empty when it
/// now does nothing), so a key bound to two mappings (forward and
/// sprint) drives both, as `KeyMapping.set` does.
pub fn translate_all(&self, key: KeyCode) -> Vec<Result<KeyCode, MouseButton>> {
let Some(name) = key_name(key) else {
return Some(Ok(key));
return vec![Ok(key)];
};
if let Some(mapping) = self.mapping_for(name) {
let default = Self::default_of(mapping);
if let Some(code) = key_code(default) {
return Some(Ok(code));
}
return mouse_button(default).map(Err);
let bound: Vec<_> = self
.mappings_for(name)
.filter_map(|mapping| {
let default = Self::default_of(mapping);
match key_code(default) {
Some(code) => Some(Ok(code)),
None => mouse_button(default).map(Err),
}
})
.collect();
if !bound.is_empty() {
return distinct(bound);
}
// An unbound key whose default meaning was moved elsewhere is inert.
if MAPPINGS
.iter()
.any(|(n, d, _)| *d == name && !self.is_default(n))
{
return None;
return Vec::new();
}
Some(Ok(key))
vec![Ok(key)]
}
/// Translate a mouse button the same way (keys bound to mouse buttons).
pub fn translate_mouse(&self, button: MouseButton) -> Option<Result<KeyCode, MouseButton>> {
self.translate_mouse_all(button).into_iter().next()
}
/// [`KeyBinds::translate_all`] for a mouse button.
pub fn translate_mouse_all(&self, button: MouseButton) -> Vec<Result<KeyCode, MouseButton>> {
let name = mouse_name(button);
if let Some(mapping) = self.mapping_for(&name) {
let default = Self::default_of(mapping);
if let Some(b) = mouse_button(default) {
return Some(Err(b));
}
return key_code(default).map(Ok);
let bound: Vec<_> = self
.mappings_for(&name)
.filter_map(|mapping| {
let default = Self::default_of(mapping);
match mouse_button(default) {
Some(b) => Some(Err(b)),
None => key_code(default).map(Ok),
}
})
.collect();
if !bound.is_empty() {
return distinct(bound);
}
if MAPPINGS
.iter()
.any(|(n, d, _)| *d == name && !self.is_default(n))
{
return None;
return Vec::new();
}
Some(Err(button))
vec![Err(button)]
}
/// `AbstractContainerScreen.checkHotbarMouseClicked`: off hand, then hotbar.
pub fn container_mouse_key(&self, button: MouseButton, creative: bool) -> Option<KeyCode> {
+3
View File
@@ -709,6 +709,9 @@ pub struct Extra {
/// A copper golem's `openedChestPos`.
pub opened_chest: Option<[i32; 3]>,
pub point: Option<[f64; 3]>,
/// `NEAREST_REPELLENT`: the nearest repelling block a hoglin or piglin
/// sensed, looked up every 20 ticks.
pub repellent: Option<[i32; 3]>,
pub vector: [f64; 3],
/// Active status effects: (effect id, ticks left, amplifier).
pub effects: Vec<(&'static str, i32, i32)>,
+14
View File
@@ -1242,6 +1242,20 @@ pub fn walk_target_value(m: &Mob, w: &MobWorld, p: [i32; 3]) -> f32 {
if m.species() == Species::Strider {
return super::strider::walk_target_value(m, w, p);
}
// Hoglin.getWalkTargetValue: nowhere near a repellent, crimson nylium best.
if m.species() == Species::Hoglin {
let near = m.extra.repellent.is_some_and(|r| {
let d = |i: usize| i64::from(r[i] - p[i]);
d(0) * d(0) + d(1) * d(1) + d(2) * d(2) < 64
});
return if near {
-1.0
} else if w.block_name(p[0], p[1] - 1, p[2]) == "minecraft:crimson_nylium" {
10.0
} else {
0.0
};
}
// Bee.getWalkTargetValue: any air block.
if m.species() == Species::Bee {
return if w.facts.is_air(w.world.block(p[0], p[1], p[2])) {
+1
View File
@@ -304,6 +304,7 @@ fn loot_stack(item: &str, count: i32) -> LootStack {
map: false,
exploration: None,
ominous_amplifier: None,
stew_effects: Vec::new(),
}
}
/// `Mob.dropChances.byEquipment(slot)`: the recorded chance, or the one the
+83 -3
View File
@@ -9,7 +9,7 @@ use super::{
NearestTarget, Prey, RandomLookAround, Stroll, goal_clone,
},
};
use horizon_core::geometry::trig::Mth;
use horizon_core::geometry::{Vec3, trig::Mth};
use horizon_core::random::RandomSource;
use std::f32::consts::PI;
@@ -83,12 +83,16 @@ pub fn register_hoglin(m: &mut Mob) {
g.add(1, BabyPanic(super::goals::Panic::new(1.25)));
g.add(2, MeleeAttack::new(1.0, true));
g.add(3, super::goals::Breed::new(1.0));
g.add(3, HoglinAvoidRepellent);
g.add(4, super::goals::FollowParent::new(1.1));
g.add(5, Stroll::avoiding_water(0.4));
g.add(6, LookAtPlayer::new(8.0));
m.ai.targets.add(1, HurtByTarget::new().alert());
m.ai.targets
.add(2, NearestTarget::player(true).when(|m, _| !m.is_baby()));
// `HoglinAi.findNearestValidAttackTarget`: nothing while pacified.
m.ai.targets.add(
2,
NearestTarget::player(true).when(|m, _| !m.is_baby() && m.extra.ints[0] <= 0),
);
}
pub fn register_zoglin(m: &mut Mob) {
let g = &mut m.ai.goals;
@@ -108,6 +112,49 @@ pub fn register_zoglin(m: &mut Mob) {
.interval(10),
);
}
/// `SetWalkTargetAwayFrom.pos(NEAREST_REPELLENT, 1.0, 8, true)` of the hoglin's
/// idle activity: closer than 8 blocks to a repellent, walk away from it.
#[derive(Clone, Debug)]
struct HoglinAvoidRepellent;
impl Goal for HoglinAvoidRepellent {
goal_clone!();
fn flags(&self) -> u8 {
MOVE
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
let Some(r) = m.extra.repellent else {
return false;
};
// Vec3.atBottomCenterOf.
let avoid = [
f64::from(r[0]) + 0.5,
f64::from(r[1]),
f64::from(r[2]) + 0.5,
];
if m.distance_sqr(Vec3::new(avoid[0], avoid[1], avoid[2])) >= 64.0 {
return false;
}
for _ in 0..10 {
if let Some(p) = m.land_random_pos_away(cx.w, 16, 7, avoid) {
let at = [
p[0].floor() as i32,
p[1].floor() as i32,
p[2].floor() as i32,
];
m.ai.pending_path = m.create_path_to(cx.w, at, 0);
return m.ai.pending_path.is_some();
}
}
false
}
fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool {
!m.ai.nav.is_done()
}
fn start(&mut self, m: &mut Mob, _: &mut Cx) {
let path = m.ai.pending_path.take();
m.nav_move_to_path(path, 1.0);
}
}
/// Baby hoglins flee what hurts them; adults stand their ground.
#[derive(Clone, Debug)]
struct BabyPanic(super::goals::Panic);
@@ -165,12 +212,45 @@ impl Goal for GoToWantedItem {
m.extra.point = None;
}
}
/// `HoglinSpecificSensor.findNearestRepellent`: the nearest `#hoglin_repellents`
/// block within 8 blocks sideways and 4 up or down.
fn find_hoglin_repellent(m: &Mob, w: &MobWorld) -> Option<[i32; 3]> {
let tag = w.block_tags.get("minecraft:hoglin_repellents")?;
let at = [
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
];
w.nearest_block(at, 8, 4, |_, name| tag.contains(name))
}
/// The hoglin's repellent memories: the sensor (every 20 ticks), the end of
/// `PACIFIED` (`ints[0]`), a hit ending it (`HoglinAi.wasHurtBy`, `ints[1]`
/// remembers the hit seen) and `BecomePassiveIfMemoryPresent(NEAREST_REPELLENT, 200)`.
fn hoglin_repellent(m: &mut Mob, w: &MobWorld) {
if m.extra.ints[0] > 0 {
m.extra.ints[0] -= 1;
}
if m.ai.last_hurt_by.is_some() && m.ai.last_hurt_by_time != m.extra.ints[1] {
m.extra.ints[1] = m.ai.last_hurt_by_time;
m.extra.ints[0] = 0;
}
if m.age.wrapping_add(m.id).is_multiple_of(20) {
m.extra.repellent = find_hoglin_repellent(m, w);
}
if m.extra.ints[0] <= 0 && m.extra.repellent.is_some() {
m.extra.ints[0] = 200;
m.ai.target = None;
}
}
/// Per-tick piglin and hoglin state: admiring, anger, zombification and the
/// hoglin attack animation. Returns a conversion when it happens.
pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
if m.extra.anim_ticks > 0 {
m.extra.anim_ticks -= 1;
}
if m.species() == Species::Hoglin && m.alive() {
hoglin_repellent(m, w);
}
if m.extra.anger > 0 {
m.extra.anger -= 1;
if m.extra.anger == 0 && m.ai.target == Some(Who::Player) && !hostile_to_player(m, w) {
+29
View File
@@ -65,6 +65,35 @@ impl MobWorld<'_> {
pub fn has_tag(&self, tag: &str, block: &str) -> bool {
self.block_tags.get(tag).is_some_and(|s| s.contains(block))
}
/// `findBlocksInBoxByManhattanDistance(at, range_xz, range_y).filterState(..).findFirst()`:
/// the first block `matches` accepts (given its position and name), going
/// out from `at` by Manhattan distance as `BlockPos.withinBoxByManhattanDistance` does.
pub fn nearest_block(
&self,
at: [i32; 3],
range_xz: i32,
range_y: i32,
matches: impl Fn([i32; 3], &str) -> bool,
) -> Option<[i32; 3]> {
// Visiting order: distance, then x, then y, then +z before -z.
let mut best: Option<((i32, i32, i32, bool), [i32; 3])> = None;
for dx in -range_xz..=range_xz {
for dy in -range_y..=range_y {
for dz in -range_xz..=range_xz {
let key = (dx.abs() + dy.abs() + dz.abs(), dx, dy, dz < 0);
if best.is_some_and(|(k, _)| k <= key) {
continue;
}
let p = [at[0] + dx, at[1] + dy, at[2] + dz];
let state = self.world.block(p[0], p[1], p[2]);
if !self.facts.is_air(state) && matches(p, &self.facts.get(state).name) {
best = Some((key, p));
}
}
}
}
best.map(|(_, p)| p)
}
/// Level.clip with COLLIDER shapes (optionally stopping at any fluid): true on a miss.
pub fn clear_between(&self, from: Vec3, to: Vec3, fluids_block: bool) -> bool {
let mut scene = SceneCollisions {
+14 -6
View File
@@ -1083,7 +1083,7 @@ impl MotionWorld<'_, '_, '_> {
/// `Entity.applyEffectsFromBlocks` for the blocks Horizon's player reacts
/// to inside its movement path: powder snow (`PowderSnowBlock.entityInside`
/// and the FREEZE / EXTINGUISH effects), cobwebs, sweet berry bushes,
/// cactus and lit campfires, and the magma block it stands on
/// cactus and lit campfires, and the magma and slime blocks it stands on
/// (`stepOn`). Pressure plates, tripwires and rails are the world tick's
/// scan.
pub fn apply_effects_from_blocks(&mut self) -> Result<()> {
@@ -1141,14 +1141,22 @@ impl MotionWorld<'_, '_, '_> {
// MagmaBlock's hot floor hurts unless it steps carefully (sneaks).
if self.player.ground.on_ground {
let on = self.legacy_on_position()?;
let magma = self
.assets
.registry
.state(self.block(on))
.is_some_and(|s| s.name == "minecraft:magma_block");
let under = self.assets.registry.state(self.block(on));
let magma = under.is_some_and(|s| s.name == "minecraft:magma_block");
let slime = under.is_some_and(|s| s.name == "minecraft:slime_block");
if magma && !self.player.shift_key_down {
self.environment_hurt("minecraft:hot_floor", 1.0)?;
}
// SlimeBlock.stepOn: a slow walk on slime drags the horizontal
// speed (the client moves its own player, so not the server's copy).
if slime && !damage_only && !self.player.shift_key_down {
let abs_delta_y = self.player.velocity.y.abs();
if abs_delta_y < 0.1 {
let scale = 0.4 + abs_delta_y * 0.2;
self.player.velocity.x *= scale;
self.player.velocity.z *= scale;
}
}
}
let mut visited = std::collections::HashSet::new();
let mut entered = Vec::new();
@@ -63,6 +63,12 @@ pub fn loot_item_with_components(s: &horizon_world::loot::LootStack) -> ItemStac
if let Some(level) = s.ominous_amplifier.filter(|l| *l > 0) {
item.data_mut().ominous_amplifier = Some(level.clamp(0, 4) as u8);
}
// set_stew_effect's `suspicious_stew_effects`.
for (effect, duration) in &s.stew_effects {
item.data_mut()
.stew_effects
.push((Arc::from(effect.as_str()), *duration));
}
item
}
@@ -248,6 +254,7 @@ mod tests {
map: false,
exploration: None,
ominous_amplifier: None,
stew_effects: Vec::new(),
};
// An End city chest's enchant_with_levels roll.
let boots = loot_item_with_components(&stack(
@@ -309,6 +316,7 @@ mod tests {
"zoom": 1
})))),
ominous_amplifier: None,
stew_effects: Vec::new(),
};
let mut item = loot_item(&stack);
assert!(has_pending_map(&item));
+7 -1
View File
@@ -109,7 +109,9 @@ pub struct Weather {
pub thunder_level: (f32, f32),
}
impl Weather {
pub fn tick(&mut self, random: &mut horizon_core::random::LegacyRandom) {
/// The timers of `advanceWeatherCycle`, which run only while
/// `advance_weather` is on.
pub fn tick_timers(&mut self, random: &mut horizon_core::random::LegacyRandom) {
use horizon_core::random::RandomSource;
let mut uniform =
|min: i32, max: i32| min + random.next_int_bound(max - min + 1).unwrap_or(0);
@@ -141,6 +143,10 @@ impl Weather {
self.rain_time = uniform(12000, 180000);
}
}
}
/// The rain and thunder level fade at the end of `advanceWeatherCycle`,
/// which runs whatever `advance_weather` says, so `/weather` still shows.
pub fn tick_levels(&mut self) {
self.thunder_level.0 = self.thunder_level.1;
self.thunder_level.1 =
(self.thunder_level.1 + if self.thundering { 0.01 } else { -0.01 }).clamp(0.0, 1.0);
+13
View File
@@ -181,6 +181,8 @@ pub struct GameRules {
pub max_snow_accumulation_height: i32,
pub spawn_mobs: bool,
pub spawn_monsters: bool,
/// `fire_spread_radius_around_player`: -1 spreads everywhere.
pub fire_spread_radius_around_player: i32,
}
impl Default for GameRules {
fn default() -> Self {
@@ -193,6 +195,7 @@ impl Default for GameRules {
max_snow_accumulation_height: 1,
spawn_mobs: true,
spawn_monsters: true,
fire_spread_radius_around_player: 128,
}
}
}
@@ -288,6 +291,11 @@ pub enum LevelEvent {
/// The world as seen by block behaviour. Implemented by the game and tests.
pub trait LevelAccess {
/// `Level.isClientSide`: this level is a client's copy (false on a
/// server, a host or the test harness).
fn is_client_side(&self) -> bool {
false
}
/// `getBlockState`. Unloaded or out-of-bounds positions read as air.
fn block_state(&self, pos: BlockPos) -> BlockStateId;
/// Storage write (`LevelChunkSection.setBlockState`). Returns the previous
@@ -343,6 +351,11 @@ pub trait LevelAccess {
fn can_spread_fire_around(&self, _pos: BlockPos) -> bool {
true
}
/// The `INCREASED_FIRE_BURNOUT` environment attribute at `pos` (a biome
/// attribute).
fn increased_fire_burnout(&self, _pos: BlockPos) -> bool {
false
}
/// `Level.isUnobstructed(state, pos, context)`: whether the state's
/// collision shape at `pos` would intersect an entity.
fn is_unobstructed(&self, _pos: BlockPos, _state: BlockStateId) -> bool {
+141 -16
View File
@@ -27,6 +27,9 @@ pub struct MovingPiston {
pub progress: f32,
pub progress_o: f32,
pub last_ticked: i64,
/// `PistonMovingBlockEntity.deathTicks`: on a client the entity waits
/// five ticks past progress 1.0 before placing the block itself.
pub death_ticks: i32,
/// Identity of this block entity (a replaced entity is a new ticker).
pub id: u64,
}
@@ -126,11 +129,8 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
self.note_trigger_event(pos, state);
true
} else if data.is(super::classes::Class::Bell) {
// BellBlockEntity.triggerEvent handles event 1; the server
// broadcasts handled events to the clients.
if a == 1 {
self.emit(LevelEvent::BlockEntityEvent { pos, state, a, b });
}
// BellBlockEntity.triggerEvent handles event 1; the caller
// reports handled events (`runBlockEvents` broadcasts them).
a == 1
} else {
false
@@ -164,7 +164,9 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
let Some(piston) = self.moving_piston(pos) else {
return;
};
if piston.progress_o >= 1.0 {
// finalTick: `progressO < 1.0 || level.isClientSide` — a client
// finishes its copy even at full progress.
if piston.progress_o >= 1.0 && !self.level.is_client_side() {
return;
}
self.remove_moving_piston(pos);
@@ -189,6 +191,20 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
piston.last_ticked = self.level.game_time();
piston.progress_o = piston.progress;
if piston.progress_o >= 1.0 {
if self.level.is_client_side() && piston.death_ticks < 5 {
// The client's copy waits for the server's state before
// placing the block itself (deathTicks < 5).
piston.death_ticks += 1;
if let Some(entry) = self
.ticks
.moving_pistons
.iter_mut()
.find(|(p, _)| *p == pos)
{
entry.1 = piston;
}
return;
}
self.remove_moving_piston(pos);
if b.is_block(self.state(pos), b.named.moving_piston) {
let mut new = self.update_from_neighbour_shapes(piston.moved_state, pos);
@@ -241,8 +257,13 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
direction != Direction::Down && self.has_signal(rel(up, direction), direction)
})
}
/// `PistonBaseBlock.checkIfExtend`.
/// `PistonBaseBlock.checkIfExtend`, which `neighborChanged`, `onPlace`
/// and `setPlacedBy` call only server-side: a client moves its pistons on
/// the server's block events alone.
pub(crate) fn piston_check_if_extend(&mut self, pos: BlockPos, state: BlockStateId) {
if self.level.is_client_side() {
return;
}
let b = self.b;
let direction = b.facing(state);
let extend = self.piston_neighbor_signal(pos, direction);
@@ -527,6 +548,12 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
for pos in to_destroy.iter().rev() {
let state = self.state(*pos);
self.drop_resources(state, *pos);
// The client's copy plays the destroy effect itself (the
// server sends no 2001 for piston moves).
let fire = b.is_block(state, b.named.fire) || b.is_block(state, b.named.soul_fire);
if !fire && self.level.is_client_side() {
self.level_event(2001, *pos, state.0 as i32);
}
self.set_block(*pos, b.air(), 18);
self.game_event(*pos, "minecraft:block_destroy");
to_update.push(state);
@@ -551,6 +578,7 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
progress: 0.0,
progress_o: 0.0,
last_ticked: 0,
death_ticks: 0,
id: 0,
},
);
@@ -576,6 +604,7 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
progress: 0.0,
progress_o: 0.0,
last_ticked: 0,
death_ticks: 0,
id: 0,
},
);
@@ -624,13 +653,17 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
let direction = b.facing(state);
let extended_state = b.table.set_bool(state, p.extended, true);
let sticky = self.is_sticky_piston(state);
let extend = self.piston_neighbor_signal(pos, direction);
if extend && (a == 1 || a == 2) {
self.set_block(pos, extended_state, 2);
return false;
}
if !extend && a == 0 {
return false;
// The signal re-check is server-only (`!level.isClientSide`): a
// client trusts the event as sent.
if !self.level.is_client_side() {
let extend = self.piston_neighbor_signal(pos, direction);
if extend && (a == 1 || a == 2) {
self.set_block(pos, extended_state, 2);
return false;
}
if !extend && a == 0 {
return false;
}
}
if a == 0 {
if !self.piston_move_blocks(pos, direction, true, sticky) {
@@ -664,6 +697,7 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
progress: 0.0,
progress_o: 0.0,
last_ticked: 0,
death_ticks: 0,
id: 0,
},
);
@@ -748,8 +782,18 @@ impl Behaviours {
}
let mut sim = self.sim(level, ticks);
let state = sim.state(event.pos);
if self.block(state) == event.block {
sim.trigger_event(state, event.pos, event.param_a, event.param_b);
if self.block(state) == event.block
&& sim.trigger_event(state, event.pos, event.param_a, event.param_b)
{
// ServerLevel.runBlockEvents broadcasts a handled event to
// the clients (`ClientboundBlockEventPacket`); their copy of
// the block re-runs `triggerEvent` (a piston's `moveBlocks`).
sim.emit(LevelEvent::BlockEntityEvent {
pos: event.pos,
state,
a: event.param_a,
b: event.param_b,
});
}
}
for event in reschedule {
@@ -779,4 +823,85 @@ impl Behaviours {
self.sim(level, ticks).moving_piston_tick(pos);
}
}
/// `ClientLevel.blockEvent`: the client re-runs the block's
/// `triggerEvent` on its own level (a piston's `moveBlocks` builds the
/// moving block entities it then animates) instead of waiting for the
/// server's states. No queue and no ticking-chunk gate: a client runs
/// the event where the packet lands.
pub fn client_block_event<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
pos: BlockPos,
a: i32,
b: i32,
) -> bool {
let triggered = {
let mut sim = self.sim(level, ticks);
let state = sim.state(pos);
let triggered = sim.trigger_event(state, pos, a, b);
if triggered {
// The client's copy of a handled event reaches the client
// copy of the block entity (a bell's ring).
sim.emit(LevelEvent::BlockEntityEvent { pos, state, a, b });
}
triggered
};
self.client_drain_block_events(level, ticks);
triggered
}
/// `ClientLevel.tickBlockEntities` for moving pistons: the client copy of
/// [`Behaviours::tick_block_entities`], without the server's
/// ticking-chunk gate (a client ticks every loaded block entity). One
/// whose block was replaced is dropped (`TickingBlockEntity.isRemoved`).
pub fn client_tick_block_entities<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
) {
let tickers: Vec<(BlockPos, u64)> = ticks
.moving_pistons
.iter()
.map(|(p, m)| (*p, m.id))
.collect();
for (pos, id) in tickers {
if !ticks
.moving_pistons
.iter()
.any(|(p, m)| *p == pos && m.id == id)
{
continue;
}
{
let mut sim = self.sim(level, ticks);
let state = sim.state(pos);
if sim.b.is_block(state, sim.b.named.moving_piston) {
sim.moving_piston_tick(pos);
} else {
sim.remove_moving_piston(pos);
}
}
self.client_drain_block_events(level, ticks);
}
}
/// Block events a client-side `triggerEvent` queued
/// (`PistonBaseBlock.checkIfExtend` in a neighbour update): a client
/// runs them as they come (`ClientLevel.blockEvent`), not in a tick pass.
fn client_drain_block_events<L: LevelAccess + ?Sized>(&self, level: &mut L, ticks: &mut Ticks) {
while let Some(event) = ticks.block_events.first().copied() {
ticks.block_events.remove(0);
let mut sim = self.sim(level, ticks);
let state = sim.state(event.pos);
if self.block(state) == event.block
&& sim.trigger_event(state, event.pos, event.param_a, event.param_b)
{
sim.emit(LevelEvent::BlockEntityEvent {
pos: event.pos,
state,
a: event.param_a,
b: event.param_b,
});
}
}
}
}
+100
View File
@@ -47,6 +47,8 @@ pub(crate) struct TestLevel {
pub day_time: i64,
pub events: Vec<LevelEvent>,
pub block_light: HashMap<BlockPos, i32>,
/// `Level.isClientSide`.
pub client_side: bool,
}
impl TestLevel {
fn new(b: &Behaviours) -> Self {
@@ -58,10 +60,14 @@ impl TestLevel {
day_time: 0,
events: Vec::new(),
block_light: HashMap::new(),
client_side: false,
}
}
}
impl LevelAccess for TestLevel {
fn is_client_side(&self) -> bool {
self.client_side
}
fn block_state(&self, pos: BlockPos) -> BlockStateId {
self.blocks.get(&pos).copied().unwrap_or(self.air)
}
@@ -919,6 +925,100 @@ fn pistons_push_and_sticky_pistons_pull() {
assert_eq!(w.get(BlockPos::new(2, 1, 0)), air);
}
/// `ServerLevel.runBlockEvents` reports a handled event for the clients
/// (`ClientboundBlockEventPacket`), carrying the block the event named.
#[test]
fn a_handled_block_event_reaches_the_clients() {
let mut w = world!();
w.floor(0, 10, "stone");
let piston = w.id("piston", &[("facing", "east")]);
let block = w.id("redstone_block", &[]);
w.set(BlockPos::new(0, 1, 0), piston);
w.set(BlockPos::new(-1, 1, 0), block);
w.level.events.clear();
w.full_tick();
assert!(w.level.events.iter().any(|e| matches!(
e,
LevelEvent::BlockEntityEvent {
pos,
state,
a: 0,
..
} if *pos == BlockPos::new(0, 1, 0) && *state == piston
)));
}
/// `ClientLevel.blockEvent`: the client re-runs `triggerEvent` on its own
/// level, which builds the moving block entities a piston's `moveBlocks`
/// makes, and ticks them to the placed block.
#[test]
fn a_client_replays_a_pistons_block_event() {
let mut w = world!();
w.floor(0, 10, "stone");
let piston = w.id("sticky_piston", &[("facing", "east")]);
let dirt = w.id("dirt", &[]);
let block = w.id("redstone_block", &[]);
w.put(BlockPos::new(0, 1, 0), piston);
w.put(BlockPos::new(1, 1, 0), dirt);
w.put(BlockPos::new(-1, 1, 0), block);
w.f.behaviours.client_block_event(
&mut w.level,
&mut w.ticks,
BlockPos::new(0, 1, 0),
0,
Direction::East as i32,
);
assert!(
w.ticks
.moving_pistons
.iter()
.any(|(p, _)| *p == BlockPos::new(2, 1, 0))
);
for _ in 0..3 {
w.level.time += 1;
w.f.behaviours
.client_tick_block_entities(&mut w.level, &mut w.ticks);
}
assert_eq!(w.get(BlockPos::new(2, 1, 0)), dirt);
assert_eq!(
w.name(BlockPos::new(1, 1, 0)),
"piston_head[facing=east,short=false,type=sticky]"
);
assert!(w.ticks.moving_pistons.is_empty());
}
/// A client's copy of a move doesn't start the pistons the moved block
/// powers (`checkIfExtend` is server-only): their own block events come from
/// the server.
#[test]
fn a_client_replay_starts_no_other_piston() {
let mut w = world!();
w.floor(0, 10, "stone");
w.level.client_side = true;
let piston = w.id("piston", &[("facing", "east")]);
let block = w.id("redstone_block", &[]);
let up = w.id("piston", &[("facing", "up")]);
w.put(BlockPos::new(0, 1, 0), piston);
w.put(BlockPos::new(1, 1, 0), block);
w.put(BlockPos::new(2, 2, 0), up);
w.f.behaviours.client_block_event(
&mut w.level,
&mut w.ticks,
BlockPos::new(0, 1, 0),
0,
Direction::East as i32,
);
for _ in 0..10 {
w.level.time += 1;
w.f.behaviours
.client_tick_block_entities(&mut w.level, &mut w.ticks);
}
assert_eq!(w.get(BlockPos::new(2, 1, 0)), block);
assert_eq!(w.get(BlockPos::new(2, 2, 0)), up);
assert!(w.ticks.moving_pistons.is_empty());
assert!(w.ticks.block_events.is_empty());
}
#[test]
fn pistons_pop_fragile_blocks_and_refuse_obsidian() {
let mut w = world!();
+2 -3
View File
@@ -565,9 +565,8 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
return;
}
}
// FireBlock.tick reads the INCREASED_FIRE_BURNOUT environment attribute
// (jungles, swamps, peaks, mushroom fields); Horizon doesn't yet.
let burnout = false;
// FireBlock.tick: the INCREASED_FIRE_BURNOUT environment attribute.
let burnout = self.level.increased_fire_burnout(pos);
let extra = if burnout { -50 } else { 0 };
for (direction, chance) in [
(Direction::East, 300),
+19 -1
View File
@@ -31,6 +31,9 @@ pub struct LootStack {
pub exploration: Option<Box<ExplorationMap>>,
/// Set by set_ominous_bottle_amplifier.
pub ominous_amplifier: Option<i32>,
/// Added by set_stew_effect (the `suspicious_stew_effects` component):
/// (effect id, duration in ticks).
pub stew_effects: Vec<(String, i32)>,
}
/// `ExplorationMapFunction`'s settings.
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -74,6 +77,7 @@ impl LootStack {
map: false,
exploration: None,
ominous_amplifier: None,
stew_effects: Vec::new(),
}
}
pub fn is_empty(&self) -> bool {
@@ -678,6 +682,13 @@ impl LootData {
}
}
/// `MobEffect.isInstantaneous`.
fn is_instantaneous(effect: &str) -> bool {
matches!(
effect,
"minecraft:saturation" | "minecraft:instant_health" | "minecraft:instant_damage"
)
}
/// The level of one enchantment on a stack (its `enchantments` component).
fn item_level(stack: &LootStack, enchantment: &str) -> i32 {
stack
@@ -1134,7 +1145,14 @@ impl<R: RandomSource> Context<'_, R> {
.random
.next_int_bound(effects.len() as i32)
.unwrap_or(0) as usize;
self.int(&effects[pick]["duration"]);
let effect = effects[pick]["type"].as_str().unwrap_or("");
let mut duration = self.int(&effects[pick]["duration"]);
// Seconds, unless the effect is instantaneous.
if !is_instantaneous(effect) {
duration *= 20;
}
// SuspiciousStewEffects.withEffectAdded
stack.stew_effects.push((effect.to_owned(), duration));
}
}
"minecraft:set_ominous_bottle_amplifier" => {
+3 -3
View File
@@ -13,7 +13,7 @@ python3 tools/parity.py --failed # the ones that failed last time
python3 tools/parity.py --all # everything, from scratch: the audit (26 minutes on the Mac mini alone)
python3 tools/parity.py --fresh food # don't reuse vanilla oracle results
python3 tools/parity.py --repeat 3 food # run it three times; the runs must agree
python3 tools/parity.py --hosts macmini,thinkpad # with other machines (default: tools/parity_hosts.json's default list, empty)
python3 tools/parity.py --hosts macmini,playhorizon # with other machines (default: tools/parity_hosts.json's default list, empty)
python3 tools/parity.py --list # what would run
python3 tools/parity.py --status # last result of each harness
python3 tools/parity.py --changed origin/main # those a branch's changes can affect (CI's parity job)
@@ -40,9 +40,9 @@ The game logs into `HORIZON_HOME` and falls back to the player's own game folder
### Other machines
Harnesses can also run on the Mac mini, the ThinkPad and the desktop (`tools/parity_hosts.json` describes them; `desktop` uses its CI runner's environment and vanilla data, and refuses work, or stops it, while someone uses it: docs/release-flow.md, "The desktop's runner"; its `default` list is empty, so pass `--hosts macmini,thinkpad` or set `PARITY_HOSTS`, after copying `shared-local/` to `~/code/horizon-parity/shared-local` on each host). The runner mirrors the worktree there with rsync (not `.git`, `.local`, `target` or ignored files) into `~/code/horizon-parity/remote/<host><path>`, whose `.local` links to the vanilla data in `~/code/horizon-parity/shared-local`, and starts `tools/parity.py --worker` over ssh. The worker builds the probes (about 80 s the first time) and runs what it is sent under the same tracer, admitting harnesses against its own free memory. One queue, longest first, feeds every machine, remote ones first: the Mac takes up to 14 harnesses, the desktop 8. Each pass comes back with the content hash of every file it depended on, so it is keyed on exactly what ran, and logs come back to `.local/parity-runner/logs/`; state, sharing and `gate.py` work as before. If a host can't be reached, or drops out, its harnesses run here.
Harnesses can also run on the Mac mini, the desktop and playhorizon (`tools/parity_hosts.json` describes them; `desktop` and `playhorizon` use their CI runner's environment and vanilla data, and the desktop refuses work, or stops it, while someone uses it: docs/release-flow.md, "The desktop's runner"; its `default` list is empty, so pass `--hosts macmini,playhorizon` or set `PARITY_HOSTS`, after copying `shared-local/` to `~/code/horizon-parity/shared-local` on each host). The runner mirrors the worktree there with rsync (not `.git`, `.local`, `target` or ignored files) into `~/code/horizon-parity/remote/<host><path>`, whose `.local` links to the vanilla data in `~/code/horizon-parity/shared-local`, and starts `tools/parity.py --worker` over ssh. The worker builds the probes (about 80 s the first time) and runs what it is sent under the same tracer, admitting harnesses against its own free memory. One queue, longest first, feeds every machine, remote ones first: the Mac takes up to 14 harnesses, the desktop 8, playhorizon 6. Each pass comes back with the content hash of every file it depended on, so it is keyed on exactly what ran, and logs come back to `.local/parity-runner/logs/`; state, sharing and `gate.py` work as before. If a host can't be reached, or drops out, its harnesses run here.
Harnesses a host can't run are listed in the file: `local_only` (`save_roundtrip` runs the game on a virtual screen) and each host's `exclude`. The Mac excludes nothing: vanilla's `Math.sin`, `pow`, `log` and the like don't round the same on an Apple silicon Mac as on Linux (HotSpot uses fdlibm there, Intel's stubs on x86-64), and Rust's float functions round like neither (they call the platform libm), so code that mirrors a vanilla `Math` call uses `horizon_core::jmath`, which computes what HotSpot computes on the host architecture. The ThinkPad helps too, gently: Linux, 2 harnesses at `nice 19`, since it hosts the Claude account pool; it finds ALSA through `~/code/horizon-parity/alsa-dev` like the desktop.
Harnesses a host can't run are listed in the file: `local_only` (`save_roundtrip` runs the game on a virtual screen) and each host's `exclude`. The Mac excludes nothing: vanilla's `Math.sin`, `pow`, `log` and the like don't round the same on an Apple silicon Mac as on Linux (HotSpot uses fdlibm there, Intel's stubs on x86-64), and Rust's float functions round like neither (they call the platform libm), so code that mirrors a vanilla `Math` call uses `horizon_core::jmath`, which computes what HotSpot computes on the host architecture. The ThinkPad no longer runs harnesses (2026-10-26): playhorizon is the Linux host that is always on.
### Shards and Rust scopes
+1 -1
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env bash
# A Horizon CI runner (labels self-hosted, Linux, X64, horizon-game and the host's name) on a Linux machine of the
# maintainer's (NixOS: ludodesktop, ludothinkpad; Ubuntu: playhorizon, a partner's server), as a systemd user service
# maintainer's (NixOS: ludodesktop; Ubuntu: playhorizon, a partner's server), as a systemd user service
# of the account that holds his Minecraft files, like the Mac mini's runners (docs/release-flow.md). Run it on that
# machine, as that user:
#
+53
View File
@@ -7274,5 +7274,58 @@ CHECKS += ['cushions']
CHECK_FNS['cushions'] = check_cushions
def check_forced_levels(host, guest, out):
"""#1525: forced block/entity ticks outlive the last player and the 300-tick idle timeout.
Also keep a resident, unforced furnace outside the forced ticket's neighbour ring: scheduling
a playerless integrated-server level must not enable the fixtures' tick-everywhere fallback.
"""
if not SERVER_THREAD:
return 'skipped (needs --server-thread)'
start = pos_of(guest)
results = {}
guest('command', command='gamemode creative')
try:
for dimension in (NETHER, END):
into_level(guest, dimension, 8, 100, 8)
host('command', command='tick freeze')
furnace = ('minecraft:furnace{Items:[{Slot:0b,id:"minecraft:raw_iron",count:1},'
'{Slot:1b,id:"minecraft:coal",count:1}],cooking_total_time:200,'
'cooking_time_spent:0}')
for x in (8, 56):
guest('command', command=f'setblock {x} 100 8 {furnace}')
server_reply(guest, f'execute if data block {x} 100 8 '
'Items[{Slot:0b,id:"minecraft:raw_iron"}] '
'run say forced-input-ready', 'forced-input-ready')
guest('command', command='forceload add 8 8')
guest('command', command='summon minecraft:armor_stand 8.5 104 8.5 {Tags:["forced_tick"]}')
guest('command', command=f'execute in {OVERWORLD} run tp @s {start[0]} {start[1]} {start[2]}')
wait_dimension(guest, OVERWORLD, 400)
host('command', command='tick step 450')
host.wait(500)
prefix = f'execute in {dimension} '
results[dimension] = server_reply(
host, prefix + 'if data block 8 100 8 Items[{Slot:2b,id:"minecraft:iron_ingot"}] '
'if data block 56 100 8 {cooking_time_spent:0} '
'if data block 56 100 8 Items[{Slot:0b,id:"minecraft:raw_iron"}] '
'if data entity @e[tag=forced_tick,limit=1] {Pos:[8.5d,101.0d,8.5d]} run say forced-level-pass',
'forced-level-pass')
assert dims(host, guest) == (OVERWORLD, OVERWORLD), dims(host, guest)
host('command', command=prefix + 'run forceload remove 8 8')
host('command', command=prefix + 'run kill @e[tag=forced_tick]')
host('command', command='tick unfreeze')
finally:
host('command', command='tick unfreeze')
for dimension in (NETHER, END):
host('command', command=f'execute in {dimension} run forceload remove 8 8')
guest('command', command=f'execute in {OVERWORLD} run tp @s {start[0]} {start[1]} {start[2]}')
guest('command', command='gamemode survival')
return results
CHECKS += ['forced-levels']
CHECK_FNS['forced-levels'] = check_forced_levels
if __name__ == '__main__':
main()
+5 -12
View File
@@ -28,19 +28,12 @@
"python": "python3.13",
"jobs": 6,
"nice": 10,
"note": "a partner's server (Ubuntu, 8 EPYC threads, 30 GB, Detroit; tailnet only), used by nothing else: 6 jobs, in the CI runner's environment, slice and Xvfb screen (tools/ci/linux-runner.sh); the light Linux checks that used to go to the ThinkPad go here"
},
"thinkpad": {
"ssh": "thinkpad",
"root": "code/horizon-parity",
"shell": "sh -c",
"jobs": 2,
"nice": 19,
"environment": {
"PARITY_BUILD_JOBS": "2"
"exclude": {
"mob_ai": "the vanilla oracle runs out of its 3 GB heap here (OutOfMemoryError in IO workers; passes on the desktop and the Mac) - 2026-10-26 trial",
"lan_integration": "two clients rendered on the CPU (lavapipe): different timing subtests fail on each run (elytra, consume-release, barter, critical-hits) - 2026-10-26 trial",
"world_reopen": "failed twice here (no Save and Quit button after reopening; the minecart-count flake), passes on the desktop - 2026-10-26 trial"
},
"note": "hosts the Claude account pool: two harnesses at most, at the lowest priority",
"setup": "export PKG_CONFIG_PATH=$HOME/code/horizon-parity/alsa-dev/lib/pkgconfig"
"note": "a partner's server (Ubuntu, 8 EPYC threads, 30 GB, Detroit; tailnet only), used by nothing else: 6 jobs, in the CI runner's environment, slice and Xvfb screen (tools/ci/linux-runner.sh); the always-on Linux host since the ThinkPad stopped running harnesses (2026-10-26)"
}
},
"local_only": {
+2 -4
View File
@@ -46,12 +46,10 @@ from tools import parity, release_train # noqa: E402
RBUILD = Path.home() / "fleet" / "rbuild"
LINE_LIMIT = 500
# What rbuild's login shell needs on each fleet machine before cargo (it adds sccache itself). The ThinkPad hosts
# the Claude account pool: three jobs at most.
# What rbuild's login shell needs on each fleet machine before cargo (it adds sccache itself). The ThinkPad no
# longer builds (2026-10-26: it keeps the AI pool and a few services; Linux work goes to playhorizon's runner).
HOST_SETUP = {
"macmini": "source ~/.cargo/env; export PATH=/opt/homebrew/bin:$PATH CARGO_BUILD_JOBS=${CARGO_BUILD_JOBS:-10}",
"thinkpad": 'export CARGO_BUILD_JOBS=3 PKG_CONFIG_PATH="$(ls -d /nix/store/*-alsa-lib-*-dev/lib/pkgconfig | tail -1):'
'$(ls -d /nix/store/*-systemd-*-dev/lib/pkgconfig | tail -1)"',
"local": "",
}
# Hosts that hold the vanilla data, and how a run there gets it: CI's own runner scripts on the parity runner's