From 682927cb6934a33df0bcacaa754c4babf5681287 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 13:43:56 +0200 Subject: [PATCH] Hear game events from players and mobs, light the darkness effect and persist the warden warning Players and mobs now report footsteps, swimming, landings, splashes, damage, deaths, eating, drinking, container use, shots and landed projectiles, blasts, lightning and primed TNT to the vibration system, with sneaking and wool respected. The darkness effect fades in and out over 22 ticks, closes the fog in to 15 blocks, dims the lightmap with its pulse and hides the sun, moon and stars. Active sculk sensors shed redstone dust, charge and shriek level events show their particles, and the player's warning level is saved with the player data. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/fog.rs | 15 ++ crates/horizon-client/src/game.rs | 23 +- crates/horizon-client/src/game/control.rs | 2 + crates/horizon-client/src/game/creatures.rs | 10 +- crates/horizon-client/src/game/crossbow.rs | 1 + crates/horizon-client/src/game/explosion.rs | 3 + crates/horizon-client/src/game/lightning.rs | 4 + crates/horizon-client/src/game/potions.rs | 1 + crates/horizon-client/src/game/render_tick.rs | 1 + crates/horizon-client/src/game/sculk.rs | 210 ++++++++++++++++-- crates/horizon-client/src/game/tnt.rs | 3 + crates/horizon-client/src/game/trident.rs | 1 + crates/horizon-client/src/gfx.rs | 9 +- crates/horizon-client/src/mobs/ai.rs | 3 +- crates/horizon-client/src/mobs/warden.rs | 58 +++-- crates/horizon-client/src/particles.rs | 4 +- crates/horizon-client/src/sculk.rs | 6 +- crates/horizon-world/src/level/tests.rs | 27 +++ 18 files changed, 336 insertions(+), 45 deletions(-) diff --git a/crates/horizon-client/src/fog.rs b/crates/horizon-client/src/fog.rs index 998b3ae8f..4146de4f6 100644 --- a/crates/horizon-client/src/fog.rs +++ b/crates/horizon-client/src/fog.rs @@ -185,6 +185,8 @@ pub struct FogInputs<'a> { pub skybox: bool, /// Blindness: (remaining duration ticks, infinite). pub blindness: Option<(i32, bool)>, + /// The darkness effect's blend factor, while the effect is on. + pub darkness: Option, } /// `FogRenderer.setupFog` + `computeFogColor`. @@ -239,6 +241,9 @@ pub fn setup_fog(tables: &FogTables, state: &FogState, input: &FogInputs) -> Fog } else { 1.0 }; + } else if let Some(blend) = input.darkness { + // DarknessFogEnvironment.getModifiedDarkness. + darkness = darkness.max(blend); } if darkness > 0.0 && !matches!(input.fog_type, FogType::Lava | FogType::PowderSnow) { let brightness = (1.0 - darkness) * (1.0 - darkness); @@ -283,6 +288,15 @@ pub fn setup_fog(tables: &FogTables, state: &FogState, input: &FogInputs) -> Fog fog.sky_end = distance * 0.8; fog.cloud_end = distance * 0.8; } + _ if input.darkness.is_some() => { + // DarknessFogEnvironment.setupFog: closing in to 15 blocks. + let blend = input.darkness.unwrap_or(0.0); + let distance = rd + (15.0 - rd) * blend; + fog.environmental_start = distance * 0.75; + fog.environmental_end = distance; + fog.sky_end = distance; + fog.cloud_end = distance; + } FogType::Water => { fog.environmental_start = -8.0; let factor = tables @@ -345,6 +359,7 @@ mod tests { thunder: 0.0, skybox: true, blindness: None, + darkness: None, } } #[test] diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index d46e6ab74..212153971 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1433,6 +1433,12 @@ impl Game<'_> { } else if let Some(entity) = BlockEntity::for_block(&name) { self.world.block_entities.entry(key).or_insert(entity); self.container = Some(key); + self.post_block_game_event( + "minecraft:container_open", + [key.0, key.1, key.2], + Some(horizon_client::mobs::Who::Player), + None, + ); let stat = match &*name { "minecraft:chest" => "open_chest", "minecraft:trapped_chest" => "trigger_trapped_chest", @@ -1965,6 +1971,8 @@ impl Game<'_> { } if ticks >= duration { self.using = None; + // Consumable.onConsume. + self.post_entity_event("minecraft:eat", horizon_client::mobs::Who::Player); if let Some((nutrition, saturation)) = info.food && let Some(p) = self.player.as_mut() { @@ -3383,6 +3391,12 @@ impl Game<'_> { } self.craft_size = 2; if let Some(key) = self.container.take() { + self.post_block_game_event( + "minecraft:container_close", + [key.0, key.1, key.2], + Some(horizon_client::mobs::Who::Player), + None, + ); let name = self .res .facts @@ -5711,6 +5725,7 @@ impl Game<'_> { on_ground, ); self.creatures.projectiles.push(arrow); + self.player_projectile_shot(); let pitch = 1.0 / (self.world.random.next_float() * 0.4 + 1.2) + power * 0.5; self.audio .play("minecraft:entity.arrow.shoot", Some(eye), 1.0, pitch); @@ -6527,6 +6542,7 @@ impl Game<'_> { self.save_fight(); self.save_stats(); self.save_advancements(); + self.save_warden_tracker(); self.level.selected_slot = self.selected as i32; let mode = self.mode_id(); let level = &mut self.level; @@ -6713,7 +6729,11 @@ impl Game<'_> { } let celestial = if title { self.panorama_geometry() - } else if self.dim == Dim::Overworld { + } else if self.dim == Dim::Overworld + && self.potions.effects.get("darkness").is_none() + && self.potions.effects.get("blindness").is_none() + { + // Camera.doesMobEffectBlockSky: no sun, moon or stars. self.celestial_geometry(&sky) } else if self.dim == Dim::End { self.end_sky_geometry() @@ -6792,6 +6812,7 @@ impl Game<'_> { screen: &screen, game_time: self.world.game_time as f32, ticks: self.ticks, + darkness: self.darkness_lighting(alpha as f32), }; self.renderer.as_mut().ok_or("renderer")?.render(&frame) } diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 7c07af665..c9c5a34ac 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -84,8 +84,10 @@ impl Game<'_> { .chain(super::station_control::HELP) .chain(super::blockctl::HELP) .chain(super::render_control::HELP) + .chain(super::sculk::HELP) .collect::>() }))), "setblock" | "fill" | "particle" | "signedit" => self.render_command(&words), + "sculk" => Ok(Some(self.sculk_command(&words)?)), "status" => Ok(Some(self.control_status())), "key" => { let key = key_code(arg(1)?).ok_or_else(|| format!("unknown key {}", words[1]))?; diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 31abb2adf..13cda3685 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -259,6 +259,7 @@ impl Game<'_> { "on_ground": m.on_ground, "variant": m.extra.variant, "color": m.extra.color, + "warden": horizon_client::mobs::warden::describe(m), }) }) .collect(); @@ -874,7 +875,11 @@ impl Game<'_> { m.ai.target = Some(target); } } - MobEvent::Projectile(p) => self.creatures.projectiles.push(p), + MobEvent::Projectile(p) => { + let (owner, at) = (p.owner, [p.position.x, p.position.y, p.position.z]); + self.creatures.projectiles.push(p); + self.projectile_event("minecraft:projectile_shoot", owner, at); + } MobEvent::Spawn(mut m) => { self.next_entity += 1; m.id = self.next_entity; @@ -1360,6 +1365,8 @@ impl Game<'_> { return Ok(()); } let atp = [at.x, at.y, at.z]; + // Projectile.onHit: the landing is heard. + self.projectile_event("minecraft:projectile_land", p.owner, atp); let source_kind = match p.kind { ProjectileKind::Arrow { .. } => DamageKind::Arrow, ProjectileKind::SmallFireball | ProjectileKind::LargeFireball { .. } => { @@ -2063,6 +2070,7 @@ impl Game<'_> { on_ground, ); self.creatures.projectiles.push(proj); + self.player_projectile_shot(); let sound = match kind { ProjectileKind::Snowball => "minecraft:entity.snowball.throw", ProjectileKind::Egg => "minecraft:entity.egg.throw", diff --git a/crates/horizon-client/src/game/crossbow.rs b/crates/horizon-client/src/game/crossbow.rs index 52dc3078e..c51049da8 100644 --- a/crates/horizon-client/src/game/crossbow.rs +++ b/crates/horizon-client/src/game/crossbow.rs @@ -144,6 +144,7 @@ impl Game<'_> { ); arrow.shoot(&mut self.world.random, dir.to_array(), 3.15, 1.0); self.creatures.projectiles.push(arrow); + self.player_projectile_shot(); let pitch = if index == 0 { 1.0 } else { diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 9185252f1..2add475a3 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -326,6 +326,9 @@ impl Game<'_> { fire: bool, ) -> Result<()> { let mut targets = self.exploded_positions(center, radius); + // Explosion.explode: the blast is heard. + let ctx = horizon_client::sculk::Context::default(); + self.post_game_event("minecraft:explode", center, ctx); self.explosion_hurt_entities(center, radius); if interaction != BlockInteraction::Keep { // Util.shuffle(list, level.random) diff --git a/crates/horizon-client/src/game/lightning.rs b/crates/horizon-client/src/game/lightning.rs index 9feff6ef3..163fda0d6 100644 --- a/crates/horizon-client/src/game/lightning.rs +++ b/crates/horizon-client/src/game/lightning.rs @@ -120,6 +120,10 @@ impl Game<'_> { Some([x, top.y, z]) } pub(super) fn spawn_bolt(&mut self, at: [f64; 3], visual_only: bool) { + if !visual_only { + let ctx = horizon_client::sculk::Context::default(); + self.post_game_event("minecraft:lightning_strike", at, ctx); + } let r = &mut self.world.random; let seed = r.next_long(); let flashes = r.next_int_bound(3).unwrap_or(0) + 1; diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index ffa2c86da..72546c8bb 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -154,6 +154,7 @@ impl Game<'_> { return true; } self.using = None; + self.post_entity_event("minecraft:drink", horizon_client::mobs::Who::Player); let (lasting, now) = PlayerEffects::potion_effects(stack.potion(), 1.0); for e in lasting { self.potions.effects.add(e); diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index b978ce1f8..c13973e95 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -88,6 +88,7 @@ impl Game<'_> { thunder, skybox: self.dim == Dim::Overworld, blindness: None, + darkness: self.darkness_fog(), }) } /// `SkyRenderer.shouldRenderDarkDisc`: eye below the horizon (y 63) and not under water. diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs index ac6b79221..81bf33fe7 100644 --- a/crates/horizon-client/src/game/sculk.rs +++ b/crates/horizon-client/src/game/sculk.rs @@ -15,6 +15,13 @@ use horizon_world::registry::BlockStateId; use std::collections::{HashMap, HashSet}; use winit::keyboard::KeyCode; +pub const HELP: &[&str] = &[ + "sculk sculk listeners, the warning level and the darkness blend", + "sculk charge X Y Z AMOUNT a mob dying there with that much experience (the nearest catalyst takes it)", + "sculk warn LEVEL set the player's warden warning level", + "sculk dig end the minute of calm of every warden", +]; + /// The sculk block kinds by state id, built once. #[derive(Default)] struct Tables { @@ -65,9 +72,12 @@ pub(super) struct SculkState { steps: HashMap, damaged: HashMap, last_health: Option, + /// The darkness effect's blend factor, previous and current tick. + darkness: (f32, f32), /// Who causes the block changes being processed (the player's actions). pub actor: Option, ticks: u32, + tracker_loaded: bool, } const KIND_SENSOR: u8 = 1; const KIND_CALIBRATED: u8 = 2; @@ -102,6 +112,99 @@ impl Game<'_> { out } + /// The `sculk` control command: listeners and their vibrations, or a + /// test charge for the nearest catalyst. + pub(super) fn sculk_command(&mut self, words: &[&str]) -> Result { + match words.get(1).copied() { + Some("charge") => { + let num = |i: usize| -> Result { + Ok(words.get(i).ok_or("missing argument")?.parse::()?) + }; + let at = [num(2)?, num(3)?, num(4)?]; + let amount = num(5)? as u32; + let taken = self.catalyst_takes_experience(at, |_| amount); + Ok(serde_json::json!({ "ok": true, "taken": taken })) + } + Some("dig") => { + // Let every warden's minute of calm run out. + for m in self + .mobs + .iter_mut() + .filter(|m| m.species() == Species::Warden) + { + warden::expire_dig_cooldown(m); + } + Ok(serde_json::json!({ "ok": true })) + } + Some("warn") => { + let level = words.get(2).ok_or("missing level")?.parse::()?; + self.sculk.tracker.set_warning_level(level); + Ok(serde_json::json!({ "ok": true })) + } + _ => Ok(self.sculk_status()), + } + } + /// The `sculk` control command's listing. + pub(super) fn sculk_status(&self) -> serde_json::Value { + let listeners: Vec = self + .sculk + .index + .iter() + .filter_map(|key| match self.world.block_entities.get(key) { + Some(BlockEntity::Sculk(e)) => Some(serde_json::json!({ + "pos": [key.0, key.1, key.2], + "kind": e.id(), + "current": e.vibration.current.map(|i| i.event), + "travel": e.vibration.travel, + "last_frequency": e.last_frequency, + "warning_level": e.warning_level, + "cursors": e.spreader.cursors.len(), + })), + _ => None, + }) + .collect(); + serde_json::json!({ + "listeners": listeners, + "warning_level": self.sculk.tracker.warning_level, + "cooldown": self.sculk.tracker.cooldown_ticks, + "darkness": self.sculk.darkness.1, + "chunks_known": self.sculk.known.len(), + }) + } + /// `ServerPlayer`'s `warden_spawn_tracker` from the player data. + fn load_warden_tracker(&mut self) { + if self.sculk.tracker_loaded { + return; + } + self.sculk.tracker_loaded = true; + if let Some(tag) = self + .level + .player_extra + .as_ref() + .and_then(|p| p.get("warden_spawn_tracker")) + { + self.sculk.tracker = WardenSpawnTracker::from_nbt(tag); + } + } + /// Write the tracker into the player data being saved. + pub(super) fn save_warden_tracker(&mut self) { + if !self.sculk.tracker_loaded { + return; + } + let tag = self.sculk.tracker.to_nbt(); + let extra = self + .level + .player_extra + .get_or_insert_with(|| horizon_world::nbt::Tag::Compound(Default::default())); + if let horizon_world::nbt::Tag::Compound(map) = extra { + map.insert("warden_spawn_tracker".into(), tag); + } + } + /// Who is causing the block changes being processed. + pub(super) fn sculk_actor(&self) -> Option { + self.sculk.actor + } + // ---- setup and the block entity index ---- fn sculk_prepare(&mut self) { @@ -413,20 +516,17 @@ impl Game<'_> { let state = self.world.block(key.0, key.1, key.2); let can_receive = match kind { SculkKind::Sensor | SculkKind::Calibrated => { - if source_block == [key.0, key.1, key.2] - && matches!(event, "minecraft:block_destroy" | "minecraft:block_place") - { - false - } else if sculk::frequency(event) == 0 - || !self.res.behaviours.sculk_sensor_can_activate(state) - { - false - } else if kind == SculkKind::Calibrated { + // The sensor does not hear its own placement or removal. + let own = source_block == [key.0, key.1, key.2] + && matches!(event, "minecraft:block_destroy" | "minecraft:block_place"); + let frequency = sculk::frequency(event); + let calibrated_out = kind == SculkKind::Calibrated && { let back = self.calibrated_signal(key); - !(back != 0 && sculk::frequency(event) != back) - } else { - true - } + back != 0 && frequency != back + }; + !own && !calibrated_out + && frequency != 0 + && self.res.behaviours.sculk_sensor_can_activate(state) } SculkKind::Shrieker => !self.shrieker_shrieking(state) && ctx.player, SculkKind::Catalyst => false, @@ -536,7 +636,9 @@ impl Game<'_> { pub(super) fn tick_sculk(&mut self) -> Result<()> { self.sculk.ticks = self.sculk.ticks.wrapping_add(1); self.sculk_prepare(); + self.load_warden_tracker(); self.sculk.tracker.tick(); + self.tick_darkness_blend(); self.sculk_sync_index(); let keys: Vec<(i32, i32, i32)> = self.sculk.index.iter().copied().collect(); for key in keys { @@ -783,16 +885,7 @@ impl Game<'_> { && (m.position.y + f64::from(m.height()) / 2.0 - c[1]).abs() < 24.0 && (m.position.z - c[2]).abs() < 24.0 }); - let near = self.player.as_ref().is_some_and(|p| { - !self.spectator() - && !p.health.dead_or_dying() - && (p.position.x - c[0]).powi(2) - + (p.position.y - c[1]).powi(2) - + (p.position.z - c[2]).powi(2) - < WardenSpawnTracker::PLAYER_SEARCH_RADIUS.powi(2) - }); - // The triggering player is always among them. - let _ = near; + // The only player is the one who set it off. let mut trackers = [self.sculk.tracker]; let level = WardenSpawnTracker::try_warn(&mut trackers, warden_nearby); self.sculk.tracker = trackers[0]; @@ -940,6 +1033,46 @@ impl Game<'_> { // ---- darkness ---- + /// `MobEffectInstance.BlendState.tick` for the darkness effect: it fades + /// in and out over 22 ticks. + fn tick_darkness_blend(&mut self) { + const BLEND: f32 = 22.0; + let (_, current) = self.sculk.darkness; + let next = match self.potions.effects.get("darkness") { + Some(e) => { + let target = if e.duration == -1 || e.duration > BLEND as i32 { + 1.0 + } else { + 0.0 + }; + current + (target - current).clamp(-1.0 / BLEND, 1.0 / BLEND) + } + None => 0.0, + }; + self.sculk.darkness = (current, next); + } + /// The darkness effect's blend factor at the partial tick. + fn darkness_blend(&self, partial: f32) -> f32 { + let (previous, current) = self.sculk.darkness; + previous + (current - previous) * partial + } + /// The fog's view of the darkness effect, while it is on. + pub(super) fn darkness_fog(&self) -> Option { + self.potions + .effects + .get("darkness") + .map(|_| self.darkness_blend(self.clock.fraction() as f32)) + } + /// `LightmapRenderStateExtractor`: (brightness taken off the gamma + /// option, the pulsing light scale). + pub(super) fn darkness_lighting(&self, partial: f32) -> (f32, f32) { + // options.darknessEffectScale is at its default of 100%. + let modifier = self.darkness_blend(partial); + let pulse = + ((self.ticks as f32 - partial) * std::f32::consts::PI * 0.025).cos() * 0.45 * modifier; + (modifier, pulse.max(0.0)) + } + /// `Warden.applyDarknessAround` / `MobEffectUtil.addEffectToPlayersAround`. pub(super) fn apply_darkness(&mut self, at: [f64; 3], radius: f64) { if self.creative || self.spectator() { @@ -956,7 +1089,7 @@ impl Game<'_> { if d[0] * d[0] + d[1] * d[1] + d[2] * d[2] >= radius * radius { return; } - if let Some(active) = self.potions.effects.get("minecraft:darkness") + if let Some(active) = self.potions.effects.get("darkness") && active.duration > warden::DARKNESS_REAPPLY - 1 { return; @@ -1186,6 +1319,35 @@ impl Game<'_> { // ---- entity events ---- + /// `Projectile.shoot` / `onHit`: a projectile of `owner` at a position. + pub(super) fn projectile_event( + &mut self, + event: &'static str, + owner: Option, + at: [f64; 3], + ) { + let mut ctx = Context::default(); + if event == "minecraft:projectile_shoot" { + // The shooter is the source of the shot. + ctx = self.who_context(owner, None); + } else { + ctx.owner = owner; + ctx.player = owner == Some(Who::Player) || self.rides_player(owner); + } + self.post_game_event(event, at, ctx); + } + /// The player shot or threw something. + pub(super) fn player_projectile_shot(&mut self) { + if let Some(p) = self.player.as_ref() { + let at = [ + p.position.x, + p.position.y + f64::from(self.eye), + p.position.z, + ]; + self.projectile_event("minecraft:projectile_shoot", Some(Who::Player), at); + } + } + /// Events from entities moving, getting hurt and dying, derived from what /// changed this tick. fn tick_entity_events(&mut self) { diff --git a/crates/horizon-client/src/game/tnt.rs b/crates/horizon-client/src/game/tnt.rs index d4138ff83..3297fe96e 100644 --- a/crates/horizon-client/src/game/tnt.rs +++ b/crates/horizon-client/src/game/tnt.rs @@ -37,6 +37,9 @@ impl Game<'_> { /// `new PrimedTnt(level, x + 0.5, y, z + 0.5, owner)`; `short` applies /// `wasExploded`'s random short fuse. Plays `entity.tnt.primed` for primes. pub(super) fn spawn_primed_tnt(&mut self, pos: BlockPos, short: bool) { + // PrimedTnt: the fuse is lit. + let who = self.sculk_actor(); + self.post_block_game_event("minecraft:prime_fuse", [pos.x, pos.y, pos.z], who, None); let r = &mut self.world.random; let rot = r.next_double() * f64::from(std::f32::consts::TAU); let position = Vec3::new( diff --git a/crates/horizon-client/src/game/trident.rs b/crates/horizon-client/src/game/trident.rs index e2cd00e34..66a0fd93a 100644 --- a/crates/horizon-client/src/game/trident.rs +++ b/crates/horizon-client/src/game/trident.rs @@ -177,6 +177,7 @@ impl Game<'_> { returning: 0, creative_only: self.creative, }); + self.player_projectile_shot(); self.audio .play("minecraft:item.trident.throw", at, 1.0, 1.0); } diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 44b76e51f..ce51c2475 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -77,6 +77,9 @@ pub struct Frame<'a> { pub screen: &'a [crate::screen_effects::ScreenQuad], pub game_time: f32, pub ticks: u64, + /// The darkness effect on the lightmap: the brightness it takes off the + /// gamma option and the pulsing scale subtracted from the light. + pub darkness: (f32, f32), } pub struct Renderer { instance: wgpu::Instance, @@ -1186,7 +1189,11 @@ impl Renderer { } }; self.animate(frame.ticks); - self.update_lightmap(&frame.sky, 0.0, self.gamma); + self.update_lightmap( + &frame.sky, + frame.darkness.1, + (self.gamma - frame.darkness.0).max(0.0), + ); let view_proj = self.view_projection(frame); let aspect = self.config.width as f32 / self.config.height.max(1) as f32; let (yaw, pitch) = (frame.yaw.to_radians(), frame.pitch.to_radians()); diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index a6b788c4b..ce790de87 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -591,7 +591,8 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { /// Mob.checkDespawn (players are the only despawn reference). fn check_despawn(m: &mut Mob, w: &MobWorld) -> bool { let creature = m.kind.category == "creature"; - if m.persistent || creature && m.kind.flags.animal { + // Warden.removeWhenFarAway is false. + if m.persistent || m.species() == Species::Warden || creature && m.kind.flags.animal { m.ai.no_action_time = 0; return true; } diff --git a/crates/horizon-client/src/mobs/warden.rs b/crates/horizon-client/src/mobs/warden.rs index c4177e3d8..4df5ebf19 100644 --- a/crates/horizon-client/src/mobs/warden.rs +++ b/crates/horizon-client/src/mobs/warden.rs @@ -890,18 +890,17 @@ fn start_behaviours(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { && st.walk.is_none() && let Some((location, until)) = st.disturbance && now < until + && dist_sqr(location, block_pos(m)) >= 4.0 { - if dist_sqr(location, block_pos(m)) >= 4.0 { - let ox = m.random.next_int_bound(3).unwrap_or(1) - 1; - let oz = m.random.next_int_bound(3).unwrap_or(1) - 1; - let target = [location[0] + ox, location[1], location[2] + oz]; - st.look = Some((Track::Block(target), NEVER)); - st.walk = Some(Walk { - target: Track::Block(target), - speed: SPEED_INVESTIGATING as f32, - close_enough: 2, - }); - } + let ox = m.random.next_int_bound(3).unwrap_or(1) - 1; + let oz = m.random.next_int_bound(3).unwrap_or(1) - 1; + let target = [location[0] + ox, location[1], location[2] + oz]; + st.look = Some((Track::Block(target), NEVER)); + st.walk = Some(Walk { + target: Track::Block(target), + speed: SPEED_INVESTIGATING as f32, + close_enough: 2, + }); } // Sniff: Sniffing. if active(st, Activity::Sniff) @@ -1412,6 +1411,37 @@ pub fn ai_step(m: &mut Mob, events: &mut Vec) { m.anim.states[SONIC_BOOM].stop(); } } +/// Test aid: the minute of calm ran out. +pub fn expire_dig_cooldown(m: &mut Mob) { + if let Some(st) = m.extra.warden.as_mut() { + st.dig_cooldown = None; + st.attack_target = None; + st.roar_target = None; + } +} +/// The warden's state for the control socket. +pub fn describe(m: &Mob) -> Option { + let st = m.extra.warden.as_ref()?; + let anger: Vec = st + .anger + .suspects() + .iter() + .map(|w| format!("{w:?}={}", st.anger.anger_of(*w))) + .collect(); + Some(serde_json::json!({ + "pose": format!("{:?}", pose(m)), + "activity": format!("{:?}", st.activity), + "anger_level": format!("{:?}", anger_level(m)), + "anger": anger, + "attack_target": st.attack_target.map(|t| format!("{t:?}")), + "roar_target": st.roar_target.map(|t| format!("{t:?}")), + "disturbance": st.disturbance.map(|(p, _)| p), + "walk": st.walk.is_some(), + "dig_cooldown": st.dig_cooldown.map(|t| t - i64::from(m.age)), + "sniff_cooldown": st.sniff_cooldown.map(|t| t - i64::from(m.age)), + "vibration": st.vibration.current.map(|i| i.event), + })) +} /// `Warden.getHeartBeatDelay`. pub fn heart_beat_delay(client_anger: i32) -> i32 { let anger = client_anger as f32 / AngerLevel::Angry.minimum() as f32; @@ -1606,9 +1636,11 @@ mod tests { #[test] fn memories_expire_with_their_ttl() { - let mut st = Warden::default(); + let mut st = Warden { + in_brain: true, + ..Warden::default() + }; // Set during the brain: present for exactly the ttl. - st.in_brain = true; let until = st.expiry(100, 5); assert!(present(until, 104)); assert!(!present(until, 105)); diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index 2a02cd37a..d570a7e74 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -2609,11 +2609,11 @@ impl ParticleEngine { } alpha = 1.0 - ((p.age as f32 + partial) / p.lifetime as f32).clamp(0.0, 1.0); rotations = [ - Some(Quat::from_rotation_x(-1.0472)), + Some(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_3)), Some(Quat::from_euler( glam::EulerRot::YXZ, -std::f32::consts::PI, - 1.0472, + std::f32::consts::FRAC_PI_3, 0.0, )), ]; diff --git a/crates/horizon-client/src/sculk.rs b/crates/horizon-client/src/sculk.rs index 64d61fefb..e7eb4b7ce 100644 --- a/crates/horizon-client/src/sculk.rs +++ b/crates/horizon-client/src/sculk.rs @@ -303,8 +303,10 @@ impl Data { Tag::compound(entries) } pub fn from_nbt(tag: &Tag) -> Self { - let mut data = Self::default(); - data.current = tag.get("event").and_then(info_from_nbt); + let mut data = Self { + current: tag.get("event").and_then(info_from_nbt), + ..Self::default() + }; if let Some(Tag::Int(t)) = tag.get("event_delay") { data.travel = (*t).max(0); } diff --git a/crates/horizon-world/src/level/tests.rs b/crates/horizon-world/src/level/tests.rs index 74534e46f..c9396c2b9 100644 --- a/crates/horizon-world/src/level/tests.rs +++ b/crates/horizon-world/src/level/tests.rs @@ -1052,3 +1052,30 @@ fn catalyst_bloom_lasts_eight_ticks() { w.tick(); assert_eq!(w.prop(pos, "bloom"), "false"); } + +#[test] +fn placing_and_breaking_report_the_affected_state() { + let mut w = world!(); + w.floor(0, 4, "stone"); + let wool = w.id("white_wool", &[]); + let placed = w.place( + "white_wool", + BlockPos::new(0, 0, 0), + Direction::Up, + 0.0, + 0.0, + 0.0, + ); + assert!(matches!(placed, PlaceOutcome::Placed { .. })); + assert!(w.level.events.iter().any(|e| matches!( + e, + LevelEvent::GameEvent { event: "minecraft:block_place", state: Some(s), .. } if *s == wool + ))); + w.level.events.clear(); + w.f.behaviours + .destroy_block(&mut w.level, &mut w.ticks, BlockPos::new(0, 1, 0), false); + assert!(w.level.events.iter().any(|e| matches!( + e, + LevelEvent::GameEvent { event: "minecraft:block_destroy", state: Some(s), .. } if *s == wool + ))); +}