diff --git a/crates/horizon-client/examples/probe/entity_death_loot_fixture.rs b/crates/horizon-client/examples/probe/entity_death_loot_fixture.rs index 86ef275d9..3f47ba787 100644 --- a/crates/horizon-client/examples/probe/entity_death_loot_fixture.rs +++ b/crates/horizon-client/examples/probe/entity_death_loot_fixture.rs @@ -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")); diff --git a/crates/horizon-client/src/animate_tick.rs b/crates/horizon-client/src/animate_tick.rs index b3a587114..28b28544b 100644 --- a/crates/horizon-client/src/animate_tick.rs +++ b/crates/horizon-client/src/animate_tick.rs @@ -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)] diff --git a/crates/horizon-client/src/biome.rs b/crates/horizon-client/src/biome.rs index 63ad004d4..c8c15e44e 100644 --- a/crates/horizon-client/src/biome.rs +++ b/crates/horizon-client/src/biome.rs @@ -28,6 +28,9 @@ pub struct BiomeInfo { pub spawn_costs: HashMap, /// 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), diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index a28cf102a..58b89a140 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -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>, 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) { @@ -7548,6 +7619,69 @@ impl Game<'_> { self.audio .play("minecraft:entity.player.attack.sweep", from, 1.0, 1.0); } + /// The damage and knockback part of `Player.doSweepAttack` after a sweep + /// hit on the mob at `target`: every other living mob in its box grown by + /// (1, 0.25, 1) and closer than 3 blocks (`distanceToSqr < 9`, in creative + /// too), but the player's allies + /// (`isAlliedTo`), takes `1 + sweeping_damage_ratio * baseDamage` with the + /// weapon's enchantments, scaled by the attack strength, and is pushed 0.4 + /// along the player's yaw. + pub(super) fn sweep_damage(&mut self, target: usize, scale: f32) { + let Some(p) = self.player.as_ref() else { + return; + }; + let from = [p.position.x, p.position.y, p.position.z]; + // `baseDamage` of `Player.attack` before a critical hit (a sweep has + // none) and the enchantments: the attack damage attribute with the + // strength and weakness effects, scaled by the attack strength. + let hand_damage = 1.0 + self.attack_item_info().map_or(0.0, |i| i.attack_damage); + let base_damage = (hand_damage + self.effect_attack_bonus()) * (0.2 + scale * scale * 0.8); + // The enchantment's attribute modifier on the attribute's 0 to 1 range. + let ratio = self + .res + .stations() + .enchantments + .attribute_add( + self.inventory[self.selected].as_ref(), + "minecraft:sweeping_damage_ratio", + ) + .clamp(0.0, 1.0) as f32; + let sweep_damage = 1.0 + ratio * base_damage; + let hit_box = self.mobs[target] + .bounds() + .inflate(horizon_core::geometry::Vec3::new(1.0, 0.25, 1.0)); + let (uuid, allies) = ( + self.level.player_uuid.or(Some([0, 0, 0, 1])), + self.player_allies(), + ); + let nearby: Vec = self + .mobs + .iter() + .enumerate() + .filter(|(i, m)| { + *i != target + && m.alive() + && !m.removed + && !allies.contains(&m.id) + && !mace::ally_of_player(m, uuid) + && m.bounds().intersects(hit_box) + && m.position.distance_squared(p.position) < 9.0 + }) + .map(|(i, _)| i) + .collect(); + let (xd, zd) = self.extra_knockback_direction(); + for i in nearby { + let kind = self.mobs[i].kind.id.clone(); + let kind = format!("minecraft:{}", kind.trim_start_matches("minecraft:")); + let damage = (sweep_damage + self.enchant_damage_bonus(&kind)) * scale; + let source = self.attack_source(from); + if self.hurt_by_player(i, damage, source) { + self.mobs[i].knockback(0.4, xd, zd); + self.last_hurt_by_player + .insert(self.mobs[i].id, self.lan_acting); + } + } + } /// `Player.attack`'s sounds when a vehicle takes the hit (it always does, /// and can't be hit critically): knockback when sprinting at full /// strength, then strong or weak. Before `swing_arm` resets the charge. @@ -7721,6 +7855,7 @@ impl Game<'_> { // Player.playServerSideSound: at the player. if let Some(at) = sweep { self.sweep_attack(at, from); + self.sweep_damage(index, scale); } else { self.audio.play(sound, from, 1.0, 1.0); } @@ -7740,15 +7875,18 @@ impl Game<'_> { } } /// ServerExplosion: rays from a 16^3 grid lose (resistance + 0.3) * 0.3 per step. - /// A mob explosion (`Level.ExplosionInteraction.MOB`: drop decay with the - /// default mobGriefing rule). + /// A mob explosion (`ServerLevel.explode` with `ExplosionInteraction.MOB`: + /// blocks are kept without mobGriefing, else the mob_explosion_drop_decay + /// rule picks decay). fn explode(&mut self, center: [f64; 3], radius: f32) -> Result<()> { - self.server_explode( - center, - radius, - explosion::BlockInteraction::DestroyWithDecay, - false, - ) + let interaction = if !self.ui.rules.bool("mob_griefing") { + explosion::BlockInteraction::Keep + } else if self.ui.rules.bool("mob_explosion_drop_decay") { + explosion::BlockInteraction::DestroyWithDecay + } else { + explosion::BlockInteraction::Destroy + }; + self.server_explode(center, radius, interaction, false) } /// Copies of a save batch carrying its live block entities and save data. fn with_entities<'a>( @@ -9671,8 +9809,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 +9826,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 +9889,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 +9947,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 +11769,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 +12027,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(); diff --git a/crates/horizon-client/src/game/campfire_douse.rs b/crates/horizon-client/src/game/campfire_douse.rs new file mode 100644 index 000000000..04accb2d3 --- /dev/null +++ b/crates/horizon-client/src/game/campfire_douse.rs @@ -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 { + 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) + } +} diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 5b40adf9e..03174c009 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -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). diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index a2ed7fd66..1f560af0d 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1128,7 +1128,7 @@ impl Game<'_> { self.particles.add(&options, at, velocity); } } - MobEvent::Experience { at, amount } => self.spawn_orbs(at, amount), + MobEvent::Experience { at, amount } => self.spawn_breeding_orb(at, amount), MobEvent::AxolotlSupportPlayer => { let previous = self .potions @@ -1272,6 +1272,13 @@ impl Game<'_> { m.extra.egg_time = life; } } + /// `Animal.finalizeSpawnChildFromBreeding`'s experience orb: only when the + /// `mob_drops` game rule is on. + fn spawn_breeding_orb(&mut self, at: [f64; 3], amount: u32) { + if self.ui.rules.bool("mob_drops") { + self.spawn_orbs(at, amount); + } + } /// Animal.spawnChildFromBreeding fn breed( &mut self, @@ -1365,7 +1372,7 @@ impl Game<'_> { } self.world.random = r; let xp = 1 + self.world.random.next_int_bound(7).unwrap_or(0) as u32; - self.spawn_orbs([p.position.x, p.position.y, p.position.z], xp); + self.spawn_breeding_orb([p.position.x, p.position.y, p.position.z], xp); return; } if p.species() == Species::Cat { @@ -1386,7 +1393,7 @@ impl Game<'_> { }; } let xp = 1 + self.world.random.next_int_bound(7).unwrap_or(0) as u32; - self.spawn_orbs([p.position.x, p.position.y, p.position.z], xp); + self.spawn_breeding_orb([p.position.x, p.position.y, p.position.z], xp); return; } if p.species() == Species::Wolf { @@ -1408,7 +1415,7 @@ impl Game<'_> { }; } let xp = 1 + self.world.random.next_int_bound(7).unwrap_or(0) as u32; - self.spawn_orbs([p.position.x, p.position.y, p.position.z], xp); + self.spawn_breeding_orb([p.position.x, p.position.y, p.position.z], xp); return; } // Nautilus.getBreedOffspring: a tame parent's baby is tame too. @@ -1424,7 +1431,7 @@ impl Game<'_> { } } let xp = 1 + self.world.random.next_int_bound(7).unwrap_or(0) as u32; - self.spawn_orbs([p.position.x, p.position.y, p.position.z], xp); + self.spawn_breeding_orb([p.position.x, p.position.y, p.position.z], xp); } /// `MobEffectUtil.addEffectToPlayersAround` for an elder guardian: /// mining fatigue III for five minutes unless a stronger or longer one @@ -1520,15 +1527,19 @@ impl Game<'_> { if let Some(a) = attacker.or(owner) { self.note_attacker(damage_type, a); } + // DamageSource.scalesWithDifficulty: a mob (or its projectile's + // owner) caused the hit, not a player. + let living_cause = attacker.or(owner).is_some(); let mut outcome = horizon_client::health::BlockOutcome::default(); if let Some(player) = self.player.as_mut() && let Some(id) = self.motion.health.damage.id(damage_type) - && let Ok(o) = player.hurt_blocking( + && let Ok(o) = player.hurt_caused_by( &self.motion.health, self.world.health_rules, id, amount, blocking, + living_cause, ) && { outcome = o; @@ -1547,7 +1558,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 +3316,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. diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs index 267f323c3..43f41d201 100644 --- a/crates/horizon-client/src/game/dispense_fixture.rs +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -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; diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index c75c2c762..fff03ef1c 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -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 { + // 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) diff --git a/crates/horizon-client/src/game/enchant_effects.rs b/crates/horizon-client/src/game/enchant_effects.rs index aa9f75e06..7cdb3e526 100644 --- a/crates/horizon-client/src/game/enchant_effects.rs +++ b/crates/horizon-client/src/game/enchant_effects.rs @@ -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 { + 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 { diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 6ecba3a54..8800e29d8 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -296,12 +296,14 @@ impl Game<'_> { if !creative && !spectator && hurtable - && let Ok(o) = p.hurt_blocking( + && let Ok(o) = p.hurt_caused_by( &self.motion.health, self.world.health_rules, id, amount, blocking, + // The exploding mob is the causing entity. + exploding.is_some(), ) { outcome = o; diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 63aea7e9f..5292cd31b 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -944,6 +944,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 = { @@ -1177,17 +1184,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)); + } + _ => {} } } } diff --git a/crates/horizon-client/src/game/lan_pvp.rs b/crates/horizon-client/src/game/lan_pvp.rs index c7c6b6525..8e756b7be 100644 --- a/crates/horizon-client/src/game/lan_pvp.rs +++ b/crates/horizon-client/src/game/lan_pvp.rs @@ -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", diff --git a/crates/horizon-client/src/game/levels.rs b/crates/horizon-client/src/game/levels.rs index 9137a26d1..8d2e0a4a2 100644 --- a/crates/horizon-client/src/game/levels.rs +++ b/crates/horizon-client/src/game/levels.rs @@ -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 { let guests = self .lan @@ -405,7 +405,17 @@ impl Game<'_> { let mut dims: Vec = [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() { diff --git a/crates/horizon-client/src/game/lightning.rs b/crates/horizon-client/src/game/lightning.rs index 916bd2a0a..297f372c5 100644 --- a/crates/horizon-client/src/game/lightning.rs +++ b/crates/horizon-client/src/game/lightning.rs @@ -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); } } diff --git a/crates/horizon-client/src/game/mace.rs b/crates/horizon-client/src/game/mace.rs index 8ad5e76c3..34c968980 100644 --- a/crates/horizon-client/src/game/mace.rs +++ b/crates/horizon-client/src/game/mace.rs @@ -24,7 +24,7 @@ const KNOCKBACK_POWER: f32 = 0.7; /// `Entity.isAlliedTo` between the player (`player` its UUID) and a mob /// without teams: `TamableAnimal.considersEntityAsAlly` (a pet it tamed) and /// `Allay.considersEntityAsAlly` (an allay that likes it). -fn ally_of_player(m: &Mob, player: Option<[i32; 4]>) -> bool { +pub(super) fn ally_of_player(m: &Mob, player: Option<[i32; 4]>) -> bool { let tamable = matches!( m.species(), Species::Wolf diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index 8742962e9..bb936744b 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -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) { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index e9f30e84b..3cfbd15e3 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -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(); diff --git a/crates/horizon-client/src/health.rs b/crates/horizon-client/src/health.rs index 25c719bfb..4f7824b25 100644 --- a/crates/horizon-client/src/health.rs +++ b/crates/horizon-client/src/health.rs @@ -295,6 +295,20 @@ impl PlayerMotion { source: DamageTypeId, amount: f32, blocking: Option, + ) -> Result { + self.hurt_caused_by(resources, rules, source, amount, blocking, false) + } + /// `hurt_blocking` from a source whose causing entity is a living + /// non-player (`living_cause`), which the `when_caused_by_living_non_player` + /// damage types scale with the difficulty. + pub fn hurt_caused_by( + &mut self, + resources: &HealthResources, + rules: HealthRules, + source: DamageTypeId, + amount: f32, + blocking: Option, + living_cause: bool, ) -> Result { if self.client_side { return Ok(BlockOutcome::default()); @@ -315,6 +329,7 @@ impl PlayerMotion { invulnerable, rules, source, + living_cause, events: &mut self.events, dead: &mut h.dead, sync_velocity: &mut h.sync_velocity, @@ -390,6 +405,8 @@ pub(crate) struct Environment<'a> { pub(crate) invulnerable: bool, pub(crate) rules: HealthRules, pub(crate) source: DamageSource<'a, ()>, + /// The causing entity is a living non-player (a mob, or its projectile's owner). + pub(crate) living_cause: bool, pub(crate) events: &'a mut Vec, pub(crate) dead: &'a mut bool, pub(crate) sync_velocity: &'a mut bool, @@ -773,8 +790,13 @@ impl PlayerHurtWorld for Environment<'_> { Ok(()) } fn scales_with_difficulty(&mut self, _: &mut State) -> io::Result { - Ok(self.source.definition().scaling == Scaling::Always) - } // no causing entity + // DamageSource.scalesWithDifficulty. + Ok(match self.source.definition().scaling { + Scaling::Never => false, + Scaling::Always => true, + Scaling::LivingNonPlayer => self.living_cause, + }) + } fn difficulty(&mut self, _: &mut State) -> io::Result { Ok(self.rules.difficulty) } diff --git a/crates/horizon-client/src/hunger.rs b/crates/horizon-client/src/hunger.rs index 15eac144f..34f414d50 100644 --- a/crates/horizon-client/src/hunger.rs +++ b/crates/horizon-client/src/hunger.rs @@ -151,6 +151,7 @@ impl FoodWorld for TickWorld<'_> { .damage .source::<()>(id, None, None, None) .expect("validated starvation source"), + living_cause: false, events: self.events, dead: self.dead, sync_velocity: self.sync_velocity, diff --git a/crates/horizon-client/src/keybinds.rs b/crates/horizon-client/src/keybinds.rs index fb0d04344..2047b9117 100644 --- a/crates/horizon-client/src/keybinds.rs +++ b/crates/horizon-client/src/keybinds.rs @@ -241,6 +241,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(keys: Vec) -> Vec { + 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 @@ -286,49 +300,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 + '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> { + 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> { 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> { + self.translate_mouse_all(button).into_iter().next() + } + /// [`KeyBinds::translate_all`] for a mouse button. + pub fn translate_mouse_all(&self, button: MouseButton) -> Vec> { 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 { diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 00c21633e..4b67f738f 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1251,6 +1251,10 @@ pub struct Seen { /// `MAX_HEALTH`, `JUMP_STRENGTH` and `MOVEMENT_SPEED` base values (a /// horse's breeding stock). pub stats: [f64; 3], + /// `Wolf.isInSittingPose`. + pub sitting: bool, + /// `Entity.isVehicle` or `isPassenger`. + pub ridden: bool, } impl Mob { pub fn burning_time(&self) -> f64 { @@ -1323,6 +1327,8 @@ impl Mob { m.extra.vector[0], m.attrs.speed, ], + sitting: m.extra.sitting, + ridden: m.rider.is_some() || m.extra.rider.is_some() || m.extra.mount.is_some(), } } /// `EntityType.getCategory`'s name. @@ -1760,6 +1766,10 @@ impl Mob { self.health -= amount; self.hurt_time = 10; } + // Animal.actuallyHurt: damage taken ends love mode (`resetLove`). + if drops::is_animal(self.species()) { + self.extra.in_love = 0; + } self.last_damage = Some((source, i64::from(self.age))); if let Some(who) = source.attacker { self.ai.last_hurt_by = Some(who); diff --git a/crates/horizon-client/src/mobs/drops.rs b/crates/horizon-client/src/mobs/drops.rs index e5ccfd283..c7b1c77e1 100644 --- a/crates/horizon-client/src/mobs/drops.rs +++ b/crates/horizon-client/src/mobs/drops.rs @@ -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 diff --git a/crates/horizon-client/src/mobs/enderman.rs b/crates/horizon-client/src/mobs/enderman.rs index c5ed01680..3ccd963a2 100644 --- a/crates/horizon-client/src/mobs/enderman.rs +++ b/crates/horizon-client/src/mobs/enderman.rs @@ -331,8 +331,11 @@ impl Goal for TakeBlock { fn flags(&self) -> u8 { 0 } - fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool { - m.extra.carried.is_none() && m.random.next_int_bound(reduced(20)).unwrap_or(1) == 0 + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + // EndermanTakeBlockGoal.canUse: needs mobGriefing, checked before the draw. + m.extra.carried.is_none() + && cx.w.mob_griefing + && m.random.next_int_bound(reduced(20)).unwrap_or(1) == 0 } fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { let x = (m.position.x - 2.0 + m.random.next_double() * 4.0).floor() as i32; @@ -379,8 +382,11 @@ impl Goal for LeaveBlock { fn flags(&self) -> u8 { 0 } - fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool { - m.extra.carried.is_some() && m.random.next_int_bound(reduced(2000)).unwrap_or(1) == 0 + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + // EndermanLeaveBlockGoal.canUse: needs mobGriefing, checked before the draw. + m.extra.carried.is_some() + && cx.w.mob_griefing + && m.random.next_int_bound(reduced(2000)).unwrap_or(1) == 0 } fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { let Some(carried) = m.extra.carried else { diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index 7f73e32c4..a784464d8 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -1771,11 +1771,16 @@ impl Goal for Breed { } let llama = super::llama::is_llama(species); let equine = matches!(species, Species::Horse | Species::Donkey) || llama; - if equine && !m.extra.tame { - return false; - } - // Llama.canParent: not ridden, and at full health. - if llama && (m.rider.is_some() || m.health < m.attrs.max_health) { + // AbstractHorse.canParent: tame, an adult, not a vehicle or passenger + // and at full health. + if equine + && (!m.extra.tame + || m.is_baby() + || m.rider.is_some() + || m.extra.rider.is_some() + || m.extra.mount.is_some() + || m.health < m.attrs.max_health) + { return false; } self.partner = @@ -1788,7 +1793,10 @@ impl Goal for Breed { && s.in_love && !s.baby && (!tamable || s.tame) - && (!equine || s.tame) + // Wolf.canMate: a sitting wolf is no partner. + && !(species == Species::Wolf && s.sitting) + // AbstractHorse.canParent of the partner. + && (!equine || s.tame && !s.ridden && s.health >= s.stats[0] as f32) && (!sniffer || super::sniffer::can_mate_state(s.variant)) }) .map(|s| s.id) diff --git a/crates/horizon-client/src/mobs/rabbit.rs b/crates/horizon-client/src/mobs/rabbit.rs index a2ab6e95c..ac4c3850f 100644 --- a/crates/horizon-client/src/mobs/rabbit.rs +++ b/crates/horizon-client/src/mobs/rabbit.rs @@ -1,5 +1,9 @@ //! Rabbit hopping controls and the clocks consumed by `RabbitModel`. -use super::{Mob, MobEvent, MobWorld, control::Operation}; +use super::{ + Mob, MobEvent, MobWorld, + control::Operation, + goals::{Breed, Tempt}, +}; use horizon_core::{ geometry::{Vec3, trig}, random::RandomSource, @@ -14,7 +18,12 @@ const IDLE_TIMEOUT: usize = 3; const CLIENT_JUMP_TICKS: usize = 4; const CLIENT_JUMP_DURATION: usize = 5; +/// Rabbit.registerGoals after the generic panic and stroll: BreedGoal and +/// TemptGoal with rabbit food. pub fn register(m: &mut Mob) { + let food = m.kind.food.clone(); + m.ai.goals.add(2, Breed::new(0.8)); + m.ai.goals.add(3, Tempt::new(1.0, food, false)); m.ai.mov.kind = super::control::MoveKind::Custom; m.ai.nav.can_float = true; m.extra.ints[IDLE_TIMEOUT] = m.random.next_int_bound(40).unwrap_or(0) + 180; diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 0bce8927c..fcdd32cbd 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -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(); diff --git a/crates/horizon-client/src/structure_blocks.rs b/crates/horizon-client/src/structure_blocks.rs index f77696277..604cf7925 100644 --- a/crates/horizon-client/src/structure_blocks.rs +++ b/crates/horizon-client/src/structure_blocks.rs @@ -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)); diff --git a/crates/horizon-client/src/world.rs b/crates/horizon-client/src/world.rs index d73956d85..83083eba2 100644 --- a/crates/horizon-client/src/world.rs +++ b/crates/horizon-client/src/world.rs @@ -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); diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index 41b325768..c81bdf369 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -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 { diff --git a/crates/horizon-world/src/level/pistons.rs b/crates/horizon-world/src/level/pistons.rs index 648d6d543..45e469efd 100644 --- a/crates/horizon-world/src/level/pistons.rs +++ b/crates/horizon-world/src/level/pistons.rs @@ -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 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 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 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 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 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 Sim<'_, L> { progress: 0.0, progress_o: 0.0, last_ticked: 0, + death_ticks: 0, id: 0, }, ); @@ -576,6 +604,7 @@ impl Sim<'_, L> { progress: 0.0, progress_o: 0.0, last_ticked: 0, + death_ticks: 0, id: 0, }, ); @@ -624,13 +653,17 @@ impl 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 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( + &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( + &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(&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, + }); + } + } + } } diff --git a/crates/horizon-world/src/level/tests.rs b/crates/horizon-world/src/level/tests.rs index 8a4b6c34f..da75083d2 100644 --- a/crates/horizon-world/src/level/tests.rs +++ b/crates/horizon-world/src/level/tests.rs @@ -47,6 +47,8 @@ pub(crate) struct TestLevel { pub day_time: i64, pub events: Vec, pub block_light: HashMap, + /// `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!(); diff --git a/crates/horizon-world/src/level/tick.rs b/crates/horizon-world/src/level/tick.rs index 29f53e053..25e2a19d3 100644 --- a/crates/horizon-world/src/level/tick.rs +++ b/crates/horizon-world/src/level/tick.rs @@ -565,9 +565,8 @@ impl 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), diff --git a/crates/horizon-world/src/loot.rs b/crates/horizon-world/src/loot.rs index 96ca5bdee..f98afa21f 100644 --- a/crates/horizon-world/src/loot.rs +++ b/crates/horizon-world/src/loot.rs @@ -31,6 +31,9 @@ pub struct LootStack { pub exploration: Option>, /// Set by set_ominous_bottle_amplifier. pub ominous_amplifier: Option, + /// 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 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" => { diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index c508a67d6..ab3fcde1b 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -7245,5 +7245,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()