Merge branch 'main' into worktree-agent-a45c92d353e101334

This commit is contained in:
Ludovic Marie
2026-10-10 03:43:23 +02:00
38 changed files with 5723 additions and 32 deletions
+36
View File
@@ -57,6 +57,8 @@ enum Animate {
drag: bool,
},
Fire,
/// An active sculk sensor.
SculkSensor,
}
fn step(facing: &str) -> [i32; 3] {
match facing {
@@ -128,6 +130,11 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option<String>) -> Animate {
drag: prop("drag").as_deref() == Some("true"),
},
"fire" | "soul_fire" => Animate::Fire,
"sculk_sensor" | "calibrated_sculk_sensor"
if prop("sculk_sensor_phase").as_deref() == Some("active") =>
{
Animate::SculkSensor
}
_ if name.ends_with("candle_cake") && lit => Animate::CandleCake,
_ if (name == "candle" || name.ends_with("_candle")) && lit => {
Animate::Candles(prop("candles").and_then(|c| c.parse().ok()).unwrap_or(1))
@@ -905,6 +912,35 @@ fn block_animate_tick(
}
}
}
Animate::SculkSensor => {
// SculkSensorBlock.animateTick.
let r = engine.random();
let direction = r.next_int_bound(6).unwrap_or(0);
// Direction.values(): down, up, north, south, west, east.
if direction >= 2 {
let step = [[0, 0, -1], [0, 0, 1], [-1, 0, 0], [1, 0, 0]][direction as usize - 2];
let x = fx
+ 0.5
+ if step[0] == 0 {
0.5 - r.next_double()
} else {
f64::from(step[0]) * 0.6
};
let z = fz
+ 0.5
+ if step[2] == 0 {
0.5 - r.next_double()
} else {
f64::from(step[2]) * 0.6
};
let ya = f64::from(r.next_float() * 0.04);
engine.add(
&crate::particles::ParticleOptions::sculk_to_redstone(),
[x, fy + 0.25, z],
[0.0, ya, 0.0],
);
}
}
Animate::RespawnAnchor => {
let r = engine.random();
if next_int(r, 100) == 0 {
@@ -317,6 +317,15 @@ pub fn build() -> Dispatcher {
let a = d.argument(b, "biome", ArgType::Resource(Resource::Biome));
d.executes(a, "locate.biome");
// warden_spawn_tracker (clear | set <warning_level>)
let tracker = d.literal(root, "warden_spawn_tracker");
d.requires(tracker, GAMEMASTERS);
let clear = d.literal(tracker, "clear");
d.executes(clear, "warden_spawn_tracker.clear");
let set = d.literal(tracker, "set");
let level = d.argument(set, "warning_level", ArgType::Integer { min: 0, max: 4 });
d.executes(level, "warden_spawn_tracker.set");
// say / me / msg / list
let say = d.literal(root, "say");
d.requires(say, GAMEMASTERS);
+9
View File
@@ -58,6 +58,8 @@ pub enum BlockEntity {
Beacon(Box<Beacon>),
/// `LecternBlockEntity`: the book and the open page.
Lectern(Lectern),
/// Sculk sensors, shriekers and catalysts (`crate::sculk`).
Sculk(Box<crate::sculk::SculkEntity>),
/// `CreakingHeartBlockEntity`: its protector and the hurt emitter.
CreakingHeart(Box<CreakingHeart>),
/// `BannerBlockEntity`: the pattern layers.
@@ -178,6 +180,9 @@ impl BlockEntity {
if name == "minecraft:lectern" {
return Some(Self::Lectern(Lectern::default()));
}
if let Some(sculk) = crate::sculk::SculkEntity::for_block(name) {
return Some(Self::Sculk(Box::new(sculk)));
}
if name == "minecraft:crafter" {
return Some(Self::Crafter(Crafter::default()));
}
@@ -236,6 +241,7 @@ impl BlockEntity {
Self::Jukebox(_) => "minecraft:jukebox",
Self::Beacon(_) => "minecraft:beacon",
Self::Lectern(_) => "minecraft:lectern",
Self::Sculk(s) => s.id(),
Self::Banner(_) => "minecraft:banner",
Self::Crafter(_) => "minecraft:crafter",
Self::CreakingHeart(_) => "minecraft:creaking_heart",
@@ -250,6 +256,7 @@ impl BlockEntity {
Self::Jukebox(j) => j.record.iter().cloned().collect(),
Self::Beacon(_) | Self::CreakingHeart(_) => Vec::new(),
Self::Lectern(l) => l.book.iter().cloned().collect(),
Self::Sculk(_) => Vec::new(),
Self::Banner(_) => Vec::new(),
Self::Crafter(c) => c.items.iter().flatten().cloned().collect(),
}
@@ -263,6 +270,7 @@ impl BlockEntity {
| Self::Jukebox(_)
| Self::Beacon(_)
| Self::Lectern(_)
| Self::Sculk(_)
| Self::Banner(_) => &[],
Self::Crafter(c) => &c.items,
Self::CreakingHeart(_) => &[],
@@ -277,6 +285,7 @@ impl BlockEntity {
| Self::Jukebox(_)
| Self::Beacon(_)
| Self::Lectern(_)
| Self::Sculk(_)
| Self::Banner(_) => &mut [],
Self::Crafter(c) => &mut c.items,
Self::CreakingHeart(_) => &mut [],
+16
View File
@@ -339,6 +339,15 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
"minecraft:wither" => {
map.insert("Invul".into(), Tag::Int(m.extra.counter));
}
"minecraft:warden" => {
if let Some(st) = &m.extra.warden {
map.insert("listener".into(), st.vibration.to_nbt());
map.insert(
"anger".into(),
Tag::compound([("suspects", Tag::List(Vec::new()))]),
);
}
}
"minecraft:ravager" => {
map.insert("AttackTick".into(), Tag::Int(m.extra.counter));
map.insert("StunTick".into(), Tag::Int(m.extra.counter2));
@@ -620,6 +629,13 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
if m.species() == crate::mobs::Species::Wither {
m.extra.counter = number(tag.get("Invul")).unwrap_or(0) as i32;
}
if m.species() == crate::mobs::Species::Warden {
// The brain starts afresh: a minute before it digs back down.
crate::mobs::warden::finalize(&mut m, false, &mut Vec::new());
if let (Some(st), Some(listener)) = (m.extra.warden.as_mut(), tag.get("listener")) {
st.vibration = crate::sculk::Data::from_nbt(listener);
}
}
if m.species() == crate::mobs::Species::Ravager {
m.extra.counter = number(tag.get("AttackTick")).unwrap_or(0) as i32;
m.extra.counter2 = number(tag.get("StunTick")).unwrap_or(0) as i32;
+15
View File
@@ -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<f32>,
}
/// `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]
+54 -5
View File
@@ -57,6 +57,7 @@ mod render_control;
mod render_tick;
mod scoreboard;
mod screens;
mod sculk;
mod shield;
mod sign_edit;
mod station_control;
@@ -312,14 +313,17 @@ impl LevelAccess for GameLevel<'_> {
fn block_entity_analog_signal(
&self,
pos: BlockPos,
_state: BlockStateId,
state: BlockStateId,
_direction: Direction,
) -> i32 {
if let Some(signal) = sculk::sensor_signal(self.world, self.behaviours, state, pos) {
return signal;
}
if let Some((_, comparator)) = jukebox::jukebox_signals(self.world, self.items, pos) {
return comparator;
}
if let Some(signal) = creaking::heart_signal(self.world, pos) {
return if self.registry.state(_state).is_some_and(|s| {
return if self.registry.state(state).is_some_and(|s| {
s.properties
.get("creaking_heart_state")
.is_some_and(|v| v == "uprooted")
@@ -541,6 +545,7 @@ struct Game<'a> {
mobs: Vec<Mob>,
arrows: Vec<Arrow>,
creatures: creatures::Creatures,
sculk: sculk::SculkState,
raiding: raids::Raiding,
attack_ticks: u32,
last_hurt_by_player: HashSet<u32>,
@@ -1266,6 +1271,12 @@ impl Game<'_> {
sounds.pitch * 0.8,
);
}
LevelEvent::LevelEvent {
id: 3006,
pos,
data,
} => self.sculk_charge_event(pos, data),
LevelEvent::LevelEvent { id: 3007, pos, .. } => self.shriek_event(pos),
LevelEvent::LevelEvent { id, pos, .. } => {
let c = Some([
f64::from(pos.x) + 0.5,
@@ -1415,10 +1426,17 @@ impl Game<'_> {
},
);
}
LevelEvent::GameEvent { pos, event, state } => {
self.sculk_level_event(pos, event, state)
}
LevelEvent::BlockEvent {
pos,
state,
kind: "shrieker_respond",
} => self.shrieker_block_event(pos, state),
LevelEvent::GrowTree { .. }
| LevelEvent::PlaceFeature { .. }
| LevelEvent::BlockEvent { .. }
| LevelEvent::GameEvent { .. } => {}
| LevelEvent::BlockEvent { .. } => {}
}
}
Ok(())
@@ -1455,6 +1473,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",
@@ -1576,6 +1600,9 @@ impl Game<'_> {
self.process_level_events()
}
fn break_block(&mut self, pos: [i32; 3]) -> Result<()> {
self.with_player_actor(|game| game.break_block_as_player(pos))
}
fn break_block_as_player(&mut self, pos: [i32; 3]) -> Result<()> {
let state = self.world.block(pos[0], pos[1], pos[2]);
let facts = self.res.facts.get(state).clone();
// Block.playerWillDestroy: mining their gold angers all nearby piglins.
@@ -1673,6 +1700,9 @@ impl Game<'_> {
Ok(())
}
fn use_item(&mut self) -> Result<()> {
self.with_player_actor(|game| game.use_item_as_player())
}
fn use_item_as_player(&mut self) -> Result<()> {
// Spectators only look (MultiPlayerGameMode.useItemOn/useItem pass).
if self.spectator() {
return Ok(());
@@ -1984,6 +2014,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()
{
@@ -2532,6 +2564,7 @@ impl Game<'_> {
}
if running {
self.tick_block_entities()?;
self.tick_sculk()?;
self.tick_brewing_stands()?;
}
if let Some(r) = &self.renderer {
@@ -3113,6 +3146,7 @@ impl Game<'_> {
| BlockEntity::Jukebox(_)
| BlockEntity::Beacon(_)
| BlockEntity::Lectern(_)
| BlockEntity::Sculk(_)
| BlockEntity::Banner(_)
| BlockEntity::CreakingHeart(_),
) => {}
@@ -3313,6 +3347,7 @@ impl Game<'_> {
| BlockEntity::Jukebox(_)
| BlockEntity::Beacon(_)
| BlockEntity::Lectern(_)
| BlockEntity::Sculk(_)
| BlockEntity::Banner(_)
| BlockEntity::CreakingHeart(_),
) => {}
@@ -3405,6 +3440,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
@@ -5778,6 +5819,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);
@@ -6685,6 +6727,7 @@ impl Game<'_> {
self.save_scoreboard();
self.save_bossbars();
self.save_schedule();
self.save_warden_tracker();
self.sync_level();
self.level.write(&self.world_root)?;
self.save_world_state();
@@ -6796,7 +6839,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()
@@ -6875,6 +6922,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)
}
@@ -7725,6 +7773,7 @@ pub fn run() -> Result<()> {
mobs: Vec::new(),
arrows: Vec::new(),
creatures: Default::default(),
sculk: Default::default(),
raiding: Default::default(),
attack_ticks: 100,
last_hurt_by_player: HashSet::new(),
@@ -563,6 +563,11 @@ impl Game<'_> {
self.cmd_scoreboard(id, ctx)
}
"locate.structure" | "locate.biome" => self.cmd_locate(id, ctx),
"warden_spawn_tracker.clear" | "warden_spawn_tracker.set" => {
let level = Self::int(ctx, "warning_level");
self.cmd_warden_spawn_tracker(level);
Ok(1)
}
"say" | "me" | "msg" => self.cmd_say(id, ctx),
"list" => {
let names = if ctx.has("uuids") {
@@ -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::<Vec<_>>() }))),
"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]))?;
+26 -2
View File
@@ -293,6 +293,7 @@ impl Game<'_> {
"on_ground": m.on_ground,
"variant": m.extra.variant,
"color": m.extra.color,
"warden": horizon_client::mobs::warden::describe(m),
"villager": horizon_client::mobs::villager::ext(m).map(|e| serde_json::json!({
"food_level": e.food_level,
"inventory": e.inventory.iter().map(|s| format!("{}x{}", s.count, s.item)).collect::<Vec<_>>(),
@@ -694,6 +695,17 @@ impl Game<'_> {
/// LivingEntity.die / dropAllDeathLoot.
fn mob_died(&mut self, m: &Mob) {
let by_player = self.last_hurt_by_player.remove(&m.id) || m.ai.last_hurt_by_player > 0;
// LivingEntity.die: the death is heard, and a sculk catalyst nearby
// takes the experience.
self.sculk_mob_died(m);
let consumed =
self.catalyst_takes_experience([m.position.x, m.position.y, m.position.z], |game| {
if by_player {
experience_reward(m, &mut game.world.random)
} else {
0
}
});
if by_player {
self.stats.add("killed", &m.kind.id, 1);
self.stats.custom("mob_kills", 1);
@@ -785,7 +797,7 @@ impl Game<'_> {
}
}
}
if by_player {
if by_player && !consumed {
let xp = experience_reward(m, &mut self.world.random);
if xp > 0 {
self.spawn_orbs(pos, xp);
@@ -928,7 +940,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;
@@ -1035,6 +1051,11 @@ impl Game<'_> {
}
},
MobEvent::Breed { parent, partner } => self.breed(parent, partner),
MobEvent::Vibration { from, to, ticks } => {
self.mob_vibration_particle(from, to, ticks)
}
MobEvent::DigParticles { at } => self.warden_dig_particles(at),
MobEvent::Darkness { at, radius } => self.apply_darkness(at, radius),
MobEvent::CreakingHurt {
home,
by_player,
@@ -1439,6 +1460,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 { .. } => {
@@ -2168,6 +2191,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",
@@ -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 {
@@ -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)
@@ -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;
@@ -170,6 +170,7 @@ impl Game<'_> {
return true;
}
self.using = None;
self.post_entity_event("minecraft:drink", horizon_client::mobs::Who::Player);
if ominous {
self.drink_ominous_bottle(slot, stack);
return true;
@@ -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.
File diff suppressed because it is too large Load Diff
+3
View File
@@ -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(
@@ -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);
}
+8 -1
View File
@@ -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());
+1
View File
@@ -67,6 +67,7 @@ pub mod save;
pub mod scoreboard;
pub mod scoreboard_cmd;
pub mod screen_effects;
pub mod sculk;
pub mod settings;
pub mod shadows;
pub mod signs;
+20
View File
@@ -39,6 +39,7 @@ pub mod tame;
pub mod undead;
pub mod vex;
pub mod villager;
pub mod warden;
pub mod witch;
pub mod wither;
mod world;
@@ -338,6 +339,7 @@ pub enum DamageKind {
Generic,
InWall,
Thorns,
SonicBoom,
}
/// A damage source: its type, the attacking entity and where it came from.
#[derive(Clone, Copy, Debug)]
@@ -392,6 +394,7 @@ impl Damage {
| DamageKind::Magic
| DamageKind::InWall
| DamageKind::Generic
| DamageKind::SonicBoom
)
}
pub fn is_fire(&self) -> bool {
@@ -479,6 +482,8 @@ pub struct Extra {
pub meeting: Option<[i32; 3]>,
/// Villager and wandering trader offers and experience.
pub trade: Option<Box<crate::merchant::Trader>>,
/// A warden's brain, anger and vibrations.
pub warden: Option<Box<warden::Warden>>,
/// A raider's patrol and raid state.
pub raider: Option<Box<raider::State>>,
/// A villager's raid activity and gossip.
@@ -716,6 +721,21 @@ pub enum MobEvent {
table: &'static str,
at: [f64; 3],
},
/// A vibration travelling to a listener (`VibrationParticleOption`).
Vibration {
from: [f64; 3],
to: [f64; 3],
ticks: i32,
},
/// The crumbs of the block under a digging or emerging warden.
DigParticles {
at: [f64; 3],
},
/// `Warden.applyDarknessAround`: darkness for survival players nearby.
Darkness {
at: [f64; 3],
radius: f64,
},
/// A creaking bound to the heart at `home` was hurt (`creakingHurt` when a player did it).
CreakingHurt {
home: [i32; 3],
+15 -1
View File
@@ -87,6 +87,7 @@ pub enum Family {
Wither,
Allay,
Villager,
Warden,
Creaking,
}
pub fn family(s: Species) -> Family {
@@ -132,6 +133,7 @@ pub fn family(s: Species) -> Family {
S::Enderman => Family::Enderman,
S::Slime | S::MagmaCube => Family::Cube,
S::Guardian | S::ElderGuardian => Family::Guardian,
S::Warden => Family::Warden,
S::Shulker => Family::Shulker,
_ => Family::Generic,
}
@@ -171,6 +173,7 @@ pub fn register(m: &mut Mob) {
Family::Wither => super::wither::register(m),
Family::Allay => super::allay::register(m),
Family::Villager => super::villager::register(m),
Family::Warden => super::warden::register(m),
Family::Creaking => super::creaking::register(m),
}
super::raider::register(m);
@@ -381,6 +384,11 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
}
fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
let sound = match m.species() {
// Warden.getAmbientSound: by anger, silent while roaring or digging.
Species::Warden => match super::warden::ambient_sound(m) {
Some(sound) => sound,
None => return,
},
Species::Zombie | Species::Husk if m.is_baby() => m.kind.sounds[0],
Species::Drowned if m.fluids.in_water => "entity.drowned.ambient_water",
Species::Enderman if m.ai.target.is_some() => "entity.enderman.scream",
@@ -551,6 +559,7 @@ fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) {
Species::Enderman => super::enderman::custom_server_ai_step(m, cx),
Species::Blaze => super::nether::blaze_server_ai_step(m, cx),
Species::ElderGuardian => super::guardian::elder_server_ai_step(m, cx),
Species::Warden => super::warden::server_ai_step(m, cx),
// SpellcasterIllager.customServerAiStep.
Species::Evoker if m.extra.counter > 0 => m.extra.counter -= 1,
_ => {}
@@ -578,6 +587,7 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
Species::Zoglin if m.extra.anim_ticks > 0 => m.extra.anim_ticks -= 1,
s if super::equine::is_equine(s) => super::equine::ai_step(m, w, events),
Species::Phantom => super::phantom::flap_sound(m, events),
Species::Warden => super::warden::ai_step(m, events),
Species::Guardian | Species::ElderGuardian => super::guardian::ai_step(m, w, events),
Species::Vex => super::vex::ai_step(m, w),
Species::Ravager => super::ravager::ai_step(m, w, events),
@@ -600,7 +610,8 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
/// 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;
}
@@ -648,6 +659,7 @@ pub fn speed_bonus(m: &Mob) -> f64 {
pub fn sound_volume(m: &Mob) -> f32 {
match m.species() {
Species::Ghast => 5.0,
Species::Warden => 4.0,
Species::Slime | Species::MagmaCube => 0.4 * m.extra.size.max(1) as f32,
Species::Cod
| Species::Salmon
@@ -689,6 +701,7 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage, _amount: f32) -> bool {
Species::Allay if m.extra.tame && source.attacker == Some(Who::Player) => false,
Species::Creaking => super::creaking::accepts_damage(m, source),
Species::Wither => super::wither::accepts(m, source.kind, source.attacker, false),
Species::Warden => super::warden::accepts_damage(m, source),
Species::Shulker => super::shulker::accepts(m, source),
Species::Enderman => super::enderman::on_damage(m, source),
Species::WitherSkeleton | Species::Blaze | Species::MagmaCube | Species::Strider
@@ -705,6 +718,7 @@ pub fn after_hurt(m: &mut Mob, source: &Damage) {
match m.species() {
Species::Enderman => super::enderman::after_hurt(m, source),
Species::Shulker => super::shulker::after_hurt(m),
Species::Warden => super::warden::hurt(m, source),
Species::Wolf => super::tame::after_hurt(m, source),
// NeutralMob: an iron golem hit by the player stays angry a while.
// PiglinAi.wasHurtBy: drop what is being admired, no admiring for
+2
View File
@@ -8,6 +8,7 @@ use std::f32::consts::PI;
/// The setupAnim implementation a model uses.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Anim {
Warden,
Allay,
Creaking,
Camel,
@@ -346,6 +347,7 @@ pub fn setup(
) {
match m.kind.anim {
Anim::Camel => super::camel::anim(m, s, p, w_anims),
Anim::Warden => super::warden::anim(m, s, p, w_anims),
Anim::Allay => super::allay::anim(m, s, p),
Anim::Creaking => super::creaking::anim(m, s, p, w_anims),
Anim::Squid | Anim::Fish | Anim::Pufferfish | Anim::Dolphin => {
+5
View File
@@ -99,6 +99,11 @@ impl Mob {
super::species::Baby::None => {}
}
}
// Warden.getDefaultDimensions: a metre tall while digging or emerging.
if self.kind.species == super::Species::Warden && super::warden::digging_or_emerging(self) {
h = 1.0;
e = 0.85;
}
if self.kind.species == super::Species::Pufferfish {
let s = super::aquatic::puff_scale(self.extra.size);
(w, h, e) = (w * s, h * s, e * s);
+15 -1
View File
@@ -774,7 +774,21 @@ pub fn render_with(
draw(part, base, &poses, *uv, *color, light, overlay, out);
}
held_items(m, &model, base, &poses, atlas, light, out);
for layer in layers(m) {
let mut all_layers = layers(m);
// WardenRenderer: the translucent emissive layers fade with the animations.
if m.species() == Species::Warden {
for (model, texture, a) in super::warden::emissive_layers(m, alpha) {
if a > 0.0 {
all_layers.push(Layer {
model: model.into(),
texture: texture.into(),
color: ((a.clamp(0.0, 1.0) * 255.0) as u32) << 24 | 0x00FF_FFFF,
full_bright: true,
});
}
}
}
for layer in all_layers {
let Some(part) = m.kind.layer(&layer.model).cloned() else {
continue;
};
@@ -292,6 +292,8 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) {
Climate::Cold => 2,
};
match m.species() {
// Warden.finalizeSpawn: a minute before it digs back down.
S::Warden => super::warden::finalize(m, false, &mut Vec::new()),
S::Pig | S::Cow | S::Chicken => m.extra.variant = climate_index,
S::Sheep => m.extra.color = super::farm::sheep_color(biome.climate, &mut m.random),
S::Mooshroom => m.extra.variant = 0,
+16
View File
@@ -83,6 +83,7 @@ pub enum Species {
Wither,
Camel,
Allay,
Warden,
Creaking,
}
/// Baby bounding boxes (each class's BABY_DIMENSIONS).
@@ -1163,6 +1164,20 @@ pub const ALL: &[Def] = &[
Some("entity.strider.step"),
Baby::Abs(0.45, 0.85, 0.4375)
),
def!(
Warden,
"warden",
"warden#main",
"entity/warden/warden",
A::Warden,
[
"entity.warden.ambient",
"entity.warden.hurt",
"entity.warden.death"
],
None,
Baby::None
),
];
pub fn def(s: Species) -> &'static Def {
ALL.iter().find(|d| d.species == s).unwrap_or(&ALL[0])
@@ -1371,6 +1386,7 @@ impl Def {
| S::Vex
| S::Ravager
| S::Wither
| S::Warden
)
}
/// The item tag Animal.isFood tests.
File diff suppressed because it is too large Load Diff
+267 -17
View File
@@ -120,6 +120,12 @@ particle_types! {
Soul = "soul",
SculkSoul = "sculk_soul",
DragonBreath = "dragon_breath",
DustColorTransition = "dust_color_transition",
SculkCharge = "sculk_charge",
SculkChargePop = "sculk_charge_pop",
Shriek = "shriek",
SonicBoom = "sonic_boom",
Vibration = "vibration",
}
impl ParticleType {
/// `ParticleType.getOverrideLimiter`: spawned regardless of distance.
@@ -139,8 +145,11 @@ pub struct ParticleOptions {
pub block: Option<(String, u32)>,
/// RGB(A) for dust, spells, entity effects and tinted leaves.
pub color: [f32; 4],
/// `DustParticleOptions.scale`, `PowerParticleOption.power`, `SpellParticleOption.power`.
/// `DustParticleOptions.scale`, `PowerParticleOption.power`, `SpellParticleOption.power`,
/// `SculkChargeParticleOptions.roll`, `ShriekParticleOption.delay`.
pub scale: f32,
/// `DustColorTransitionOptions.toColor` (`color` is the from colour).
pub to_color: [f32; 3],
/// `TrailParticleOption`: the point it flies to and how many ticks it takes.
pub trail: Option<([f64; 3], i32)>,
}
@@ -151,9 +160,44 @@ impl ParticleOptions {
block: None,
color: [1.0; 4],
scale: 1.0,
to_color: [1.0, 0.0, 0.0],
trail: None,
}
}
/// `DustColorTransitionOptions`.
pub fn dust_transition(from: [f32; 3], to: [f32; 3], scale: f32) -> Self {
Self {
color: [from[0], from[1], from[2], 1.0],
to_color: to,
scale: scale.clamp(0.01, 4.0),
..Self::simple(ParticleType::DustColorTransition)
}
}
/// `DustColorTransitionOptions.SCULK_TO_REDSTONE`.
pub fn sculk_to_redstone() -> Self {
let rgb = |c: u32| {
[
((c >> 16) & 255) as f32 / 255.0,
((c >> 8) & 255) as f32 / 255.0,
(c & 255) as f32 / 255.0,
]
};
Self::dust_transition(rgb(3_790_560), rgb(16_711_680), 1.0)
}
/// `SculkChargeParticleOptions(roll)`.
pub fn sculk_charge(roll: f32) -> Self {
Self {
scale: roll,
..Self::simple(ParticleType::SculkCharge)
}
}
/// `ShriekParticleOption(delay)`.
pub fn shriek(delay: i32) -> Self {
Self {
scale: delay as f32,
..Self::simple(ParticleType::Shriek)
}
}
/// `TrailParticleOption(target, color, duration)`.
pub fn trail(target: [f64; 3], rgb: u32, duration: i32) -> Self {
Self {
@@ -205,6 +249,8 @@ enum Size {
Lava,
Portal,
ReversePortal,
/// `ShriekParticle.getQuadSize`.
Shriek,
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Light {
@@ -278,6 +324,23 @@ enum Behaviour {
DragonBreath {
hit_ground: bool,
},
/// `ShriekParticle`: waits `delay` ticks, then rises.
Shriek {
delay: i32,
},
/// `VibrationSignalParticle`: flies to a listener.
Vibration {
dest: [f64; 3],
rot: f32,
rot_o: f32,
pitch: f32,
pitch_o: f32,
},
/// `DustColorTransitionParticle`: from one colour to the other.
Transition {
from: [f32; 3],
to: [f32; 3],
},
/// `TrailParticle`: eases towards its target over its lifetime.
Trail {
target: [f64; 3],
@@ -532,6 +595,7 @@ impl Particle {
Size::ReversePortal => {
self.size * (1.0 - (self.age as f32 + a) / (self.lifetime as f32 * 1.5))
}
Size::Shriek => self.size * (t * 0.75).clamp(0.0, 1.0),
}
}
}
@@ -676,6 +740,27 @@ impl ParticleEngine {
self.particles.clear();
self.pending.clear();
}
/// A vibration signal flying from `from` to `to` in `ticks`
/// (`VibrationParticleOption`).
pub fn vibration(&mut self, from: [f64; 3], to: [f64; 3], ticks: i32) {
let mut q = Particle::blank(ParticleType::Vibration, from);
q.size = 0.3;
q.lifetime = ticks;
q.has_physics = false;
q.light = Light::Block15;
q.set = self.set_of(ParticleType::Vibration);
let d = [from[0] - to[0], from[1] - to[1], from[2] - to[2]];
let rot = d[0].atan2(d[2]) as f32;
let pitch = d[1].atan2((d[0] * d[0] + d[2] * d[2]).sqrt()) as f32;
q.behaviour = Behaviour::Vibration {
dest: to,
rot,
rot_o: rot,
pitch,
pitch_o: pitch,
};
self.pending.push(q);
}
/// `ParticleEngine.add` (via `particlesToAdd`, applied on the next tick).
pub fn push(&mut self, particle: Particle) {
self.pending.push(particle);
@@ -1432,12 +1517,17 @@ impl ParticleEngine {
q.set = set;
q
}
T::Explosion => {
T::Explosion | T::SonicBoom => {
let mut q = Particle::moving(r, ty, p, [0.0; 3]);
q.lifetime = 6 + r.next_int_bound(4).unwrap_or(0);
let col = r.next_float() * 0.6 + 0.4;
q.set_color(col, col, col);
q.size = 2.0 * (1.0 - v[0] as f32 * 0.5);
if ty == T::SonicBoom {
// SonicBoomParticle.
q.lifetime = 16;
q.size = 1.5;
}
q.light = Light::FullBright;
q.behaviour = Behaviour::HugeExplosion;
q.set = set;
@@ -1491,6 +1581,69 @@ impl ParticleEngine {
q.size_curve = Size::GrowIn;
q
}
T::DustColorTransition => {
let mut q = Particle::moving(r, ty, p, v);
q.friction = 0.96;
q.speed_up_when_y_blocked = true;
for c in &mut q.velocity {
*c *= f64::from(0.1f32);
}
q.size *= 0.75 * o.scale;
let base = (8.0 / (r.next_double() * 0.8 + 0.2)) as i32;
q.lifetime = ((base as f32 * o.scale).max(1.0)) as i32;
let factor = r.next_float() * 0.4 + 0.6;
let mut randomize = |c: f32| (r.next_float() * 0.2 + 0.8) * c * factor;
let from = [
randomize(o.color[0]),
randomize(o.color[1]),
randomize(o.color[2]),
];
let to = [
randomize(o.to_color[0]),
randomize(o.to_color[1]),
randomize(o.to_color[2]),
];
q.size_curve = Size::GrowIn;
q.behaviour = Behaviour::Transition { from, to };
q.set = set;
q
}
// SculkChargeParticle / SculkChargePopParticle.
T::SculkCharge | T::SculkChargePop => {
let mut q = Particle::moving(r, ty, p, v);
q.friction = 0.96;
q.scale(if ty == T::SculkCharge { 1.5 } else { 1.0 });
q.has_physics = false;
q.velocity = v;
q.light = Light::Block15;
q.behaviour = Behaviour::Animated;
q.set = set;
if ty == T::SculkCharge {
q.roll = o.scale;
q.o_roll = o.scale;
q.lifetime = r.next_int_bound(12).unwrap_or(0) + 8;
} else {
q.lifetime = r.next_int_bound(4).unwrap_or(0) + 6;
}
q
}
// Vibration signals are created by `vibration`, aimed at a listener.
T::Vibration => return None,
// ShriekParticle.
T::Shriek => {
let mut q = Particle::moving(r, ty, p, [0.0; 3]);
q.size = 0.85;
q.lifetime = 30;
q.gravity = 0.0;
q.velocity = [0.0, 0.1, 0.0];
q.light = Light::Block15;
q.size_curve = Size::Shriek;
q.behaviour = Behaviour::Shriek {
delay: o.scale as i32,
};
q.set = set;
q
}
T::Dust => {
let mut q = Particle::moving(r, ty, p, v);
q.friction = 0.96;
@@ -2185,6 +2338,49 @@ impl ParticleEngine {
start[2] + p.velocity[2] * f64::from(pos),
];
}
Behaviour::Transition { .. } => {
p.base_tick(level);
self.sprite_from_age(p);
}
Behaviour::Shriek { delay } => {
if delay > 0 {
p.behaviour = Behaviour::Shriek { delay: delay - 1 };
} else {
p.base_tick(level);
self.sprite_from_age(p);
}
}
Behaviour::Vibration {
dest, rot, pitch, ..
} => {
p.previous = p.position;
let age = p.age;
p.age += 1;
if age >= p.lifetime {
p.removed = true;
return;
}
let remaining = p.lifetime - p.age;
if remaining > 0 {
let alpha = 1.0 / f64::from(remaining);
for i in 0..3 {
p.position[i] += (dest[i] - p.position[i]) * alpha;
}
}
let d = [
p.position[0] - dest[0],
p.position[1] - dest[1],
p.position[2] - dest[2],
];
p.behaviour = Behaviour::Vibration {
dest,
rot: d[0].atan2(d[2]) as f32,
rot_o: rot,
pitch: d[1].atan2((d[0] * d[0] + d[2] * d[2]).sqrt()) as f32,
pitch_o: pitch,
};
self.sprite_from_age(p);
}
Behaviour::Trail { target } => {
p.previous = p.position;
let age = p.age;
@@ -2455,6 +2651,58 @@ impl ParticleEngine {
if let Behaviour::FlyTowards { alpha: la, .. } = p.behaviour {
alpha = lifetime_alpha(la, p.age, p.lifetime, partial);
}
let mut rotations = [Some(rotation), None];
let mut rgb = [p.rgba[0], p.rgba[1], p.rgba[2]];
match p.behaviour {
// ShriekParticle.extract: two tilted quads, fading out.
Behaviour::Shriek { delay } => {
if delay > 0 {
continue;
}
alpha = 1.0 - ((p.age as f32 + partial) / p.lifetime as f32).clamp(0.0, 1.0);
rotations = [
Some(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_3)),
Some(Quat::from_euler(
glam::EulerRot::YXZ,
-std::f32::consts::PI,
std::f32::consts::FRAC_PI_3,
0.0,
)),
];
}
// VibrationSignalParticle.extract: two quads along the flight.
Behaviour::Vibration {
rot,
rot_o,
pitch,
pitch_o,
..
} => {
let sway =
((p.age as f32 + partial - std::f32::consts::TAU) * 0.05).sin() * 2.0;
let lerped_rot = rot_o + (rot - rot_o) * partial;
let lerped_pitch =
pitch_o + (pitch - pitch_o) * partial + std::f32::consts::FRAC_PI_2;
rotations = [
Some(
Quat::from_rotation_y(lerped_rot)
* Quat::from_rotation_x(-lerped_pitch)
* Quat::from_rotation_y(sway),
),
Some(
Quat::from_rotation_y(-std::f32::consts::PI + lerped_rot)
* Quat::from_rotation_x(lerped_pitch)
* Quat::from_rotation_y(sway),
),
];
}
// DustColorTransitionParticle.lerpColors.
Behaviour::Transition { from, to } => {
let t = (p.age as f32 + partial) / (p.lifetime as f32 + 1.0);
rgb = std::array::from_fn(|i| from[i] + (to[i] - from[i]) * t);
}
_ => {}
}
let block = ParticleLevel::block_at(p.position);
let packed = light_at(block);
let (sky, mut block_light) = (u32::from(packed >> 4) * 16, u32::from(packed & 15) * 16);
@@ -2476,7 +2724,7 @@ impl ParticleEngine {
}
let light = sky_light | block_light << 8;
let c = |v: f32| (v.clamp(0.0, 1.0) * 255.0) as u32;
let color = c(alpha) << 24 | c(p.rgba[2]) << 16 | c(p.rgba[1]) << 8 | c(p.rgba[0]);
let color = c(alpha) << 24 | c(rgb[2]) << 16 | c(rgb[1]) << 8 | c(rgb[0]);
let (du, dv) = (r.u1 - r.u0, r.v1 - r.v0);
let (u0, v0, u1, v1) = (
r.u0 + du * p.uv[0],
@@ -2484,20 +2732,22 @@ impl ParticleEngine {
r.u0 + du * p.uv[2],
r.v0 + dv * p.uv[3],
);
for (n, uv) in [
((1.0, -1.0), [u1, v1]),
((1.0, 1.0), [u1, v0]),
((-1.0, 1.0), [u0, v0]),
((-1.0, -1.0), [u0, v1]),
] {
let v = center + rotation * FVec3::new(n.0, n.1, 0.0) * size;
out.push(Vertex {
pos: v.to_array(),
uv,
layer: 0,
color,
light,
});
for rotation in rotations.into_iter().flatten() {
for (n, uv) in [
((1.0, -1.0), [u1, v1]),
((1.0, 1.0), [u1, v0]),
((-1.0, 1.0), [u0, v0]),
((-1.0, -1.0), [u0, v1]),
] {
let v = center + rotation * FVec3::new(n.0, n.1, 0.0) * size;
out.push(Vertex {
pos: v.to_array(),
uv,
layer: 0,
color,
light,
});
}
}
}
}
+2
View File
@@ -404,6 +404,7 @@ pub fn encode_block_entity(
entries.push(("Page", Tag::Int(l.page)));
}
}
BlockEntity::Sculk(s) => entries.extend(s.to_nbt()),
BlockEntity::Crafter(c) => {
entries.push(("Items", encode_items(&c.items)));
entries.push((
@@ -521,6 +522,7 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain
};
}
BlockEntity::Sign(sign) => sign.decode(tag),
BlockEntity::Sculk(s) => s.load(tag),
BlockEntity::Crafter(c) => {
for (slot, item) in decode_items(tag.get("Items"), 9).into_iter().enumerate() {
c.items[slot] = item;
+887
View File
@@ -0,0 +1,887 @@
//! Game events and the vibration system (`GameEvent`, `VibrationSystem`,
//! `VibrationSelector`) shared by sculk sensors, shriekers and wardens, the
//! sculk block entities and the per-player warden spawn tracker.
use crate::mobs::Who;
use horizon_core::{
geometry::{Direction, Vec3, traverse_blocks},
position::BlockPos,
};
use horizon_world::{level::sculk::SculkSpreader, nbt::Tag};
/// Every `GameEvent` with its `VibrationSystem` frequency (0: none).
const EVENTS: &[(&str, i32)] = &[
("minecraft:step", 1),
("minecraft:swim", 1),
("minecraft:flap", 1),
("minecraft:projectile_land", 2),
("minecraft:hit_ground", 2),
("minecraft:splash", 2),
("minecraft:bounce", 2),
("minecraft:item_interact_finish", 3),
("minecraft:projectile_shoot", 3),
("minecraft:instrument_play", 3),
("minecraft:entity_action", 4),
("minecraft:elytra_glide", 4),
("minecraft:unequip", 4),
("minecraft:entity_dismount", 5),
("minecraft:equip", 5),
("minecraft:entity_interact", 6),
("minecraft:shear", 6),
("minecraft:entity_mount", 6),
("minecraft:entity_damage", 7),
("minecraft:drink", 8),
("minecraft:eat", 8),
("minecraft:container_close", 9),
("minecraft:block_close", 9),
("minecraft:block_deactivate", 9),
("minecraft:block_detach", 9),
("minecraft:container_open", 10),
("minecraft:block_open", 10),
("minecraft:block_activate", 10),
("minecraft:block_attach", 10),
("minecraft:prime_fuse", 10),
("minecraft:note_block_play", 10),
("minecraft:block_change", 11),
("minecraft:block_destroy", 12),
("minecraft:fluid_pickup", 12),
("minecraft:block_place", 13),
("minecraft:fluid_place", 13),
("minecraft:entity_place", 14),
("minecraft:lightning_strike", 14),
("minecraft:teleport", 14),
("minecraft:entity_die", 15),
("minecraft:explode", 15),
// Events that exist but make no vibration frequency.
("minecraft:item_interact_start", 0),
("minecraft:jukebox_play", 0),
("minecraft:jukebox_stop_play", 0),
("minecraft:sculk_sensor_tendrils_clicking", 0),
("minecraft:shriek", 0),
];
/// `GameEvent.RESONATE_1..15`.
pub const RESONANCE: [&str; 15] = [
"minecraft:resonate_1",
"minecraft:resonate_2",
"minecraft:resonate_3",
"minecraft:resonate_4",
"minecraft:resonate_5",
"minecraft:resonate_6",
"minecraft:resonate_7",
"minecraft:resonate_8",
"minecraft:resonate_9",
"minecraft:resonate_10",
"minecraft:resonate_11",
"minecraft:resonate_12",
"minecraft:resonate_13",
"minecraft:resonate_14",
"minecraft:resonate_15",
];
pub const SHRIEK: &str = "minecraft:shriek";
pub const TENDRILS_CLICKING: &str = "minecraft:sculk_sensor_tendrils_clicking";
pub const NO_VIBRATION_FREQUENCY: i32 = 0;
/// `VibrationSystem.getGameEventFrequency`.
pub fn frequency(event: &str) -> i32 {
if let Some(i) = RESONANCE.iter().position(|e| *e == event) {
return i as i32 + 1;
}
EVENTS
.iter()
.find(|(name, _)| *name == event)
.map_or(0, |(_, f)| *f)
}
/// `GameEvent.notificationRadius`.
pub fn notification_radius(event: &str) -> i32 {
match event {
"minecraft:jukebox_play" | "minecraft:jukebox_stop_play" => 10,
SHRIEK => 32,
_ => 16,
}
}
/// The identifier as a `'static` string, for loading saved events.
pub fn intern(event: &str) -> Option<&'static str> {
RESONANCE
.iter()
.chain(EVENTS.iter().map(|(name, _)| name))
.find(|e| **e == event)
.copied()
}
/// `GameEventTags.VIBRATIONS`: every event with a frequency, resonance and flap.
pub fn is_vibration(event: &str) -> bool {
frequency(event) != 0
}
/// `GameEventTags.SHRIEKER_CAN_LISTEN`.
pub fn shrieker_can_listen(event: &str) -> bool {
event == TENDRILS_CLICKING
}
/// `GameEventTags.WARDEN_CAN_LISTEN`: vibrations except flap, plus shrieks and
/// tendril clicks.
pub fn warden_can_listen(event: &str) -> bool {
(is_vibration(event) && event != "minecraft:flap")
|| event == SHRIEK
|| shrieker_can_listen(event)
}
/// `GameEventTags.IGNORE_VIBRATIONS_SNEAKING`.
pub fn ignored_when_sneaking(event: &str) -> bool {
matches!(
event,
"minecraft:hit_ground"
| "minecraft:projectile_shoot"
| "minecraft:step"
| "minecraft:swim"
| "minecraft:item_interact_start"
| "minecraft:item_interact_finish"
)
}
/// `VibrationSystem.getRedstoneStrengthForDistance`.
pub fn redstone_strength(distance: f32, listener_radius: i32) -> i32 {
let scale = 15.0 / f64::from(listener_radius);
(15 - (scale * f64::from(distance)).floor() as i32).max(1)
}
/// `SculkSensorBlock.RESONANCE_PITCH_BEND`: `NoteBlock.getPitchFromNote`.
pub fn resonance_pitch(frequency: i32) -> f32 {
const TONES: [i32; 16] = [0, 0, 2, 4, 6, 7, 9, 10, 12, 14, 15, 18, 19, 21, 22, 24];
2.0f32.powf((TONES[frequency.clamp(0, 15) as usize] - 12) as f32 / 12.0)
}
/// What an event's source looks like to listeners, captured when it is
/// posted (`GameEvent.Context` plus the entity facts listeners ask for).
#[derive(Clone, Copy, Debug, Default)]
pub struct Context {
pub source: Option<Who>,
/// The projectile's owner, when the source is a projectile.
pub owner: Option<Who>,
/// `affectedState` is in `dampens_vibrations`.
pub dampening_state: bool,
/// The source is a spectator.
pub spectator: bool,
/// `isSteppingCarefully` (sneaking).
pub stepping_carefully: bool,
/// `dampensVibrations` (a warden).
pub dampens: bool,
/// The source is a living entity wardens may target.
pub targetable: bool,
/// The source is a living entity at all.
pub living: bool,
/// The source is the player, rides with them, or is their projectile
/// (`SculkShriekerBlockEntity.tryGetPlayer`).
pub player: bool,
}
/// `VibrationSystem.User.isValidVibration` without the tag test.
pub fn valid_vibration(listens: bool, event: &str, ctx: &Context) -> bool {
if !listens {
return false;
}
if ctx.source.is_some() {
if ctx.spectator {
return false;
}
if ctx.stepping_carefully && ignored_when_sneaking(event) {
return false;
}
if ctx.dampens {
return false;
}
}
!ctx.dampening_state
}
/// `VibrationInfo`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Info {
pub event: &'static str,
pub distance: f32,
pub pos: [f64; 3],
pub source: Option<Who>,
pub owner: Option<Who>,
}
/// `VibrationSelector`: the closest, then highest-frequency candidate of a tick.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Selector {
current: Option<(Info, i64)>,
}
impl Selector {
pub fn add_candidate(&mut self, new: Info, tick: i64) {
if self.should_replace(&new, tick) {
self.current = Some((new, tick));
}
}
fn should_replace(&self, new: &Info, tick: i64) -> bool {
let Some((previous, previous_tick)) = &self.current else {
return true;
};
if tick != *previous_tick {
return false;
}
if new.distance < previous.distance {
true
} else if new.distance > previous.distance {
false
} else {
frequency(new.event) > frequency(previous.event)
}
}
pub fn chosen_candidate(&self, time: i64) -> Option<Info> {
self.current
.filter(|(_, tick)| *tick < time)
.map(|(info, _)| info)
}
pub fn start_over(&mut self) {
self.current = None;
}
}
/// `VibrationSystem.Data`.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Data {
pub current: Option<Info>,
pub travel: i32,
pub selector: Selector,
}
/// What one `VibrationSystem.Ticker.tick` did.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Tick {
/// A vibration was chosen: its travel time (the particle starts).
pub started: Option<(Info, i32)>,
/// A vibration arrived.
pub received: Option<Info>,
/// `onDataChanged`.
pub changed: bool,
}
impl Data {
/// `Listener.handleGameEvent` once the user accepted the event.
pub fn schedule(&mut self, info: Info, game_time: i64) {
self.selector.add_candidate(info, game_time);
}
/// `VibrationSystem.Ticker.tick`.
pub fn tick(
&mut self,
game_time: i64,
chunks_ticking: bool,
needs_ticking_chunks: bool,
travel_time: impl Fn(f32) -> i32,
) -> Tick {
let mut out = Tick::default();
if self.current.is_none()
&& let Some(info) = self.selector.chosen_candidate(game_time)
{
self.current = Some(info);
self.travel = travel_time(info.distance);
out.started = Some((info, self.travel));
out.changed = true;
self.selector.start_over();
}
if let Some(info) = self.current {
let mut changed = self.travel > 0;
self.travel = (self.travel - 1).max(0);
if self.travel <= 0 {
if needs_ticking_chunks && !chunks_ticking {
changed = false;
} else {
out.received = Some(info);
self.current = None;
changed = true;
}
}
out.changed |= changed;
}
out
}
/// The `listener` compound (`VibrationSystem.Data.CODEC`).
pub fn to_nbt(&self) -> Tag {
let mut entries: Vec<(&str, Tag)> = Vec::new();
if let Some(info) = &self.current {
entries.push(("event", info_to_nbt(info)));
}
let mut selector: Vec<(&str, Tag)> = Vec::new();
let chosen = self.selector.current;
if let Some((info, _)) = &chosen {
selector.push(("event", info_to_nbt(info)));
}
selector.push(("tick", Tag::Long(chosen.map_or(-1, |(_, t)| t))));
entries.push(("selector", Tag::compound(selector)));
entries.push(("event_delay", Tag::Int(self.travel)));
Tag::compound(entries)
}
pub fn from_nbt(tag: &Tag) -> Self {
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);
}
if let Some(selector) = tag.get("selector") {
let info = selector.get("event").and_then(info_from_nbt);
let tick = match selector.get("tick") {
Some(Tag::Long(t)) => *t,
_ => -1,
};
data.selector.current = info.map(|i| (i, tick));
}
data
}
}
fn info_to_nbt(info: &Info) -> Tag {
Tag::compound(vec![
("game_event", Tag::String(info.event.into())),
("distance", Tag::Float(info.distance.to_bits())),
(
"pos",
Tag::List(info.pos.iter().map(|v| Tag::Double(v.to_bits())).collect()),
),
])
}
fn info_from_nbt(tag: &Tag) -> Option<Info> {
let event = intern(&crate::save::text(tag.get("game_event"))?)?;
let distance = match tag.get("distance") {
Some(Tag::Float(f)) => f32::from_bits(*f),
_ => 0.0,
};
let pos = match tag.get("pos") {
Some(Tag::List(v)) if v.len() == 3 => {
let mut p = [0.0; 3];
for (i, t) in v.iter().enumerate() {
if let Tag::Double(d) = t {
p[i] = f64::from_bits(*d);
}
}
p
}
_ => return None,
};
Some(Info {
event,
distance,
pos,
source: None,
owner: None,
})
}
/// `Listener.isOccluded`: whether wool-like blocks block every line between
/// the centres of the source and listener blocks (nudged one direction each).
pub fn is_occluded(
origin: [f64; 3],
dest: [f64; 3],
mut occludes: impl FnMut(BlockPos) -> bool,
) -> bool {
let centre =
|p: [f64; 3]| Vec3::new(p[0].floor() + 0.5, p[1].floor() + 0.5, p[2].floor() + 0.5);
let from = centre(origin);
let to = centre(dest);
for direction in Direction::ALL {
let nudged = from.relative(direction, f64::from(1.0e-5f32));
let hit = traverse_blocks(nudged, to, 512, |p| occludes(p).then_some(()));
if !matches!(hit, Ok(Some(()))) {
return false;
}
}
true
}
/// Which sculk block entity this is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SculkKind {
Sensor,
Calibrated,
Shrieker,
Catalyst,
}
/// `SculkSensorBlockEntity`, `CalibratedSculkSensorBlockEntity`,
/// `SculkShriekerBlockEntity` and `SculkCatalystBlockEntity`.
#[derive(Clone, Debug)]
pub struct SculkEntity {
pub kind: SculkKind,
pub vibration: Data,
/// `last_vibration_frequency` (sensors).
pub last_frequency: i32,
/// `warning_level` (shriekers).
pub warning_level: i32,
/// The catalyst's charge cursors.
pub spreader: SculkSpreader,
}
impl SculkEntity {
pub fn new(kind: SculkKind) -> Self {
Self {
kind,
vibration: Data::default(),
last_frequency: 0,
warning_level: 0,
spreader: SculkSpreader::default(),
}
}
pub fn for_block(name: &str) -> Option<Self> {
Some(Self::new(match name {
"minecraft:sculk_sensor" => SculkKind::Sensor,
"minecraft:calibrated_sculk_sensor" => SculkKind::Calibrated,
"minecraft:sculk_shrieker" => SculkKind::Shrieker,
"minecraft:sculk_catalyst" => SculkKind::Catalyst,
_ => return None,
}))
}
pub fn id(&self) -> &'static str {
match self.kind {
SculkKind::Sensor => "minecraft:sculk_sensor",
SculkKind::Calibrated => "minecraft:calibrated_sculk_sensor",
SculkKind::Shrieker => "minecraft:sculk_shrieker",
SculkKind::Catalyst => "minecraft:sculk_catalyst",
}
}
/// `VibrationSystem.User.getListenerRadius`.
pub fn listener_radius(&self) -> i32 {
match self.kind {
SculkKind::Calibrated => 16,
SculkKind::Sensor | SculkKind::Shrieker | SculkKind::Catalyst => 8,
}
}
/// The block entity's saved fields.
pub fn to_nbt(&self) -> Vec<(&'static str, Tag)> {
match self.kind {
SculkKind::Sensor | SculkKind::Calibrated => vec![
("last_vibration_frequency", Tag::Int(self.last_frequency)),
("listener", self.vibration.to_nbt()),
],
SculkKind::Shrieker => vec![
("warning_level", Tag::Int(self.warning_level)),
("listener", self.vibration.to_nbt()),
],
SculkKind::Catalyst => vec![("cursors", cursors_to_nbt(&self.spreader))],
}
}
pub fn load(&mut self, tag: &Tag) {
match self.kind {
SculkKind::Sensor | SculkKind::Calibrated => {
if let Some(Tag::Int(f)) = tag.get("last_vibration_frequency") {
self.last_frequency = *f;
}
if let Some(l) = tag.get("listener") {
self.vibration = Data::from_nbt(l);
}
}
SculkKind::Shrieker => {
if let Some(Tag::Int(w)) = tag.get("warning_level") {
self.warning_level = *w;
}
if let Some(l) = tag.get("listener") {
self.vibration = Data::from_nbt(l);
}
}
SculkKind::Catalyst => {
if let Some(c) = tag.get("cursors") {
self.spreader = cursors_from_nbt(c);
}
}
}
}
}
fn cursors_to_nbt(spreader: &SculkSpreader) -> Tag {
Tag::List(
spreader
.cursors
.iter()
.map(|c| {
let mut e: Vec<(&str, Tag)> = vec![
("pos", Tag::IntArray(vec![c.pos.x, c.pos.y, c.pos.z])),
("charge", Tag::Int(c.charge)),
("decay_delay", Tag::Int(c.decay_delay)),
("update_delay", Tag::Int(c.update_delay)),
];
if let Some(faces) = &c.facings {
e.push((
"facings",
Tag::List(
faces
.iter()
.map(|d| Tag::String(direction_name(*d).into()))
.collect(),
),
));
}
Tag::compound(e)
})
.collect(),
)
}
fn cursors_from_nbt(tag: &Tag) -> SculkSpreader {
use horizon_world::level::sculk::ChargeCursor;
let mut spreader = SculkSpreader::default();
let Tag::List(items) = tag else {
return spreader;
};
for item in items.iter().take(32) {
let Some(Tag::IntArray(p)) = item.get("pos") else {
continue;
};
if p.len() != 3 {
continue;
}
let int = |k: &str, default: i32| match item.get(k) {
Some(Tag::Int(v)) => *v,
_ => default,
};
let facings = match item.get("facings") {
Some(Tag::List(v)) => Some(
v.iter()
.filter_map(|t| match t {
Tag::String(s) => direction_from_name(&String::from_utf16_lossy(&s.0)),
_ => None,
})
.collect(),
),
_ => None,
};
spreader.add_cursor(ChargeCursor {
pos: BlockPos::new(p[0], p[1], p[2]),
charge: int("charge", 0).clamp(0, 1000),
update_delay: int("update_delay", 0).max(0),
decay_delay: int("decay_delay", 1).clamp(0, 1),
facings,
});
}
spreader
}
fn direction_name(d: Direction) -> &'static str {
match d {
Direction::Down => "down",
Direction::Up => "up",
Direction::North => "north",
Direction::South => "south",
Direction::West => "west",
Direction::East => "east",
}
}
fn direction_from_name(s: &str) -> Option<Direction> {
Direction::ALL.into_iter().find(|d| direction_name(*d) == s)
}
/// `WardenSpawnTracker`: a player's warning level toward summoning a warden.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct WardenSpawnTracker {
pub ticks_since_last_warning: i32,
pub warning_level: i32,
pub cooldown_ticks: i32,
}
impl WardenSpawnTracker {
pub const MAX_WARNING_LEVEL: i32 = 4;
/// Blocks around a shrieker within which players are warned.
pub const PLAYER_SEARCH_RADIUS: f64 = 16.0;
/// `AABB.ofSize(centre, 48, 48, 48)` for an existing warden.
pub const WARNING_CHECK_DIAMETER: f64 = 48.0;
const DECREASE_EVERY: i32 = 12000;
const INCREASE_COOLDOWN: i32 = 200;
pub fn tick(&mut self) {
if self.ticks_since_last_warning >= Self::DECREASE_EVERY {
self.set_warning_level(self.warning_level - 1);
self.ticks_since_last_warning = 0;
} else {
self.ticks_since_last_warning += 1;
}
if self.cooldown_ticks > 0 {
self.cooldown_ticks -= 1;
}
}
pub fn reset(&mut self) {
*self = Self::default();
}
pub fn on_cooldown(&self) -> bool {
self.cooldown_ticks > 0
}
/// `increaseWarningLevel`.
pub fn increase_warning_level(&mut self) {
if !self.on_cooldown() {
self.ticks_since_last_warning = 0;
self.cooldown_ticks = Self::INCREASE_COOLDOWN;
self.set_warning_level(self.warning_level + 1);
}
}
pub fn set_warning_level(&mut self, level: i32) {
self.warning_level = level.clamp(0, Self::MAX_WARNING_LEVEL);
}
/// `WardenSpawnTracker.tryWarn` over the trackers of the players around a
/// shrieker (the triggering player included): the new warning level, or
/// None when a warden is near or a player is cooling down. Every tracker
/// takes over the highest one.
pub fn try_warn(trackers: &mut [WardenSpawnTracker], warden_nearby: bool) -> Option<i32> {
if warden_nearby || trackers.iter().any(|t| t.on_cooldown()) {
return None;
}
// Stream.max keeps the last of equal maxima.
let index = trackers
.iter()
.enumerate()
.max_by_key(|(i, t)| (t.warning_level, *i))
.map(|(i, _)| i)?;
trackers[index].increase_warning_level();
let copy = trackers[index];
for t in trackers.iter_mut() {
*t = copy;
}
Some(copy.warning_level)
}
pub fn to_nbt(&self) -> Tag {
Tag::compound(vec![
(
"ticks_since_last_warning",
Tag::Int(self.ticks_since_last_warning),
),
("warning_level", Tag::Int(self.warning_level)),
("cooldown_ticks", Tag::Int(self.cooldown_ticks)),
])
}
pub fn from_nbt(tag: &Tag) -> Self {
let int = |k: &str| match tag.get(k) {
Some(Tag::Int(v)) => (*v).max(0),
_ => 0,
};
Self {
ticks_since_last_warning: int("ticks_since_last_warning"),
warning_level: int("warning_level").min(Self::MAX_WARNING_LEVEL),
cooldown_ticks: int("cooldown_ticks"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn info(event: &'static str, distance: f32) -> Info {
Info {
event,
distance,
pos: [0.0; 3],
source: None,
owner: None,
}
}
#[test]
fn frequencies_match_the_vanilla_table() {
assert_eq!(frequency("minecraft:step"), 1);
assert_eq!(frequency("minecraft:hit_ground"), 2);
assert_eq!(frequency("minecraft:projectile_shoot"), 3);
assert_eq!(frequency("minecraft:entity_damage"), 7);
assert_eq!(frequency("minecraft:eat"), 8);
assert_eq!(frequency("minecraft:block_open"), 10);
assert_eq!(frequency("minecraft:block_change"), 11);
assert_eq!(frequency("minecraft:block_place"), 13);
assert_eq!(frequency("minecraft:explode"), 15);
assert_eq!(frequency("minecraft:resonate_9"), 9);
assert_eq!(frequency("minecraft:shriek"), 0);
assert_eq!(frequency(TENDRILS_CLICKING), 0);
assert_eq!(frequency("minecraft:jukebox_play"), 0);
assert_eq!(frequency("minecraft:made_up"), 0);
}
#[test]
fn event_tables_cover_resonance() {
for (i, name) in RESONANCE.iter().enumerate() {
assert_eq!(frequency(name), i as i32 + 1, "{name}");
assert!(is_vibration(name));
assert!(warden_can_listen(name));
}
assert!(warden_can_listen(SHRIEK));
assert!(warden_can_listen(TENDRILS_CLICKING));
assert!(!warden_can_listen("minecraft:flap"));
assert!(is_vibration("minecraft:flap"));
assert!(shrieker_can_listen(TENDRILS_CLICKING));
assert!(!shrieker_can_listen("minecraft:step"));
assert_eq!(notification_radius(SHRIEK), 32);
assert_eq!(notification_radius("minecraft:jukebox_play"), 10);
assert_eq!(notification_radius("minecraft:step"), 16);
}
#[test]
fn redstone_strength_falls_with_distance() {
assert_eq!(redstone_strength(0.0, 8), 15);
assert_eq!(redstone_strength(1.0, 8), 14);
assert_eq!(redstone_strength(4.0, 8), 8);
assert_eq!(redstone_strength(8.0, 8), 1);
assert_eq!(redstone_strength(8.0, 16), 8);
assert_eq!(redstone_strength(16.0, 16), 1);
}
#[test]
fn selector_prefers_the_nearest_then_the_loudest() {
let mut s = Selector::default();
s.add_candidate(info("minecraft:step", 5.0), 10);
s.add_candidate(info("minecraft:eat", 6.0), 10);
assert_eq!(s.chosen_candidate(11).unwrap().event, "minecraft:step");
s.add_candidate(info("minecraft:block_place", 5.0), 10);
assert_eq!(
s.chosen_candidate(11).unwrap().event,
"minecraft:block_place"
);
s.add_candidate(info("minecraft:eat", 2.0), 10);
assert_eq!(s.chosen_candidate(11).unwrap().event, "minecraft:eat");
// A later tick never replaces the pending candidate.
s.add_candidate(info("minecraft:explode", 0.0), 11);
assert_eq!(s.chosen_candidate(11).unwrap().event, "minecraft:eat");
// It is chosen only on a later tick than it was posted.
assert!(s.chosen_candidate(10).is_none());
s.start_over();
assert!(s.chosen_candidate(12).is_none());
}
#[test]
fn vibrations_travel_one_block_per_tick() {
let mut d = Data::default();
d.schedule(info("minecraft:step", 3.2), 100);
let travel = |distance: f32| distance.floor() as i32;
// Posted this tick: nothing yet.
let t = d.tick(100, true, true, travel);
assert_eq!(t, Tick::default());
// Chosen next tick with a travel time of three.
let t = d.tick(101, true, true, travel);
assert_eq!(t.started.map(|(_, n)| n), Some(3));
assert!(t.received.is_none());
assert!(d.tick(102, true, true, travel).received.is_none());
let t = d.tick(103, true, true, travel);
assert_eq!(t.received.map(|i| i.event), Some("minecraft:step"));
assert!(d.current.is_none());
}
#[test]
fn nearby_vibrations_arrive_at_once() {
let mut d = Data::default();
d.schedule(info("minecraft:eat", 0.4), 5);
let t = d.tick(6, true, true, |x| x.floor() as i32);
assert!(t.started.is_some());
assert!(t.received.is_some());
}
#[test]
fn unloaded_neighbours_hold_a_vibration_back() {
let mut d = Data::default();
d.schedule(info("minecraft:eat", 0.0), 5);
let t = d.tick(6, false, true, |_| 0);
assert!(t.started.is_some());
assert!(t.received.is_none());
assert!(d.current.is_some());
let t = d.tick(7, true, true, |_| 0);
assert!(t.received.is_some());
// Entities do not need the neighbours.
d.schedule(info("minecraft:eat", 0.0), 8);
assert!(d.tick(9, false, false, |_| 0).received.is_some());
}
#[test]
fn vibration_data_round_trips_through_nbt() {
let mut d = Data::default();
d.schedule(info("minecraft:block_destroy", 4.0), 40);
d.tick(41, true, true, |x| x as i32);
d.schedule(info("minecraft:step", 2.0), 41);
let back = Data::from_nbt(&d.to_nbt());
assert_eq!(back.travel, d.travel);
assert_eq!(back.current.map(|i| i.event), d.current.map(|i| i.event));
assert_eq!(back.selector.current.map(|(_, t)| t), Some(41));
}
#[test]
fn wool_on_the_line_occludes() {
let origin = [0.5, 0.5, 0.5];
let dest = [4.5, 0.5, 0.5];
// A full wall of wool between them blocks all six nudged lines.
let wall = |p: BlockPos| p.x == 2;
assert!(is_occluded(origin, dest, wall));
// One wool block on the line blocks the nudged lines too.
let single = |p: BlockPos| p == BlockPos::new(2, 0, 0);
assert!(is_occluded(origin, dest, single));
// Wool off to the side lets the vibration through.
let aside = |p: BlockPos| p == BlockPos::new(2, 1, 0);
assert!(!is_occluded(origin, dest, aside));
assert!(!is_occluded(origin, dest, |_| false));
}
#[test]
fn sneaking_ignores_footsteps_but_not_damage() {
let sneaking = Context {
source: Some(Who::Player),
stepping_carefully: true,
..Context::default()
};
assert!(!valid_vibration(true, "minecraft:step", &sneaking));
assert!(!valid_vibration(true, "minecraft:hit_ground", &sneaking));
assert!(valid_vibration(true, "minecraft:entity_damage", &sneaking));
let wardenish = Context {
source: Some(Who::Mob(1)),
dampens: true,
..Context::default()
};
assert!(!valid_vibration(
true,
"minecraft:entity_damage",
&wardenish
));
let on_wool = Context {
dampening_state: true,
..Context::default()
};
assert!(!valid_vibration(true, "minecraft:block_place", &on_wool));
assert!(!valid_vibration(
false,
"minecraft:step",
&Context::default()
));
}
#[test]
fn resonance_pitch_follows_the_tone_map() {
assert!((resonance_pitch(0) - 0.5).abs() < 1e-6);
assert!((resonance_pitch(4) - 2.0f32.powf(-6.0 / 12.0)).abs() < 1e-6);
assert!((resonance_pitch(15) - 2.0).abs() < 1e-6);
}
#[test]
fn warning_levels_rise_with_a_cooldown_and_decay() {
let mut t = WardenSpawnTracker::default();
t.increase_warning_level();
assert_eq!(t.warning_level, 1);
assert_eq!(t.cooldown_ticks, 200);
// Cooling down: no increase.
t.increase_warning_level();
assert_eq!(t.warning_level, 1);
for _ in 0..200 {
t.tick();
}
t.increase_warning_level();
assert_eq!(t.warning_level, 2);
t.set_warning_level(9);
assert_eq!(t.warning_level, 4);
t.cooldown_ticks = 0;
t.ticks_since_last_warning = 12000;
t.tick();
assert_eq!(t.warning_level, 3);
assert_eq!(t.ticks_since_last_warning, 0);
}
#[test]
fn nearby_players_share_the_highest_warning() {
let mut trackers = [
WardenSpawnTracker::default(),
WardenSpawnTracker {
warning_level: 2,
..Default::default()
},
];
assert_eq!(WardenSpawnTracker::try_warn(&mut trackers, true), None);
assert_eq!(WardenSpawnTracker::try_warn(&mut trackers, false), Some(3));
assert_eq!(trackers[0], trackers[1]);
assert_eq!(trackers[0].cooldown_ticks, 200);
// Everyone is cooling down now.
assert_eq!(WardenSpawnTracker::try_warn(&mut trackers, false), None);
}
#[test]
fn cursors_round_trip() {
let mut e = SculkEntity::new(SculkKind::Catalyst);
e.spreader.add_cursors(BlockPos::new(3, 4, 5), 1500);
e.spreader.cursors[1].facings = Some(vec![Direction::Up, Direction::East]);
let tag = Tag::compound(e.to_nbt());
let mut back = SculkEntity::new(SculkKind::Catalyst);
back.load(&tag);
assert_eq!(back.spreader, e.spreader);
assert_eq!(back.spreader.cursors[0].charge, 1000);
assert_eq!(back.spreader.cursors[1].charge, 500);
}
}
+12
View File
@@ -26,6 +26,11 @@ pub struct World {
/// Chunks changed since the last save.
pub modified: HashSet<(i32, i32)>,
pub block_entities: HashMap<(i32, i32, i32), crate::containers::BlockEntity>,
/// States (by id) whose writes are recorded in `watched_writes` (sculk
/// blocks, which need a block entity).
pub watched: Vec<bool>,
/// Writes of watched states: position, previous and new state.
pub watched_writes: Vec<((i32, i32, i32), u16, u16)>,
/// `ChunkAccess.inhabitedTime` of resident chunks: ticks a player spent
/// within spawning range (local difficulty).
pub inhabited: HashMap<(i32, i32), i64>,
@@ -106,6 +111,8 @@ impl World {
loaded_entities: Vec::new(),
modified: HashSet::new(),
block_entities: HashMap::new(),
watched: Vec::new(),
watched_writes: Vec::new(),
inhabited: HashMap::new(),
game_time: 0,
day_time: 1000,
@@ -177,6 +184,11 @@ impl World {
}
let previous = Arc::make_mut(chunk).set(x & 15, y, z & 15, state.0 as u16);
if u32::from(previous) != state.0 {
let watches = |id: u16| self.watched.get(usize::from(id)).copied().unwrap_or(false);
if watches(previous) || watches(state.0 as u16) {
self.watched_writes
.push(((x, y, z), previous, state.0 as u16));
}
self.revision = self.revision.wrapping_add(1);
self.modified.insert((x >> 4, z >> 4));
let sy = (y - MIN_Y) >> 4;
+7
View File
@@ -355,6 +355,11 @@ named_blocks! {
campfire = "campfire",
light = "light",
sculk_sensor = "sculk_sensor",
calibrated_sculk_sensor = "calibrated_sculk_sensor",
sculk_shrieker = "sculk_shrieker",
sculk_catalyst = "sculk_catalyst",
sculk = "sculk",
sculk_vein = "sculk_vein",
lectern = "lectern",
target = "target",
daylight_detector = "daylight_detector",
@@ -563,6 +568,8 @@ props! {
side_chain = "side_chain",
copper_golem_pose = "copper_golem_pose",
sculk_sensor_phase = "sculk_sensor_phase",
shrieking = "shrieking",
can_summon = "can_summon",
potent_sulfur_state = "potent_sulfur_state",
}
+8 -2
View File
@@ -114,6 +114,7 @@ mod place;
mod query;
mod rails;
mod redstone;
pub mod sculk;
mod shapes;
mod signals;
mod speleothem;
@@ -252,8 +253,13 @@ pub enum LevelEvent {
state: BlockStateId,
effect: PlayerEffect,
},
/// `Level.gameEvent` (vibration system), by vanilla identifier.
GameEvent { pos: BlockPos, event: &'static str },
/// `Level.gameEvent` (vibration system), by vanilla identifier, with the
/// affected block state when the event carries one.
GameEvent {
pos: BlockPos,
event: &'static str,
state: Option<BlockStateId>,
},
}
/// The world as seen by block behaviour. Implemented by the game and tests.
+1 -1
View File
@@ -1519,7 +1519,7 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
volume: (sounds.volume + 1.0) / 2.0,
pitch: sounds.pitch * 0.8,
});
self.game_event(ctx.pos, "minecraft:block_place");
self.game_event_state(ctx.pos, "minecraft:block_place", placed);
PlaceOutcome::Placed {
pos: ctx.pos,
state: placed,
+870
View File
@@ -0,0 +1,870 @@
//! Sculk: the sensor's phases, the shrieker and catalyst blocks, and the
//! level `SculkSpreader` with the sculk, sculk vein and default charge-cursor
//! behaviours (`SculkBlock`, `SculkVeinBlock`, `SculkBehaviour`).
use super::{
Behaviours, LevelAccess, LevelEvent, Sim, Ticks,
classes::Class,
update::{above, below, rel},
};
use crate::{fluid::FluidState, registry::BlockStateId};
use horizon_core::{geometry::Direction, position::BlockPos, random::RandomSource};
/// `SculkSensorBlock.ACTIVE_TICKS` (calibrated sensors use 10).
pub const SENSOR_ACTIVE_TICKS: i32 = 30;
pub const CALIBRATED_ACTIVE_TICKS: i32 = 10;
/// `SculkSensorBlock.COOLDOWN_TICKS`.
pub const SENSOR_COOLDOWN_TICKS: i32 = 10;
/// `SculkShriekerBlockEntity` shrieking time.
pub const SHRIEKING_TICKS: i32 = 90;
/// `SculkCatalystBlockEntity.CatalystListener.PULSE_TICKS`.
pub const PULSE_TICKS: i32 = 8;
// SculkSpreader.createLevelSpreader.
const GROWTH_SPAWN_COST: i32 = 10;
const NO_GROWTH_RADIUS: i32 = 4;
const CHARGE_DECAY_RATE: i32 = 10;
const ADDITIONAL_DECAY_RATE: i32 = 5;
const MAX_CURSORS: usize = 32;
const MAX_CHARGE: i32 = 1000;
const MAX_CURSOR_DISTANCE: i32 = 1024;
/// One `SculkSpreader.ChargeCursor`.
#[derive(Clone, Debug, PartialEq)]
pub struct ChargeCursor {
pub pos: BlockPos,
pub charge: i32,
pub update_delay: i32,
pub decay_delay: i32,
/// The faces of the block the cursor last moved onto, if any.
pub facings: Option<Vec<Direction>>,
}
impl ChargeCursor {
pub fn new(pos: BlockPos, charge: i32) -> Self {
Self {
pos,
charge,
update_delay: 0,
decay_delay: 1,
facings: None,
}
}
}
/// A catalyst's `SculkSpreader` (the level configuration).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct SculkSpreader {
pub cursors: Vec<ChargeCursor>,
}
impl SculkSpreader {
/// `addCursors`: charge in chunks of at most 1000, at most 32 cursors.
pub fn add_cursors(&mut self, start: BlockPos, mut charge: i32) {
while charge > 0 {
let current = charge.min(MAX_CHARGE);
self.add_cursor(ChargeCursor::new(start, current));
charge -= current;
}
}
pub fn add_cursor(&mut self, cursor: ChargeCursor) {
if self.cursors.len() < MAX_CURSORS {
self.cursors.push(cursor);
}
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Behaviour {
Default,
Sculk,
Vein,
}
#[derive(Clone, Copy)]
enum Spread {
SamePosition,
SamePlane,
WrapAround,
}
const ALL_SPREADS: [Spread; 3] = [Spread::SamePosition, Spread::SamePlane, Spread::WrapAround];
/// `MultifaceBlock.pack`: the faces as bits of their ordinals.
pub fn pack_faces(faces: &[Direction]) -> i32 {
faces.iter().fold(0, |code, d| code | 1 << *d as i32)
}
/// `MultifaceBlock.unpack`.
pub fn unpack_faces(data: i32) -> Vec<Direction> {
Direction::ALL
.into_iter()
.filter(|d| data & (1 << *d as i32) != 0)
.collect()
}
impl<L: LevelAccess + ?Sized> Sim<'_, L> {
fn sculk_rand(&mut self, bound: i32) -> i32 {
self.random().next_int_bound(bound).unwrap_or(0)
}
fn sculk_in_tag(&self, state: BlockStateId, tag: &str) -> bool {
self.b.tag(tag).is_some_and(|set| self.b.in_set(state, set))
}
fn sculk_sound(&mut self, pos: BlockPos, sound: &str, volume: f32, pitch: f32) {
self.emit(LevelEvent::Sound {
pos,
sound: sound.into(),
volume,
pitch,
});
}
// ---- sensors ----
/// `SculkSensorBlock.canActivate`.
pub(crate) fn sensor_phase(&self, state: BlockStateId) -> &'static str {
match self.b.table.text(state, self.b.props.sculk_sensor_phase) {
"active" => "active",
"cooldown" => "cooldown",
_ => "inactive",
}
}
fn sensor_update_neighbours(&mut self, pos: BlockPos, state: BlockStateId) {
let block = self.b.block(state);
self.update_neighbors_at(pos, block);
self.update_neighbors_at(below(pos), block);
}
/// `SculkSensorBlock.tick`.
pub(crate) fn sculk_sensor_tick(&mut self, pos: BlockPos, state: BlockStateId) {
let b = self.b;
match self.sensor_phase(state) {
"active" => self.sculk_sensor_deactivate(pos, state),
"cooldown" => {
let next = b
.table
.set_text(state, b.props.sculk_sensor_phase, "inactive");
self.set_block_and_update(pos, next);
if !b.table.bool(state, b.props.waterlogged) {
let pitch = self.random().next_float() * 0.2 + 0.8;
self.sculk_sound(
pos,
"minecraft:block.sculk_sensor.clicking_stop",
1.0,
pitch,
);
}
}
_ => {}
}
}
/// `SculkSensorBlock.deactivate`.
pub(crate) fn sculk_sensor_deactivate(&mut self, pos: BlockPos, state: BlockStateId) {
let b = self.b;
let next = b.table.set_int(
b.table
.set_text(state, b.props.sculk_sensor_phase, "cooldown"),
b.props.power,
0,
);
self.set_block_and_update(pos, next);
let block = b.block(state);
self.schedule_tick(pos, block, SENSOR_COOLDOWN_TICKS);
self.sensor_update_neighbours(pos, state);
}
/// `SculkSensorBlock.activate` without the resonance and the tendril
/// event, which need the source entity.
pub(crate) fn sculk_sensor_activate(
&mut self,
pos: BlockPos,
state: BlockStateId,
power: i32,
active_ticks: i32,
) {
let b = self.b;
let next = b.table.set_int(
b.table
.set_text(state, b.props.sculk_sensor_phase, "active"),
b.props.power,
power,
);
self.set_block_and_update(pos, next);
let block = b.block(state);
self.schedule_tick(pos, block, active_ticks);
self.sensor_update_neighbours(pos, state);
}
/// The activation sound, played after the tendril event.
pub(crate) fn sculk_sensor_click(&mut self, pos: BlockPos, state: BlockStateId) {
if !self.b.table.bool(state, self.b.props.waterlogged) {
let pitch = self.random().next_float() * 0.2 + 0.8;
self.sculk_sound(pos, "minecraft:block.sculk_sensor.clicking", 1.0, pitch);
}
}
// ---- shrieker and catalyst ----
/// `SculkShriekerBlock.tick`: the shriek ends and the block responds.
pub(crate) fn sculk_shrieker_tick(&mut self, pos: BlockPos, state: BlockStateId) {
let b = self.b;
if b.table.bool(state, b.props.shrieking) {
let next = b.table.set_bool(state, b.props.shrieking, false);
self.set_block_and_update(pos, next);
self.emit(LevelEvent::BlockEvent {
pos,
state: next,
kind: "shrieker_respond",
});
}
}
/// `SculkCatalystBlock.tick`.
pub(crate) fn sculk_catalyst_tick(&mut self, pos: BlockPos, state: BlockStateId) {
let b = self.b;
if b.table.bool(state, b.props.bloom) {
let next = b.table.set_bool(state, b.props.bloom, false);
self.set_block_and_update(pos, next);
}
}
// ---- the spreader ----
fn sculk_behaviour(&self, state: BlockStateId) -> Behaviour {
let block = self.b.block(state);
if block == self.b.named.sculk {
Behaviour::Sculk
} else if block == self.b.named.sculk_vein {
Behaviour::Vein
} else {
Behaviour::Default
}
}
fn is_vein(&self, state: BlockStateId) -> bool {
self.b.block(state) == self.b.named.sculk_vein
}
fn vein_has_face(&self, state: BlockStateId, face: Direction) -> bool {
self.is_vein(state) && self.multiface_has_face(state, face)
}
fn vein_with_face(&self, state: BlockStateId, face: Direction, value: bool) -> BlockStateId {
self.b
.table
.set_bool(state, self.direction_prop(face), value)
}
fn available_faces(&self, state: BlockStateId) -> Vec<Direction> {
if !self.b.instance_of(state, Class::Multiface) {
return Vec::new();
}
Direction::ALL
.into_iter()
.filter(|d| self.multiface_has_face(state, *d))
.collect()
}
fn is_sculk_source(&self, state: BlockStateId) -> bool {
self.sculk_behaviour(state) != Behaviour::Default
}
/// `SculkSpreader.updateCursors`.
pub(crate) fn sculk_update_cursors(
&mut self,
spreader: &mut SculkSpreader,
origin: BlockPos,
spread_veins: bool,
) {
if spreader.cursors.is_empty() {
return;
}
let cursors = std::mem::take(&mut spreader.cursors);
let mut processed: Vec<ChargeCursor> = Vec::new();
// The cursor each position merges into (index into `processed`).
let mut mergeable: Vec<(BlockPos, usize)> = Vec::new();
let mut charge_map: Vec<(BlockPos, i32)> = Vec::new();
for mut cursor in cursors {
let distance = (cursor.pos.x.wrapping_sub(origin.x).wrapping_abs())
.max(cursor.pos.y.wrapping_sub(origin.y).wrapping_abs())
.max(cursor.pos.z.wrapping_sub(origin.z).wrapping_abs());
if distance > MAX_CURSOR_DISTANCE {
continue;
}
self.sculk_cursor_update(&mut cursor, origin, spread_veins);
if cursor.charge <= 0 {
self.level_event(3006, cursor.pos, 0);
continue;
}
let pos = cursor.pos;
match charge_map.iter_mut().find(|(p, _)| *p == pos) {
Some(entry) => entry.1 += cursor.charge,
None => charge_map.push((pos, cursor.charge)),
}
match mergeable.iter().position(|(p, _)| *p == pos) {
None => {
mergeable.push((pos, processed.len()));
processed.push(cursor);
}
Some(slot) => {
let index = mergeable[slot].1;
if cursor.charge + processed[index].charge <= MAX_CHARGE {
// mergeWith
processed[index].charge += cursor.charge;
processed[index].update_delay =
processed[index].update_delay.min(cursor.update_delay);
} else {
let smaller = cursor.charge < processed[index].charge;
processed.push(cursor);
if smaller {
mergeable[slot].1 = processed.len() - 1;
}
}
}
}
}
for (pos, charge) in charge_map {
let faces = mergeable
.iter()
.find(|(p, _)| *p == pos)
.and_then(|(_, i)| processed[*i].facings.clone());
if charge > 0
&& let Some(faces) = faces
{
let particles = ((f64::from(charge) + 1.0).ln() as f32 / 2.3) as i32 + 1;
let data = (particles << 6) + pack_faces(&faces);
self.level_event(3006, pos, data);
}
}
spreader.cursors = processed;
}
/// `ChargeCursor.update`.
fn sculk_cursor_update(&mut self, cursor: &mut ChargeCursor, origin: BlockPos, veins: bool) {
// shouldUpdate: charge left and the origin's chunk is ticking.
if cursor.charge <= 0 || !self.level.is_ticking_chunk(origin.chunk()) {
return;
}
if cursor.update_delay > 0 {
cursor.update_delay -= 1;
return;
}
let mut state = self.state(cursor.pos);
let mut behaviour = self.sculk_behaviour(state);
if veins && self.sculk_attempt_spread_vein(behaviour, cursor.pos, state, &cursor.facings) {
// SculkBlock.canChangeBlockStateOnSpread is false.
if behaviour != Behaviour::Sculk {
state = self.state(cursor.pos);
behaviour = self.sculk_behaviour(state);
}
self.sculk_sound(cursor.pos, "minecraft:block.sculk.spread", 1.0, 1.0);
}
cursor.charge = self.sculk_attempt_use_charge(behaviour, cursor, origin, veins);
if cursor.charge <= 0 {
self.sculk_on_discharged(behaviour, state, cursor.pos);
return;
}
let transfer = self.sculk_valid_movement(cursor.pos);
if let Some(target) = transfer {
self.sculk_on_discharged(behaviour, state, cursor.pos);
cursor.pos = target;
state = self.state(target);
}
if self.is_sculk_source(state) {
cursor.facings = Some(self.available_faces(state));
}
cursor.decay_delay = match behaviour {
Behaviour::Default => (cursor.decay_delay - 1).max(0),
_ => 1,
};
cursor.update_delay = 1;
}
/// `SculkBehaviour.attemptSpreadVein` (the default behaviour's override
/// regrows veins or spreads in the same space).
fn sculk_attempt_spread_vein(
&mut self,
behaviour: Behaviour,
pos: BlockPos,
state: BlockStateId,
facings: &Option<Vec<Direction>>,
) -> bool {
if behaviour == Behaviour::Default {
match facings {
None => {
let current = self.state(pos);
return self.sculk_spread_all(current, pos, &[Spread::SamePosition]) > 0;
}
Some(faces) if !faces.is_empty() => {
let b = self.b;
let water = b.is_block(state, b.named.water) && b.fluid(state).is_source();
if !b.is_air(state) && !water {
return false;
}
return self.sculk_regrow(pos, state, faces);
}
Some(_) => {}
}
}
self.sculk_spread_all(state, pos, &ALL_SPREADS) > 0
}
/// `SculkVeinBlock.regrow`.
fn sculk_regrow(&mut self, pos: BlockPos, existing: BlockStateId, faces: &[Direction]) -> bool {
let b = self.b;
let mut state = b.default_of(b.named.sculk_vein);
let mut any = false;
for &face in faces {
if b.multiface_can_attach(self.state(rel(pos, face)), face) {
state = self.vein_with_face(state, face, true);
any = true;
}
}
if !any {
return false;
}
if b.fluid(existing) != FluidState::EMPTY {
state = b.table.set_bool(state, b.props.waterlogged, true);
}
self.set_block_and_update(pos, state);
true
}
/// `MultifaceSpreader.spreadAll` with the sculk vein configuration.
fn sculk_spread_all(&mut self, state: BlockStateId, pos: BlockPos, types: &[Spread]) -> i64 {
let other_source = !self.is_vein(state);
let mut count = 0;
for face in Direction::ALL {
if !(other_source || self.vein_has_face(state, face)) {
continue;
}
for direction in Direction::ALL {
if crate::level::query::axis_of(direction) == crate::level::query::axis_of(face) {
continue;
}
if !(other_source
|| (self.vein_has_face(state, face) && !self.vein_has_face(state, direction)))
{
continue;
}
let mut target = None;
for kind in types {
let candidate = match kind {
Spread::SamePosition => (pos, direction),
Spread::SamePlane => (rel(pos, direction), face),
Spread::WrapAround => {
(rel(rel(pos, direction), face), direction.opposite())
}
};
if self.sculk_can_spread_into(pos, candidate.0, candidate.1) {
target = Some(candidate);
break;
}
}
let Some((target, face_to)) = target else {
continue;
};
let old = self.state(target);
let Some(new) = self.sculk_state_for_placement(old, target, face_to) else {
continue;
};
if self.set_block(target, new, 2) {
count += 1;
}
}
}
count
}
fn sculk_valid_for_placement(&self, old: BlockStateId, pos: BlockPos, face: Direction) -> bool {
if self.vein_has_face(old, face) {
return false;
}
self.b
.multiface_can_attach(self.state(rel(pos, face)), face)
}
/// `MultifaceBlock.getStateForPlacement` for the sculk vein.
fn sculk_state_for_placement(
&self,
old: BlockStateId,
pos: BlockPos,
face: Direction,
) -> Option<BlockStateId> {
if !self.sculk_valid_for_placement(old, pos, face) {
return None;
}
let b = self.b;
let base = if self.is_vein(old) {
old
} else if b.fluid(old) == FluidState::WATER {
b.table
.set_bool(b.default_of(b.named.sculk_vein), b.props.waterlogged, true)
} else {
b.default_of(b.named.sculk_vein)
};
Some(self.vein_with_face(base, face, true))
}
/// `SculkVeinSpreaderConfig.canSpreadInto` (with the default config).
fn sculk_can_spread_into(&self, source: BlockPos, target: BlockPos, face: Direction) -> bool {
let b = self.b;
let existing = self.state(target);
let against = self.state(rel(target, face));
let against_block = b.block(against);
if against_block == b.named.sculk
|| against_block == b.named.sculk_catalyst
|| against_block == b.named.moving_piston
{
return false;
}
let manhattan =
(source.x - target.x).abs() + (source.y - target.y).abs() + (source.z - target.z).abs();
if manhattan == 2 {
let neighbour = rel(source, face.opposite());
if b.is_face_sturdy(self.state(neighbour), face) {
return false;
}
}
let fluid = b.fluid(existing);
if fluid != FluidState::EMPTY && !(b.is_block(existing, b.named.water) && fluid.is_source())
{
return false;
}
if self.sculk_in_tag(existing, "minecraft:fire") {
return false;
}
let replaceable = b.is_replaceable(existing)
|| b.is_air(existing)
|| self.is_vein(existing)
|| (b.is_block(existing, b.named.water) && fluid.is_source());
replaceable && self.sculk_valid_for_placement(existing, target, face)
}
/// `SculkBehaviour.attemptUseCharge` per behaviour.
fn sculk_attempt_use_charge(
&mut self,
behaviour: Behaviour,
cursor: &ChargeCursor,
origin: BlockPos,
veins: bool,
) -> i32 {
let charge = cursor.charge;
match behaviour {
Behaviour::Default => {
if cursor.decay_delay > 0 {
charge
} else {
0
}
}
Behaviour::Vein => {
if veins && self.sculk_place_sculk(cursor.pos) {
charge - 1
} else if self.sculk_rand(CHARGE_DECAY_RATE) == 0 {
(charge as f32 * 0.5).floor() as i32
} else {
charge
}
}
Behaviour::Sculk => {
if charge == 0 || self.sculk_rand(CHARGE_DECAY_RATE) != 0 {
return charge;
}
let pos = cursor.pos;
let dist_sqr = f64::from(
(pos.x - origin.x).pow(2)
+ (pos.y - origin.y).pow(2)
+ (pos.z - origin.z).pow(2),
);
let close = dist_sqr < f64::from(NO_GROWTH_RADIUS * NO_GROWTH_RADIUS);
if !close && self.sculk_can_place_growth(pos) {
if self.sculk_rand(GROWTH_SPAWN_COST) < charge {
let growth_pos = above(pos);
let growth = self.sculk_random_growth(growth_pos);
self.set_block_and_update(growth_pos, growth);
let sounds = self.b.data(growth).sounds.clone();
self.emit(LevelEvent::Sound {
pos,
sound: sounds.place.clone(),
volume: 1.0,
pitch: 1.0,
});
}
return (charge - GROWTH_SPAWN_COST).max(0);
}
if self.sculk_rand(ADDITIONAL_DECAY_RATE) != 0 {
return charge;
}
let penalty = if close {
1
} else {
// getDecayPenalty
let outer = (dist_sqr.sqrt() as f32 - NO_GROWTH_RADIUS as f32).powi(2);
let reach = (24 - NO_GROWTH_RADIUS) * (24 - NO_GROWTH_RADIUS);
let factor = 1.0f32.min(outer / reach as f32);
1.max((charge as f32 * factor * 0.5) as i32)
};
charge - penalty
}
}
}
/// `SculkBlock.getRandomGrowthState` (not for world generation).
fn sculk_random_growth(&mut self, pos: BlockPos) -> BlockStateId {
let b = self.b;
let state = if self.sculk_rand(11) == 0 {
b.default_of(b.named.sculk_shrieker)
} else {
b.default_of(b.named.sculk_sensor)
};
if self.fluid_at(pos) != FluidState::EMPTY {
b.table.set_bool(state, b.props.waterlogged, true)
} else {
state
}
}
/// `SculkBlock.canPlaceGrowth`.
fn sculk_can_place_growth(&self, pos: BlockPos) -> bool {
let b = self.b;
let state_above = self.state(above(pos));
let open = b.is_air(state_above)
|| (b.is_block(state_above, b.named.water) && b.fluid(state_above).is_source());
if !open {
return false;
}
let mut matched = 0;
for dz in -4..=4 {
for dy in 0..=2 {
for dx in -4..=4 {
let state = self.state(pos.offset(dx, dy, dz));
if self.sculk_in_tag(state, "minecraft:sculk_growth_inhibitors") {
matched += 1;
if matched >= 3 {
return false;
}
}
}
}
}
true
}
/// `SculkVeinBlock.attemptPlaceSculk`.
fn sculk_place_sculk(&mut self, pos: BlockPos) -> bool {
let state = self.state(pos);
let mut directions = Direction::ALL;
for i in (2..=directions.len()).rev() {
let swap = self.sculk_rand(i as i32) as usize;
directions.swap(i - 1, swap);
}
for support in directions {
if !self.vein_has_face(state, support) {
continue;
}
let support_pos = rel(pos, support);
let support_state = self.state(support_pos);
if !self.sculk_in_tag(support_state, "minecraft:sculk_replaceable") {
continue;
}
let default_sculk = self.b.default_of(self.b.named.sculk);
self.set_block_and_update(support_pos, default_sculk);
self.sculk_sound(support_pos, "minecraft:block.sculk.spread", 1.0, 1.0);
self.sculk_spread_all(default_sculk, support_pos, &ALL_SPREADS);
let skip = support.opposite();
for direction in Direction::ALL {
if direction == skip {
continue;
}
let vein_pos = rel(support_pos, direction);
let possible = self.state(vein_pos);
if self.is_vein(possible) {
self.sculk_on_discharged(Behaviour::Vein, possible, vein_pos);
}
}
return true;
}
false
}
/// `SculkVeinBlock.onDischarged`.
fn sculk_on_discharged(&mut self, behaviour: Behaviour, state: BlockStateId, pos: BlockPos) {
if behaviour != Behaviour::Vein || !self.is_vein(state) {
return;
}
let b = self.b;
let mut state = state;
for direction in Direction::ALL {
if self.multiface_has_face(state, direction)
&& b.is_block(self.state(rel(pos, direction)), b.named.sculk)
{
state = self.vein_with_face(state, direction, false);
}
}
if !Direction::ALL
.into_iter()
.any(|d| self.multiface_has_face(state, d))
{
state = if self.fluid_at(pos) == FluidState::EMPTY {
b.default_of(b.named.air)
} else {
b.default_of(b.named.water)
};
}
self.set_block_and_update(pos, state);
}
/// `ChargeCursor.getValidMovementPos`.
fn sculk_valid_movement(&mut self, pos: BlockPos) -> Option<BlockPos> {
let mut offsets = Vec::with_capacity(18);
for z in -1..=1 {
for y in -1..=1 {
for x in -1..=1 {
if (x == 0 || y == 0 || z == 0) && (x, y, z) != (0, 0, 0) {
offsets.push([x, y, z]);
}
}
}
}
for i in (2..=offsets.len()).rev() {
let swap = self.sculk_rand(i as i32) as usize;
offsets.swap(i - 1, swap);
}
let b = self.b;
let mut best = pos;
for o in offsets {
let neighbour = pos.offset(o[0], o[1], o[2]);
let transferee = self.state(neighbour);
if self.sculk_behaviour(transferee) == Behaviour::Default
|| !self.sculk_unobstructed_move(pos, neighbour)
{
continue;
}
best = neighbour;
// SculkVeinBlock.hasSubstrateAccess
if self.is_vein(transferee)
&& Direction::ALL.into_iter().any(|d| {
self.multiface_has_face(transferee, d)
&& self.sculk_in_tag(
self.state(rel(neighbour, d)),
"minecraft:sculk_replaceable",
)
})
{
break;
}
}
let _ = b;
(best != pos).then_some(best)
}
fn sculk_unobstructed_move(&self, from: BlockPos, to: BlockPos) -> bool {
let manhattan = (from.x - to.x).abs() + (from.y - to.y).abs() + (from.z - to.z).abs();
if manhattan == 1 {
return true;
}
let delta = [to.x - from.x, to.y - from.y, to.z - from.z];
let dir_x = if delta[0] < 0 {
Direction::West
} else {
Direction::East
};
let dir_y = if delta[1] < 0 {
Direction::Down
} else {
Direction::Up
};
let dir_z = if delta[2] < 0 {
Direction::North
} else {
Direction::South
};
let (a, c) = if delta[0] == 0 {
(dir_y, dir_z)
} else if delta[1] == 0 {
(dir_x, dir_z)
} else {
(dir_x, dir_y)
};
let free = |direction: Direction| {
let test = rel(from, direction);
!self
.b
.is_face_sturdy(self.state(test), direction.opposite())
};
free(a) || free(c)
}
}
impl Behaviours {
/// `SculkSensorBlock.canActivate`: the sensor is inactive.
pub fn sculk_sensor_can_activate(&self, state: BlockStateId) -> bool {
self.table.text(state, self.props.sculk_sensor_phase) == "inactive"
}
/// The sensor's phase (`inactive`, `active` or `cooldown`).
pub fn sculk_sensor_active(&self, state: BlockStateId) -> bool {
self.table.text(state, self.props.sculk_sensor_phase) == "active"
}
/// `SculkSensorBlock.activate` (the state, its ticks and the redstone
/// update); the caller sends the tendril and resonance events.
pub fn sculk_sensor_activate<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
pos: BlockPos,
power: i32,
) {
let mut sim = self.sim(level, ticks);
let state = sim.state(pos);
let active_ticks = if self.block(state) == self.named.calibrated_sculk_sensor {
CALIBRATED_ACTIVE_TICKS
} else {
SENSOR_ACTIVE_TICKS
};
sim.sculk_sensor_activate(pos, state, power, active_ticks);
}
/// The click sound after an activation.
pub fn sculk_sensor_click<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
pos: BlockPos,
) {
let mut sim = self.sim(level, ticks);
let state = sim.state(pos);
sim.sculk_sensor_click(pos, state);
}
/// `CalibratedSculkSensorBlockEntity.VibrationUser.getBackSignal`.
pub fn calibrated_back_signal<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
pos: BlockPos,
) -> i32 {
let sim = self.sim(level, ticks);
let state = sim.state(pos);
let direction = self.facing(state).opposite();
sim.signal(rel(pos, direction), direction)
}
/// `SculkCatalystBlockEntity.CatalystListener.bloom`'s block half.
pub fn sculk_catalyst_bloom<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
pos: BlockPos,
) {
let mut sim = self.sim(level, ticks);
let state = sim.state(pos);
if self.block(state) != self.named.sculk_catalyst {
return;
}
let next = self.table.set_bool(state, self.props.bloom, true);
sim.set_block_and_update(pos, next);
let block = self.block(state);
sim.schedule_tick(pos, block, PULSE_TICKS);
}
/// `SculkShriekerBlockEntity.shriek`'s block half: `shrieking` for 90 ticks.
pub fn sculk_shrieker_shriek<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
pos: BlockPos,
) {
let mut sim = self.sim(level, ticks);
let state = sim.state(pos);
if self.block(state) != self.named.sculk_shrieker {
return;
}
let next = self.table.set_bool(state, self.props.shrieking, true);
sim.set_block(pos, next, 2);
let block = self.block(state);
sim.schedule_tick(pos, block, SHRIEKING_TICKS);
sim.level_event(3007, pos, 0);
}
/// `SculkSpreader.updateCursors` for a catalyst at `origin`.
pub fn sculk_update_cursors<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
spreader: &mut SculkSpreader,
origin: BlockPos,
spread_veins: bool,
) {
self.sim(level, ticks)
.sculk_update_cursors(spreader, origin, spread_veins);
}
}
+162
View File
@@ -923,6 +923,168 @@ fn dripstone_fills_cauldrons() {
assert_eq!(w.name(BlockPos::new(0, 5, 0)), "water_cauldron[level=1]");
}
#[test]
fn sculk_sensor_phases_and_signal() {
let mut w = world!();
w.floor(0, 6, "stone");
let pos = BlockPos::new(0, 1, 0);
let sensor = w.id("sculk_sensor", &[]);
w.set(pos, sensor);
assert!(w.b().sculk_sensor_can_activate(w.get(pos)));
w.f.behaviours
.sculk_sensor_activate(&mut w.level, &mut w.ticks, pos, 11);
assert_eq!(w.prop(pos, "sculk_sensor_phase"), "active");
assert_eq!(w.prop(pos, "power"), "11");
// The sensor powers the block below it from the top.
let below = BlockPos::new(0, 0, 0);
assert_eq!(
w.f.behaviours
.best_neighbor_signal(&mut w.level, &mut w.ticks, below),
11,
"the block under an active sensor receives its power"
);
for _ in 0..29 {
w.tick();
}
assert_eq!(w.prop(pos, "sculk_sensor_phase"), "active");
w.tick();
assert_eq!(w.prop(pos, "sculk_sensor_phase"), "cooldown");
assert_eq!(w.prop(pos, "power"), "0");
for _ in 0..10 {
w.tick();
}
assert_eq!(w.prop(pos, "sculk_sensor_phase"), "inactive");
}
#[test]
fn calibrated_sensor_is_active_for_ten_ticks() {
let mut w = world!();
w.floor(0, 6, "stone");
let pos = BlockPos::new(0, 1, 0);
let sensor = w.id("calibrated_sculk_sensor", &[("facing", "north")]);
w.set(pos, sensor);
w.f.behaviours
.sculk_sensor_activate(&mut w.level, &mut w.ticks, pos, 4);
for _ in 0..9 {
w.tick();
}
assert_eq!(w.prop(pos, "sculk_sensor_phase"), "active");
w.tick();
assert_eq!(w.prop(pos, "sculk_sensor_phase"), "cooldown");
// The block behind (south) feeds the calibration signal.
let source = w.id("redstone_block", &[]);
w.set(BlockPos::new(0, 1, 1), source);
assert_eq!(
w.f.behaviours
.calibrated_back_signal(&mut w.level, &mut w.ticks, pos),
15
);
}
#[test]
fn sculk_charge_spreads_veins_and_sculk() {
let mut w = world!();
w.floor(0, 12, "stone");
w.floor(-1, 12, "stone");
let origin = BlockPos::new(0, 1, 0);
let catalyst = w.id("sculk_catalyst", &[]);
w.put(origin, catalyst);
let mut spreader = sculk::SculkSpreader::default();
spreader.add_cursors(BlockPos::new(2, 1, 0), 40);
assert_eq!(spreader.cursors.len(), 1);
for _ in 0..80 {
w.f.behaviours.sculk_update_cursors(
&mut w.level,
&mut w.ticks,
&mut spreader,
origin,
true,
);
}
let sculk = w.id("sculk", &[]);
let found = (-12..=12)
.flat_map(|x| (-12..=12).map(move |z| BlockPos::new(x, 0, z)))
.filter(|p| w.get(*p) == sculk)
.count();
assert!(found > 0, "the charge turned stone into sculk");
assert!(
w.level
.events
.iter()
.any(|e| matches!(e, LevelEvent::LevelEvent { id: 3006, .. })),
"charge particles are reported"
);
}
#[test]
fn shrieker_responds_when_the_shriek_ends() {
let mut w = world!();
w.floor(0, 6, "stone");
let pos = BlockPos::new(0, 1, 0);
let shrieker = w.id("sculk_shrieker", &[("can_summon", "true")]);
w.set(pos, shrieker);
w.f.behaviours
.sculk_shrieker_shriek(&mut w.level, &mut w.ticks, pos);
assert_eq!(w.prop(pos, "shrieking"), "true");
for _ in 0..89 {
w.tick();
}
assert_eq!(w.prop(pos, "shrieking"), "true");
w.tick();
assert_eq!(w.prop(pos, "shrieking"), "false");
assert!(w.level.events.iter().any(|e| matches!(
e,
LevelEvent::BlockEvent {
kind: "shrieker_respond",
..
}
)));
}
#[test]
fn catalyst_bloom_lasts_eight_ticks() {
let mut w = world!();
let pos = BlockPos::new(0, 1, 0);
let catalyst = w.id("sculk_catalyst", &[]);
w.set(pos, catalyst);
w.f.behaviours
.sculk_catalyst_bloom(&mut w.level, &mut w.ticks, pos);
assert_eq!(w.prop(pos, "bloom"), "true");
for _ in 0..7 {
w.tick();
}
assert_eq!(w.prop(pos, "bloom"), "true");
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
)));
}
#[test]
fn dispenser_buckets_pick_up_and_empty() {
let mut w = world!();
+3
View File
@@ -151,6 +151,9 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
Class::RedstoneLamp => self.lamp_tick(pos, state),
Class::RedstoneTorch => self.torch_tick(pos, state),
Class::Scaffolding => self.scaffolding_tick(pos, state),
Class::SculkSensor => self.sculk_sensor_tick(pos, state),
Class::SculkShrieker => self.sculk_shrieker_tick(pos, state),
Class::SculkCatalyst => self.sculk_catalyst_tick(pos, state),
Class::Speleothem => {
let tip = b.table.dir(state, p.vertical_direction);
if tip == Some(Direction::Up) && !self.can_survive(state, pos) {
+14 -2
View File
@@ -195,7 +195,19 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
});
}
pub fn game_event(&mut self, pos: BlockPos, event: &'static str) {
self.level.emit(LevelEvent::GameEvent { pos, event });
self.level.emit(LevelEvent::GameEvent {
pos,
event,
state: None,
});
}
/// `Level.gameEvent(event, pos, Context.of(state))`.
pub fn game_event_state(&mut self, pos: BlockPos, event: &'static str, state: BlockStateId) {
self.level.emit(LevelEvent::GameEvent {
pos,
event,
state: Some(state),
});
}
pub fn block_of(&self, state: BlockStateId) -> BlockId {
self.b.table.block(state)
@@ -334,7 +346,7 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
let legacy = self.b.legacy_block(fluid);
let destroyed = self.set_block_limit(pos, legacy, 3, limit);
if destroyed {
self.game_event(pos, "minecraft:block_destroy");
self.game_event_state(pos, "minecraft:block_destroy", state);
}
destroyed
}