From 2f232d955ce0a733a9bbdcf2c835549aaddc3720 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 12 Oct 2026 17:01:59 +0200 Subject: [PATCH] Charge sculk catalysts when the killing blow lands Mobs die (LivingEntity.die: the death event, catalysts, loot and experience) when they are killed, not when their death animation ends. Catalysts take a death in the dispatcher's order (nearest by exact distance, then visiting order); experience orbs draw their merge id from the level random and their motion from their own. The sculk harness gains catalyst scenarios: kills by the player near catalysts over random terrain, with blooms, charge cursors and the sculk they spread. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 17 ++++- crates/horizon-client/src/game/creatures.rs | 20 +++++- crates/horizon-client/src/game/sculk.rs | 30 +++++--- .../horizon-client/src/game/sculk_fixture.rs | 58 ++++++++++++++++ .../horizonlab/parity/VanillaSculkOracle.java | 39 +++++++++-- tools/test_sculk_parity.py | 69 ++++++++++++++++++- 6 files changed, 214 insertions(+), 19 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 921188bc7..17b699e1d 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -613,6 +613,8 @@ struct Game<'a> { raiding: raids::Raiding, attack_ticks: u32, last_hurt_by_player: HashSet, + /// Mobs whose death (`LivingEntity.die`) has been handled. + died: HashSet, chest_open: HashMap<(i32, i32, i32), (f32, f32)>, /// Item being used (eaten): hotbar slot and ticks used. using: Option<(usize, u32)>, @@ -5987,12 +5989,22 @@ impl Game<'_> { } Ok(false) } - /// ExperienceOrb.award: split into vanilla orb sizes. + /// ExperienceOrb.award: split into vanilla orb sizes. Each orb first + /// tries to merge into an existing one (`tryMergeToExisting` draws its + /// merge id from the level random; orbs here keep no entity id, so the + /// merge itself is not done), then moves off with its own random. fn spawn_orbs(&mut self, at: [f64; 3], mut value: u32) { while value > 0 { let v = ExperienceOrb::split(value); value -= v; - let r = &mut self.world.random; + let _merge_id = self.world.random.next_int_bound(40); + // The orb's own random (unseeded in vanilla), with its rotation draw first. + self.next_entity += 1; + let mut own = horizon_core::random::LegacyRandom::new( + i64::from(self.next_entity) ^ self.world.game_time.wrapping_mul(0x5DEE_CE66D), + ); + let r = &mut own; + let _yaw = r.next_float(); let p = Vec3::new(at[0], at[1], at[2]); self.orbs.push(ExperienceOrb { position: p, @@ -8062,6 +8074,7 @@ pub fn run() -> Result<()> { raiding: Default::default(), attack_ticks: 100, last_hurt_by_player: HashSet::new(), + died: HashSet::new(), chest_open: HashMap::new(), using: None, view: Default::default(), diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index c25a2c25a..73485c876 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -442,11 +442,24 @@ impl Game<'_> { /// The entity phase of `tick_creatures`: every mob's tick, deaths, and the /// projectiles and effects that follow from them. pub(super) fn tick_creature_entities(&mut self) -> Result<()> { + // LivingEntity.die runs when the killing blow lands: mobs killed + // since the last tick (by the player, explosions...) die first. + let killed: Vec = self + .mobs + .iter() + .filter(|m| !m.alive() && !m.removed && !self.died.contains(&m.id)) + .cloned() + .collect(); + for m in killed { + self.died.insert(m.id); + self.mob_died(&m); + } let uuid = self.level.player_uuid; let snapshot: Vec = self.mobs.iter().map(|m| seen(m, uuid)).collect(); let mut events = Vec::new(); let mut mobs = std::mem::take(&mut self.mobs); let mut dead = Vec::new(); + let mut died = std::mem::take(&mut self.died); { let w = self.mob_world_base(&snapshot); let mut scratch = self.world.random.clone(); @@ -458,14 +471,19 @@ impl Game<'_> { return !m.hostile() || m.persistent; } let keep = m.tick(&w, &mut scratch, &mut events); - if !keep && !m.alive() && !m.removed { + // Killed during its own tick (drowning, burning, falling...). + if !m.alive() && !m.removed && died.insert(m.id) { dead.push(m.clone()); } + if !keep { + died.remove(&m.id); + } keep }); push_apart(&mut mobs); } self.mobs.append(&mut mobs); + self.died = died; self.sync_riders(); self.tick_skeleton_traps(); self.tick_apparition(); diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs index 4b2d63944..4f5af29c3 100644 --- a/crates/horizon-client/src/game/sculk.rs +++ b/crates/horizon-client/src/game/sculk.rs @@ -1226,20 +1226,28 @@ impl Game<'_> { at: [f64; 3], experience: impl FnOnce(&mut Self) -> u32, ) -> bool { + // GameEventDispatcher: catalysts are BY_DISTANCE listeners, handled + // nearest first (exact distance to the block centre); a tie keeps the + // order they were visited in: chunk x, chunk z, section y, then the + // order they registered in. The first one takes the experience. let source = block_of(at); - let mut nearest: Option<((i32, i32, i32), i64)> = None; - for key in self.sculk.index.iter().copied() { - let d = dist_sqr(source, key); - if d <= 64 && nearest.is_none_or(|(_, best)| d < best) { - let is_catalyst = matches!( - self.world.block_entities.get(&key), - Some(BlockEntity::Sculk(e)) if e.kind == SculkKind::Catalyst - ); - if is_catalyst { - nearest = Some((key, d)); - } + let mut candidates: Vec<(f64, (i32, i32, i32), usize, (i32, i32, i32))> = Vec::new(); + for (order, key) in self.sculk.index.iter().copied().enumerate() { + if dist_sqr(source, key) > 64 { + continue; + } + let is_catalyst = matches!( + self.world.block_entities.get(&key), + Some(BlockEntity::Sculk(e)) if e.kind == SculkKind::Catalyst + ); + if is_catalyst { + let c = center(key); + let d = (at[0] - c[0]).powi(2) + (at[1] - c[1]).powi(2) + (at[2] - c[2]).powi(2); + candidates.push((d, (key.0 >> 4, key.2 >> 4, key.1 >> 4), order, key)); } } + candidates.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)).then(a.2.cmp(&b.2))); + let nearest = candidates.first().map(|c| (c.3, ())); let Some((key, _)) = nearest else { return false; }; diff --git a/crates/horizon-client/src/game/sculk_fixture.rs b/crates/horizon-client/src/game/sculk_fixture.rs index 9fbd47d09..740d42e93 100644 --- a/crates/horizon-client/src/game/sculk_fixture.rs +++ b/crates/horizon-client/src/game/sculk_fixture.rs @@ -51,6 +51,7 @@ struct Scenario { warning: Option, mobs: Vec, watch: Vec<[i32; 3]>, + regions: Vec<[i32; 6]>, actions: Vec<(i32, Vec)>, } @@ -114,6 +115,10 @@ fn parse(text: &str) -> Vec { f[2].parse().unwrap_or(0), f[3].parse().unwrap_or(0), ]), + "region" => { + let n = |i: usize| f[i].parse::().unwrap_or(0); + s.regions.push([n(1), n(2), n(3), n(4), n(5), n(6)]); + } "at" => s.actions.push(( f[1].parse().unwrap_or(0), f[2..].iter().map(|x| (*x).to_owned()).collect(), @@ -324,6 +329,7 @@ impl Game<'_> { self.sync_tick_chunks(); self.mobs.clear(); self.dropped.clear(); + self.orbs.clear(); self.level_events.clear(); self.ui.rules = Default::default(); for (rule, value) in [ @@ -443,6 +449,17 @@ impl Game<'_> { } } m.random = LegacyRandom::new(spec.seed); + // EntityType.create equips nothing (that is finalizeSpawn's job). + for slot in [ + &mut m.extra.main_hand, + &mut m.extra.off_hand, + &mut m.extra.head, + &mut m.extra.chest, + &mut m.extra.legs, + &mut m.extra.feet, + ] { + *slot = None; + } names.insert(id, format!("m{}", sources.len())); sources.push(id); self.mobs.push(m); @@ -453,7 +470,9 @@ impl Game<'_> { self.audio.capture = Some(Vec::new()); let mut known: HashSet = self.mobs.iter().map(|m| m.id).collect(); let mut known_items = self.dropped.len(); + let mut known_orbs = self.orbs.len(); let mut last: HashMap<[i32; 3], String> = HashMap::new(); + let mut region_last: HashMap<[i32; 3], String> = HashMap::new(); let (mut last_player, mut last_rng) = (String::new(), String::new()); let mut out = String::new(); for t in 0..=s.ticks { @@ -469,6 +488,20 @@ impl Game<'_> { lines.push(format!("blk {},{},{} {line}", p[0], p[1], p[2])); } } + // Regions: every block whose state changed. + for r in &s.regions { + for x in r[0]..=r[3] { + for y in r[1]..=r[4] { + for z in r[2]..=r[5] { + let state = self.fixture_state_text(self.world.block(x, y, z)); + let before = region_last.insert([x, y, z], state.clone()); + if t > 0 && before.as_ref() != Some(&state) { + lines.push(format!("set {x},{y},{z} {state}")); + } + } + } + } + } let tr = self.sculk.tracker; let dark = self .potions @@ -527,6 +560,11 @@ impl Game<'_> { )); } known_items = self.dropped.len(); + // Where an orb flies comes from its own random: its value only. + for orb in &self.orbs[known_orbs.min(self.orbs.len())..] { + lines.push(format!("new minecraft:experience_orb value={}", orb.value)); + } + known_orbs = self.orbs.len(); for line in dispense_fixture::stop_recording() { if let Some(rest) = line.strip_prefix("L ") { lines.push(format!("level {rest}")); @@ -592,6 +630,26 @@ impl Game<'_> { let ctx = self.who_context(who, state); self.post_game_event(event, pos, ctx); } + "kill" => { + // LivingEntity.hurtServer with a player attack. + let id = sources + .get(words[1][1..].parse::().unwrap_or(usize::MAX)) + .copied() + .ok_or("kill: no such mob")?; + let amount = words + .get(2) + .and_then(|a| a.parse::().ok()) + .unwrap_or(1000.0); + let at = self + .player + .as_ref() + .map(|p| [p.position.x, p.position.y, p.position.z]) + .unwrap_or_default(); + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + m.damage(amount, horizon_client::mobs::Damage::player(at)); + } + self.last_hurt_by_player.insert(id); + } "set" => { let n = |i: usize| words[i].parse::().unwrap_or(0); let pos = BlockPos::new(n(1), n(2), n(3)); diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSculkOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSculkOracle.java index b94199720..137d7a4a3 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSculkOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSculkOracle.java @@ -164,6 +164,7 @@ public final class VanillaSculkOracle { int warning = -1; List mobs = new ArrayList<>(); List watch = new ArrayList<>(); + List regions = new ArrayList<>(); List actions = new ArrayList<>(); } @@ -209,6 +210,8 @@ public final class VanillaSculkOracle { for (int i = 7; i < f.length; i++) m.flags.add(f[i]); s.mobs.add(m); } + case "region" -> s.regions.add(new int[] {Integer.parseInt(f[1]), Integer.parseInt(f[2]), Integer.parseInt(f[3]), + Integer.parseInt(f[4]), Integer.parseInt(f[5]), Integer.parseInt(f[6])}); case "watch" -> s.watch.add(new int[] {Integer.parseInt(f[1]), Integer.parseInt(f[2]), Integer.parseInt(f[3])}); case "at" -> { Action a = new Action(); @@ -422,7 +425,7 @@ public final class VanillaSculkOracle { /** Put the flat preset back around the origin: no blocks, block entities, ticks or entities left from the last scenario. */ void reset(Scenario s, ServerLevel level) throws Exception { - for (Entity e : level.getAllEntities()) if (!(e instanceof ServerPlayer)) e.discard(); + for (Entity e : allEntities(level)) if (!(e instanceof ServerPlayer)) e.discard(); BlockState bedrock = net.minecraft.world.level.block.Blocks.BEDROCK.defaultBlockState(); BlockState dirt = net.minecraft.world.level.block.Blocks.DIRT.defaultBlockState(); BlockState grass = net.minecraft.world.level.block.Blocks.GRASS_BLOCK.defaultBlockState(); @@ -443,6 +446,13 @@ public final class VanillaSculkOracle { ((java.util.Collection) get(level, "blockEvents")).clear(); } + /** The level's entities, copied (discarding while iterating leaves holes). */ + static List allEntities(ServerLevel level) { + List all = new ArrayList<>(); + for (Entity e : level.getAllEntities()) if (e != null) all.add(e); + return all; + } + static BlockState parseState(ServerLevel level, String text) throws Exception { return BlockStateParser.parseForBlock(level.holderLookup(Registries.BLOCK), text, false).blockState(); } @@ -528,7 +538,7 @@ public final class VanillaSculkOracle { Method managerTick = method(manager.getClass(), "tick"); managerTick.invoke(manager); Set known = new HashSet<>(); - for (Entity e : level.getAllEntities()) known.add(e); + for (Entity e : allEntities(level)) known.add(e); if (System.getenv("SCULK_TRACE") != null) field(Level.class, "random").set(level, new TracingRandom(0L)); level.getRandom().setSeed(s.levelSeed); Method tickTime = method(ServerLevel.class, "tickTime"); @@ -574,6 +584,18 @@ public final class VanillaSculkOracle { lines.add("blk " + key + " " + line); } } + // Regions: every block whose state changed (all of them at tick 0 are left out). + for (int[] r : s.regions) { + for (int x = r[0]; x <= r[3]; x++) + for (int y = r[1]; y <= r[4]; y++) + for (int z = r[2]; z <= r[5]; z++) { + BlockPos p = new BlockPos(x, y, z); + String key = "r" + pos(p); + String state = BlockStateParser_serialize(level.getBlockState(p)); + String before = last.put(key, state); + if (t > 0 && !state.equals(before)) lines.add("set " + pos(p) + " " + state); + } + } WardenSpawnTracker tracker = player.getWardenSpawnTracker(); MobEffectInstance dark = player.getEffect(MobEffects.DARKNESS); String now = "warn " + tracker.getWarningLevel() + " " @@ -583,7 +605,7 @@ public final class VanillaSculkOracle { lines.add(now); } List fresh = new ArrayList<>(); - for (Entity e : level.getAllEntities()) if (!known.contains(e)) fresh.add(e); + for (Entity e : allEntities(level)) if (!known.contains(e)) fresh.add(e); fresh.sort(Comparator.comparingInt(Entity::getId)); for (Entity e : fresh) { known.add(e); @@ -596,6 +618,11 @@ public final class VanillaSculkOracle { (Map>) get(mob.getBrain(), "sensors"); for (var sensor : sensors.values()) sensor.randomlyDelayStart(mob.getRandom()); } + if (e instanceof net.minecraft.world.entity.ExperienceOrb orb) { + // Where an orb flies comes from its own unseeded random: its value only. + lines.add("new minecraft:experience_orb value=" + orb.getValue()); + continue; + } lines.add("new " + BuiltInRegistries.ENTITY_TYPE.getKey(e.getType()) + " " + d(e.getX()) + "," + d(e.getY()) + "," + d(e.getZ())); } lines.addAll(LOG); @@ -608,7 +635,7 @@ public final class VanillaSculkOracle { for (String line : lines) out.println(t + " " + line); } for (Mob mob : mobs) mob.discard(); - for (Entity e : level.getAllEntities()) if (!(e instanceof ServerPlayer)) e.discard(); + for (Entity e : allEntities(level)) if (!(e instanceof ServerPlayer)) e.discard(); // Out of the way while the next scenario is built. player.snapTo(s.originX + 0.5, 100.0, s.originZ + 0.5, 0.0F, 0.0F); player.removeAllEffects(); @@ -626,6 +653,10 @@ public final class VanillaSculkOracle { BlockState state = w.length > 6 ? parseState(level, w[6]) : null; level.gameEvent(event, at, GameEvent.Context.of(source, state)); } + case "kill" -> { + Mob mob = mobs.get(Integer.parseInt(w[1].substring(1))); + mob.hurtServer(level, level.damageSources().playerAttack(player), Float.parseFloat(w.length > 2 ? w[2] : "1000")); + } case "set" -> level.setBlock(new BlockPos(Integer.parseInt(w[1]), Integer.parseInt(w[2]), Integer.parseInt(w[3])), parseState(level, w[4]), 3); default -> throw new IllegalArgumentException(String.join(" ", w)); } diff --git a/tools/test_sculk_parity.py b/tools/test_sculk_parity.py index 7b182157b..b9c7417a5 100644 --- a/tools/test_sculk_parity.py +++ b/tools/test_sculk_parity.py @@ -107,6 +107,24 @@ def handwritten(): 'at 2 event minecraft:step 3.5 -60 0.5 player']) add('shrieker_creative', 60, [f'block 0 {FLOOR} 0 {SHRIEKER}[can_summon=true]', watch, *near, 'player 3.5 -60 0.5 creative warn=2', 'at 2 event minecraft:step 3.5 -60 0.5 player']) + # Catalysts: a mob killed by the player nearby charges the catalyst, which blooms and spreads sculk. + region = f'region -9 {FLOOR - 3} -9 9 {FLOOR + 3} 9' + # Mobs without loot (items are another harness's work). + for name, mob, floor in [('catalyst_silverfish', 'silverfish', 'minecraft:sculk'), ('catalyst_endermite', 'endermite', 'minecraft:stone'), + ('catalyst_axolotl_grass', 'axolotl', None), ('catalyst_blaze', 'blaze', 'minecraft:deepslate')]: + lines = [f'block 0 {FLOOR} 0 {CATALYST}', watch, region, 'player 5.5 -60 5.5', f'mob minecraft:{mob} 2.5 -60 0.5 0 7 noai', + 'at 3 kill m0'] + if floor: + lines.insert(0, f'fill -6 {FLOOR - 1} -6 6 {FLOOR - 1} 6 {floor}') + add(name, 200, lines) + add('catalyst_far', 60, [f'block 0 {FLOOR} 0 {CATALYST}', watch, region, 'player 5.5 -60 5.5', + 'mob minecraft:silverfish 9.5 -60 0.5 0 7 noai', 'at 3 kill m0']) + add('catalyst_two', 200, [f'block 0 {FLOOR} 0 {CATALYST}', watch, f'block 4 {FLOOR} 0 {CATALYST}', f'watch 4 {FLOOR} 0', region, + f'fill -6 {FLOOR - 1} -6 6 {FLOOR - 1} 6 minecraft:sculk', 'player 5.5 -60 5.5', + 'mob minecraft:endermite 3.5 -60 0.5 0 7 noai', 'mob minecraft:silverfish -1.5 -60 2.5 0 8 noai', + 'at 3 kill m0', 'at 4 kill m1']) + add('catalyst_unkilled', 60, [f'block 0 {FLOOR} 0 {CATALYST}', watch, region, 'player 5.5 -60 5.5', + 'mob minecraft:silverfish 2.5 -60 0.5 0 7 noai', 'at 3 kill m0 3']) return s @@ -167,8 +185,52 @@ def random_scenarios(count, seed): return out +def catalyst_scenarios(count, seed): + """Catalysts over random terrain charged by kills: blooms, cursors, veins, growths.""" + rng = random.Random(seed * 7919 + 13) + out = [] + ground = ['minecraft:stone', 'minecraft:dirt', 'minecraft:deepslate', 'minecraft:sculk', 'minecraft:grass_block', + 'minecraft:moss_block', 'minecraft:tuff', 'minecraft:cobblestone', 'minecraft:sand'] + extras = ['minecraft:stone', 'minecraft:glass', 'minecraft:oak_planks', 'minecraft:water', 'minecraft:sculk_vein[down=true]', + 'minecraft:sculk', 'minecraft:sculk_catalyst', 'minecraft:white_wool', 'minecraft:oak_slab'] + # Mobs without loot (item drops are another harness's work). + mobs = ['silverfish', 'endermite', 'axolotl', 'silverfish', 'vex'] + for n in range(count): + lines = [] + for x in range(-7, 8): + for z in range(-7, 8): + if rng.random() < 0.7: + lines.append(f'block {x} {FLOOR - 1} {z} {rng.choice(ground)}') + cells = {} + for _ in range(rng.randrange(0, 14)): + x, y, z = rng.randrange(-6, 7), FLOOR + rng.randrange(0, 2), rng.randrange(-6, 7) + cells[(x, y, z)] = rng.choice(extras) + for (x, y, z), state in sorted(cells.items(), key=lambda c: c[0][1]): + if y > FLOOR and (x, FLOOR, z) not in cells: + lines.append(f'block {x} {FLOOR} {z} minecraft:stone') + lines.append(f'block {x} {y} {z} {state}') + catalysts = [] + for _ in range(rng.choice([1, 1, 1, 2, 3])): + x, z = rng.randrange(-4, 5), rng.randrange(-4, 5) + catalysts.append((x, z)) + lines.append(f'block {x} {FLOOR} {z} {CATALYST}') + lines.append(f'watch {x} {FLOOR} {z}') + lines.append(f'region -9 {FLOOR - 3} -9 9 {FLOOR + 3} 9') + lines.append(f'player {rng.randrange(-8, 9) + 0.5} {FLOOR + 4} {rng.randrange(-8, 9) + 0.5}') + ticks = rng.choice([120, 200, 300]) + kills = rng.randrange(1, 12) + for i in range(kills): + cx, cz = rng.choice(catalysts) + x, z = cx + rng.randrange(-6, 7) + 0.5, cz + rng.randrange(-6, 7) + 0.5 + lines.append(f'mob minecraft:{rng.choice(mobs)} {x} {FLOOR + 2} {z} 0 {rng.randrange(1000)} noai') + lines.append(f'at {rng.randrange(1, ticks // 2)} kill m{i}') + opts = f'levelseed={rng.randrange(1 << 30)}' + out.append((f'catalyst_random_{n}', ticks, opts, lines)) + return out + + def scenarios(count, seed): - return handwritten() + random_scenarios(count, seed) + return handwritten() + random_scenarios(count, seed) + catalyst_scenarios(count // 3, seed) def write_scenarios(path, chosen): @@ -186,6 +248,11 @@ def write_scenarios(path, chosen): elif f[0] == 'mob': f[2] = repr(float(f[2]) + ox) f[4] = repr(float(f[4]) + oz) + elif f[0] == 'region': + for k in (1, 4): + f[k] = str(int(f[k]) + ox) + for k in (3, 6): + f[k] = str(int(f[k]) + oz) elif f[0] in ('block', 'watch'): f[1] = str(int(f[1]) + ox) f[3] = str(int(f[3]) + oz)