Add the vibration system, sculk block entities and the warden

Game events now reach sculk sensors, calibrated sensors, shriekers and wardens through the vibration system: frequencies, listener ranges, travel time, wool occlusion, sneaking and dampening rules, and the nearest-first selection. Sensors power redstone and comparators and resonate amethyst, shriekers warn players and summon a warden at the fourth warning, catalysts take the experience of nearby deaths and spread sculk, and the warden has its anger, brain, sonic boom, animations and layers.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-09 13:00:26 +02:00
parent 9967697de2
commit ed89f533e2
22 changed files with 4384 additions and 31 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 {
+17 -2
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>),
}
#[derive(Clone, Debug, Default)]
pub struct Lectern {
@@ -104,6 +106,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:beacon" {
return Some(Self::Beacon(Box::new(Beacon {
last_check_y: i32::MIN / 2,
@@ -155,6 +160,7 @@ impl BlockEntity {
Self::Jukebox(_) => "minecraft:jukebox",
Self::Beacon(_) => "minecraft:beacon",
Self::Lectern(_) => "minecraft:lectern",
Self::Sculk(s) => s.id(),
}
}
pub fn contents(&self) -> Vec<ItemStack> {
@@ -166,6 +172,7 @@ impl BlockEntity {
Self::Jukebox(j) => j.record.iter().cloned().collect(),
Self::Beacon(_) => Vec::new(),
Self::Lectern(l) => l.book.iter().cloned().collect(),
Self::Sculk(_) => Vec::new(),
}
}
pub fn slots(&self) -> &[Option<ItemStack>] {
@@ -173,7 +180,11 @@ impl BlockEntity {
Self::Chest(items) => items,
Self::Furnace(f) => &f.items,
Self::Brewing(b) => &b.items,
Self::Sign(_) | Self::Jukebox(_) | Self::Beacon(_) | Self::Lectern(_) => &[],
Self::Sign(_)
| Self::Jukebox(_)
| Self::Beacon(_)
| Self::Lectern(_)
| Self::Sculk(_) => &[],
}
}
pub fn slots_mut(&mut self) -> &mut [Option<ItemStack>] {
@@ -181,7 +192,11 @@ impl BlockEntity {
Self::Chest(items) => items,
Self::Furnace(f) => &mut f.items,
Self::Brewing(b) => &mut b.items,
Self::Sign(_) | Self::Jukebox(_) | Self::Beacon(_) | Self::Lectern(_) => &mut [],
Self::Sign(_)
| Self::Jukebox(_)
| Self::Beacon(_)
| Self::Lectern(_)
| Self::Sculk(_) => &mut [],
}
}
}
+16
View File
@@ -314,6 +314,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));
@@ -565,6 +574,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;
+33 -5
View File
@@ -46,6 +46,7 @@ mod remote;
mod render_control;
mod render_tick;
mod screens;
mod sculk;
mod shield;
mod sign_edit;
mod station_control;
@@ -299,9 +300,12 @@ 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;
}
@@ -517,6 +521,7 @@ struct Game<'a> {
mobs: Vec<Mob>,
arrows: Vec<Arrow>,
creatures: creatures::Creatures,
sculk: sculk::SculkState,
attack_ticks: u32,
last_hurt_by_player: HashSet<u32>,
chest_open: HashMap<(i32, i32, i32), (f32, f32)>,
@@ -1226,6 +1231,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,
@@ -1375,10 +1386,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(())
@@ -1536,6 +1554,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.
@@ -1632,6 +1653,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(());
@@ -2470,6 +2494,7 @@ impl Game<'_> {
self.bob.1 += (target - self.bob.1) * 0.4;
}
self.tick_block_entities()?;
self.tick_sculk()?;
self.tick_brewing_stands()?;
if let Some(r) = &self.renderer {
let eye = self.player.as_ref().map(|p| {
@@ -3040,7 +3065,8 @@ impl Game<'_> {
BlockEntity::Sign(_)
| BlockEntity::Jukebox(_)
| BlockEntity::Beacon(_)
| BlockEntity::Lectern(_),
| BlockEntity::Lectern(_)
| BlockEntity::Sculk(_),
) => {}
None => {
v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i));
@@ -3265,7 +3291,8 @@ impl Game<'_> {
BlockEntity::Sign(_)
| BlockEntity::Jukebox(_)
| BlockEntity::Beacon(_)
| BlockEntity::Lectern(_),
| BlockEntity::Lectern(_)
| BlockEntity::Sculk(_),
) => {}
None => {
let texture = if self.craft_size == 3 {
@@ -7597,6 +7624,7 @@ pub fn run() -> Result<()> {
mobs: Vec::new(),
arrows: Vec::new(),
creatures: Default::default(),
sculk: Default::default(),
attack_ticks: 100,
last_hurt_by_player: HashSet::new(),
chest_open: HashMap::new(),
+17 -1
View File
@@ -639,6 +639,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);
@@ -720,7 +731,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);
@@ -970,6 +981,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::GiftLoot { table, at } => {
let drops =
self.res
File diff suppressed because it is too large Load Diff
+1
View File
@@ -55,6 +55,7 @@ pub mod pose;
pub mod projectiles;
pub mod save;
pub mod screen_effects;
pub mod sculk;
pub mod settings;
pub mod shadows;
pub mod signs;
+20
View File
@@ -37,6 +37,7 @@ pub mod tame;
pub mod undead;
pub mod vex;
pub mod villager;
pub mod warden;
pub mod witch;
pub mod wither;
mod world;
@@ -336,6 +337,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)]
@@ -390,6 +392,7 @@ impl Damage {
| DamageKind::Magic
| DamageKind::InWall
| DamageKind::Generic
| DamageKind::SonicBoom
)
}
pub fn is_fire(&self) -> bool {
@@ -473,6 +476,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>>,
}
#[derive(Clone, Debug)]
pub struct Mob {
@@ -662,6 +667,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,
},
}
/// How a spawned-by-kind mob should be set up.
#[derive(Clone, Debug, Default)]
+13
View File
@@ -87,6 +87,7 @@ pub enum Family {
Wither,
Allay,
Villager,
Warden,
}
pub fn family(s: Species) -> Family {
use Species as S;
@@ -130,6 +131,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,
}
@@ -169,6 +171,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),
}
}
/// Mob.tick additions that run before the entity tick (creeper fuse, puffing).
@@ -371,6 +374,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",
@@ -532,6 +540,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,
_ => {}
@@ -559,6 +568,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),
@@ -625,6 +635,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
@@ -665,6 +676,7 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage, _amount: f32) -> bool {
// Allay.hurtServer: its liked player cannot hurt it.
Species::Allay if m.extra.tame && source.attacker == Some(Who::Player) => false,
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
@@ -681,6 +693,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,
Camel,
Wither,
@@ -345,6 +346,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::Squid | Anim::Fish | Anim::Pufferfish | Anim::Dolphin => {
super::aquatic::anim(m, s, p)
+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
@@ -766,7 +766,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,
}
/// Baby bounding boxes (each class's BABY_DIMENSIONS).
#[derive(Clone, Copy, Debug)]
@@ -1148,6 +1149,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])
@@ -1356,6 +1371,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
@@ -119,6 +119,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.
@@ -138,8 +144,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],
}
impl ParticleOptions {
pub fn simple(ty: ParticleType) -> Self {
@@ -148,6 +157,41 @@ impl ParticleOptions {
block: None,
color: [1.0; 4],
scale: 1.0,
to_color: [1.0, 0.0, 0.0],
}
}
/// `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)
}
}
pub fn block(ty: ParticleType, sprite: String, tint: u32) -> Self {
@@ -188,6 +232,8 @@ enum Size {
Lava,
Portal,
ReversePortal,
/// `ShriekParticle.getQuadSize`.
Shriek,
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Light {
@@ -261,6 +307,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],
},
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum DripStage {
@@ -511,6 +574,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),
}
}
}
@@ -655,6 +719,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);
@@ -1411,12 +1496,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;
@@ -1470,6 +1560,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;
@@ -2146,6 +2299,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::HugeExplosion => {
p.previous = p.position;
let age = p.age;
@@ -2403,6 +2599,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(-1.0472)),
Some(Quat::from_euler(
glam::EulerRot::YXZ,
-std::f32::consts::PI,
1.0472,
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);
@@ -2424,7 +2672,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],
@@ -2432,20 +2680,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
@@ -400,6 +400,7 @@ fn encode_block_entity(p: (i32, i32, i32), e: &crate::containers::BlockEntity, b
entries.push(("Page", Tag::Int(l.page)));
}
}
BlockEntity::Sculk(s) => entries.extend(s.to_nbt()),
}
Tag::compound(entries)
}
@@ -474,6 +475,7 @@ fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers:
};
}
BlockEntity::Sign(sign) => sign.decode(tag),
BlockEntity::Sculk(s) => s.load(tag),
BlockEntity::Jukebox(_) | BlockEntity::Beacon(_) | BlockEntity::Lectern(_) => {}
}
Some((pos, entity))
+885
View File
@@ -0,0 +1,885 @@
//! 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::default();
data.current = tag.get("event").and_then(info_from_nbt);
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 -2
View File
@@ -250,8 +250,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
@@ -1514,7 +1514,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,
+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
}