diff --git a/crates/horizon-client/examples/arrow_probe.rs b/crates/horizon-client/examples/arrow_probe.rs index f0447a046..2240dd712 100644 --- a/crates/horizon-client/examples/arrow_probe.rs +++ b/crates/horizon-client/examples/arrow_probe.rs @@ -3,7 +3,7 @@ #![forbid(unsafe_code)] use horizon_client::{ Result, - arrows::{self, ArrowEvent, ArrowParticle, ArrowScene, ArrowSound}, + arrows::{self, ArrowEvent, ArrowParticle, ArrowScene, ArrowSound, BlockReaction}, assets::Assets, blocks::BlockFacts, collisions, @@ -93,6 +93,8 @@ fn main() -> Result<()> { collision: &binding, fluids: &motion.fluids, raining: &no_rain, + mob_griefing: true, + tnt_explodes: true, }; arrows::tick(&mut arrow, &view, &[]); } @@ -144,6 +146,39 @@ fn main() -> Result<()> { )); } } + ArrowEvent::Block { pos, reaction } => match reaction { + BlockReaction::PrimeTnt => { + // TntBlock.prime: PrimedTnt draws its push from the + // level random, then removeBlock(pos, false). + let _ = level_random.next_double(); + let at = Vec3::new( + f64::from(pos.x) + 0.5, + f64::from(pos.y), + f64::from(pos.z) + 0.5, + ); + events.push(format!("spawn tnt {} 80", bits(at))); + events.push(format!( + "sound tnt_primed {:08x} {:08x}", + 1.0f32.to_bits(), + 1.0f32.to_bits() + )); + events.push("prime-event".into()); + let air = + assets.registry.default_state("minecraft:air").unwrap(); + scene.set(pos.x, pos.y, pos.z, air)?; + events.push(format!( + "write {},{},{} {} 3", + pos.x, pos.y, pos.z, air.0 + )); + } + BlockReaction::Light(lit) => { + scene.set(pos.x, pos.y, pos.z, lit)?; + events.push(format!( + "write {},{},{} {} 11", + pos.x, pos.y, pos.z, lit.0 + )); + } + }, ArrowEvent::SplashEvent => events.push("splash-event".into()), ArrowEvent::ShootEvent => events.push("shoot-event".into()), } @@ -175,6 +210,13 @@ fn main() -> Result<()> { )?; } "velocity" => arrow.velocity = vector(&op["value"]), + "ignite" => arrow + .arrow + .as_mut() + .unwrap() + .ignite_for_seconds(f32::from_bits( + u32::from_str_radix(op["value"].as_str().unwrap(), 16).unwrap(), + )), "level_seed" => level_random.set_seed(seed(&op["value"])), other => return Err(format!("unknown operation {other}").into()), } diff --git a/crates/horizon-client/src/arrows.rs b/crates/horizon-client/src/arrows.rs index fae713d31..2f9e4ae34 100644 --- a/crates/horizon-client/src/arrows.rs +++ b/crates/horizon-client/src/arrows.rs @@ -64,6 +64,11 @@ pub enum ArrowEvent { BubbleColumnParticles { pos: BlockPos, }, + /// The block hit reacts (before the arrow sticks). + Block { + pos: BlockPos, + reaction: BlockReaction, + }, /// The SPLASH and PROJECTILE_SHOOT game events. SplashEvent, ShootEvent, @@ -83,6 +88,15 @@ pub enum ArrowSound { /// `entity.generic.extinguish_fire`. Extinguish, } +/// What a burning arrow does to the block it hits (`onProjectileHit`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BlockReaction { + /// `TntBlock.prime` (primed TNT, its sound and PRIME_FUSE), then + /// `removeBlock(pos, false)`. + PrimeTnt, + /// `setBlock(pos, lit=true, 11)`: campfires and candles. + Light(BlockStateId), +} /// The arrow part of `AbstractArrow` and its `Entity` state. #[derive(Clone)] pub struct ArrowState { @@ -157,6 +171,25 @@ impl ArrowState { pub fn clear_fire(&mut self) { self.fire_ticks = self.fire_ticks.min(0); } + /// `Entity.igniteForTicks` (an arrow never freezes). + pub fn ignite_for_ticks(&mut self, ticks: i32) { + if self.fire_ticks < ticks { + self.fire_ticks = ticks; + } + } + /// `Entity.igniteForSeconds`: Flame's `projectile_spawned` ignite. + pub fn ignite_for_seconds(&mut self, seconds: f32) { + self.ignite_for_ticks((seconds * 20.0).floor() as i32); + } + /// `BaseFireBlock.fireIgnite` for an entity that is not a player. + fn fire_ignite(&mut self) { + if self.fire_ticks < 0 { + self.fire_ticks += 1; + } + if self.fire_ticks >= 0 { + self.ignite_for_ticks(160); + } + } } /// The blocks, fluids and weather an arrow flies through. pub struct ArrowScene<'a, 'r> { @@ -167,6 +200,9 @@ pub struct ArrowScene<'a, 'r> { pub fluids: &'a FluidResources, /// `Level.isRainingAt`. pub raining: &'a dyn Fn(BlockPos) -> bool, + /// The `mob_griefing` and `tnt_explodes` game rules. + pub mob_griefing: bool, + pub tnt_explodes: bool, } impl ArrowScene<'_, '_> { fn block(&self, p: BlockPos) -> BlockStateId { @@ -520,8 +556,14 @@ impl Ticker<'_, '_, '_, '_> { } /// `AbstractArrow.onHitBlock`: back off the face by 0.05 along each axis /// it moved on, stop, and stick. - fn on_hit_block(&mut self, _pos: BlockPos, state: BlockStateId) { + fn on_hit_block(&mut self, pos: BlockPos, state: BlockStateId) { self.st.last_state = Some(state); + // Projectile.onHitBlock: BlockState.onProjectileHit. + if self.st.on_fire() + && let Some(reaction) = self.block_reaction(state) + { + self.st.events.push(ArrowEvent::Block { pos, reaction }); + } let v = self.p.velocity; let offset = f64::from(0.05f32); self.p.position = Vec3::new( @@ -541,6 +583,36 @@ impl Ticker<'_, '_, '_, '_> { self.p.set_critical(false); self.st.pierce = 0; } + /// `Projectile.mayInteract`: a mob's arrows need `mob_griefing`. + fn may_interact(&self) -> bool { + !matches!(self.p.owner, Some(Who::Mob(_))) || self.scene.mob_griefing + } + /// `onProjectileHit` of the blocks a burning projectile lights. + fn block_reaction(&self, state: BlockStateId) -> Option { + let name = self.scene.registry.state(state)?.name.as_str(); + let flag = |key: &str| self.scene.property(state, key) == Some("true"); + let lit = || { + let mut definition = self.scene.registry.state(state)?.clone(); + definition.properties.insert("lit".into(), "true".into()); + self.scene.registry.id(&definition) + }; + match name { + "minecraft:tnt" if self.may_interact() && self.scene.tnt_explodes => { + Some(BlockReaction::PrimeTnt) + } + "minecraft:campfire" | "minecraft:soul_campfire" + if self.may_interact() && !flag("lit") && !flag("waterlogged") => + { + lit().map(BlockReaction::Light) + } + // AbstractCandleBlock: candles also must be dry (CandleBlock.canBeLit). + _ if name.ends_with("candle_cake") && !flag("lit") => lit().map(BlockReaction::Light), + _ if name.ends_with("candle") && !flag("lit") && !flag("waterlogged") => { + lit().map(BlockReaction::Light) + } + _ => None, + } + } /// `Entity.applyEffectsFromBlocks(from, to)` for an arrow: the blocks and /// fluids its box passes through (bubble columns push, water puts the fire /// out), then rain. @@ -552,14 +624,22 @@ impl Ticker<'_, '_, '_, '_> { let was_on_fire = self.st.on_fire(); let previous_fire = self.st.fire_ticks; let mut visited = HashSet::new(); - let mut extinguish = false; - let used = self.check_inside_blocks(from, to, &mut visited, &mut extinguish, 16); + let mut effects = Collector::default(); + let used = self.check_inside_blocks(from, to, &mut visited, &mut effects, 16); if 16 - used <= 0 { - self.check_inside_blocks(to, to, &mut visited, &mut extinguish, 1); + self.check_inside_blocks(to, to, &mut visited, &mut effects, 1); } - // StepBasedCollector.applyAndClear: EXTINGUISH. - if extinguish && !self.st.removed { - self.st.clear_fire(); + // StepBasedCollector.applyAndClear. + for effect in effects.finish() { + if self.st.removed { + break; + } + match effect { + Effect::ClearFreeze => {} + Effect::FireIgnite => self.st.fire_ignite(), + Effect::LavaIgnite => self.st.ignite_for_ticks(300), + Effect::Extinguish => self.st.clear_fire(), + } } if self.in_rain() { self.st.clear_fire(); @@ -585,7 +665,7 @@ impl Ticker<'_, '_, '_, '_> { from: Vec3, to: Vec3, visited: &mut HashSet, - extinguish: &mut bool, + effects: &mut Collector, max_iterations: i32, ) -> i32 { let deflated = bounds(to).deflate(Vec3::new( @@ -605,7 +685,7 @@ impl Ticker<'_, '_, '_, '_> { hits.push((p, iteration)); true }); - for (p, _) in hits { + for (p, step) in hits { let state = self.scene.block(p); if self.scene.is_air(state) { continue; @@ -617,7 +697,14 @@ impl Ticker<'_, '_, '_, '_> { if !(inside_block || inside_fluid) || !visited.insert(p) { continue; } - if &*self.scene.facts.get(state).name == "minecraft:bubble_column" { + effects.advance(step); + let name = &*self.scene.facts.get(state).name; + if matches!(name, "minecraft:fire" | "minecraft:soul_fire") { + // BaseFireBlock.entityInside (its inFire hurt does nothing to arrows). + effects.apply(Effect::ClearFreeze); + effects.apply(Effect::FireIgnite); + } + if name == "minecraft:bubble_column" { let precise = far || deflated.intersects(Aabb::new( Vec3::new(f64::from(p.x), f64::from(p.y), f64::from(p.z)), @@ -627,8 +714,18 @@ impl Ticker<'_, '_, '_, '_> { self.bubble_column(state, p); } } - if inside_fluid && matches!(fluid.kind(), FluidKind::Water | FluidKind::FlowingWater) { - *extinguish = true; + if inside_fluid { + effects.advance(step); + match fluid.kind() { + // WaterFluid.entityInside. + FluidKind::Water | FluidKind::FlowingWater => effects.apply(Effect::Extinguish), + // LavaFluid.entityInside (lavaHurt does nothing to arrows). + FluidKind::Lava | FluidKind::FlowingLava => { + effects.apply(Effect::ClearFreeze); + effects.apply(Effect::LavaIgnite); + } + FluidKind::Empty => {} + } } } iterations + 1 @@ -678,6 +775,59 @@ impl Ticker<'_, '_, '_, '_> { } } } +/// `InsideBlockEffectType`s an arrow meets, in their apply order (FREEZE +/// needs powder snow, which an arrow's collision context passes through). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Effect { + ClearFreeze, + FireIgnite, + LavaIgnite, + Extinguish, +} +const EFFECT_ORDER: [Effect; 4] = [ + Effect::ClearFreeze, + Effect::FireIgnite, + Effect::LavaIgnite, + Effect::Extinguish, +]; +/// `InsideBlockEffectApplier.StepBasedCollector`: each step's effects once, +/// in type order, steps in the order they were reached. +struct Collector { + last_step: i32, + step: [bool; 4], + effects: Vec, +} +impl Default for Collector { + fn default() -> Self { + Self { + last_step: -1, + step: [false; 4], + effects: Vec::new(), + } + } +} +impl Collector { + fn advance(&mut self, step: i32) { + if self.last_step != step { + self.last_step = step; + self.flush(); + } + } + fn apply(&mut self, effect: Effect) { + self.step[effect as usize] = true; + } + fn flush(&mut self) { + for effect in EFFECT_ORDER { + if std::mem::take(&mut self.step[effect as usize]) { + self.effects.push(effect); + } + } + } + fn finish(mut self) -> Vec { + self.flush(); + self.effects + } +} struct Tags; impl FluidMembership for Tags { fn fluid_in_tag(&self, kind: FluidKind, tag: FluidTagId) -> bool { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 44010d9aa..4bb26d784 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -6830,6 +6830,12 @@ impl Game<'_> { p, Some(horizon_client::mobs::Who::Player), ); + // Flame: the arrow is spawned burning (EnchantmentHelper.onProjectileSpawned). + if let Some(seconds) = self.bow_projectile_ignite() + && let Some(a) = arrow.arrow.as_mut() + { + a.ignite_for_seconds(seconds); + } let (velocity, on_ground) = self .player .as_ref() diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index b3a616cd7..0d663d520 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -99,6 +99,60 @@ impl ProjectileWorld for ProjWorld<'_, '_> { .full_collision } } +/// `FlameFeatureRenderer`: fire quads stacked up a burning entity's box, +/// turned to the camera around Y, at full block light. `at` is the entity's +/// feet relative to the camera. +fn flame_geometry( + atlas: &horizon_client::hud::HudAtlas, + at: glam::Vec3, + width: f32, + height: f32, + camera_yaw: f32, + light: u8, + out: &mut Vec, +) { + let (Some(fire0), Some(fire1)) = ( + atlas.sprites.get("block/fire_0").copied(), + atlas.sprites.get("block/fire_1").copied(), + ) else { + return; + }; + let s = width * 1.4; + let mut h = height / s; + // Mth.rotationAroundAxis(Y, camera.orientation): the camera's turn about Y. + let turn = glam::Mat3::from_rotation_y(std::f32::consts::PI - camera_yaw.to_radians()); + let lift = 0.3 - (h as i32) as f32 * 0.02; + let packed = (u32::from(light >> 4) * 16) | ((15 * 16) << 8); + let (mut r, mut yo, mut zo, mut ss) = (0.5f32, 0.0f32, 0.0f32, 0); + while h > 0.0 { + let tex = if ss % 2 == 0 { fire0 } else { fire1 }; + let (mut u0, v0, mut u1, v1) = (tex.u0, tex.v0, tex.u1, tex.v1); + if ss / 2 % 2 == 0 { + std::mem::swap(&mut u0, &mut u1); + } + for (x, y, uv) in [ + (-r, -yo, [u1, v1]), + (r, -yo, [u0, v1]), + (r, 1.4 - yo, [u0, v0]), + (-r, 1.4 - yo, [u1, v0]), + ] { + let p = at + turn * glam::Vec3::new(x, y, zo + lift) * s; + out.push(Vertex { + normal: [0; 4], + pos: p.to_array(), + uv, + layer: 0, + color: 0xFFFF_FFFF, + light: packed, + }); + } + h -= 0.45; + yo -= 0.45; + r *= 0.9; + zo -= 0.03; + ss += 1; + } +} pub(super) fn seen(m: &Mob, player: Option<[i32; 4]>) -> Seen { m.seen(player) } @@ -1402,11 +1456,16 @@ impl Game<'_> { collision: w.collision, fluids: &self.motion.fluids, raining: &rain, + mob_griefing: self.ui.rules.bool("mob_griefing"), + tnt_explodes: self.ui.rules.bool("tnt_explodes"), }; + // Arrows also hit minecarts (VehicleEntity is pickable). + let mut arrow_targets = targets.clone(); + arrow_targets.extend(self.carts.iter().map(|c| (Who::Mob(c.id), c.bounds()))); let pw = ProjWorld { w: &w, targets }; projectiles.retain_mut(|p| { let (keep, hit) = if p.arrow.is_some() { - horizon_client::arrows::tick(p, &scene, &pw.targets) + horizon_client::arrows::tick(p, &scene, &arrow_targets) } else { p.tick(&pw) }; @@ -1465,7 +1524,7 @@ impl Game<'_> { } /// What an arrow's tick asked for: its particles and sounds. fn arrow_event(&mut self, at: Vec3, event: horizon_client::arrows::ArrowEvent) { - use horizon_client::arrows::{ArrowEvent, ArrowParticle, ArrowSound}; + use horizon_client::arrows::{ArrowEvent, ArrowParticle, ArrowSound, BlockReaction}; use horizon_client::particles::{ParticleOptions, ParticleType}; let kind = |k| match k { ArrowParticle::Bubble => ParticleType::Bubble, @@ -1525,6 +1584,16 @@ impl Game<'_> { ); } } + ArrowEvent::Block { pos, reaction } => match reaction { + BlockReaction::PrimeTnt => { + self.spawn_primed_tnt(pos, false); + self.with_level(|b, level, ticks| b.remove_block(level, ticks, pos, false)); + let _ = self.process_level_events(); + } + BlockReaction::Light(lit) => { + let _ = self.level_set([pos.x, pos.y, pos.z], lit); + } + }, ArrowEvent::SplashEvent => { self.projectile_event("minecraft:splash", None, [at.x, at.y, at.z]); } @@ -1559,6 +1628,25 @@ impl Game<'_> { self.hit_special(id, amount, p.owner == Some(Who::Player)); return Ok(()); } + if let ( + ProjectileKind::Arrow { .. }, + Hit::Entity { + who: Who::Mob(id), .. + }, + ) = (&p.kind, hit) + && let Some(i) = self.carts.iter().position(|c| c.id == id) + { + // AbstractArrow.onHitEntity on a minecart. + let amount = p.arrow_damage(&mut self.world.random) + p.bonus.damage; + let burning = p.arrow.as_ref().is_some_and(|a| a.on_fire()); + let creative = p.owner == Some(Who::Player) && self.creative; + self.arrow_hits_cart(i, amount, p.velocity, burning, creative); + if let Some((sound, volume, pitch)) = arrow_impact_sound(&mut self.world.random, true) { + self.audio + .play(sound, Some([at.x, at.y, at.z]), volume, pitch); + } + 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); @@ -1586,7 +1674,8 @@ impl Game<'_> { velocity: [p.velocity.x * k, 0.1, p.velocity.z * k], }])?; } - if p.bonus.flame { + // AbstractArrow.onHitEntity: a burning arrow sets its target alight. + if p.arrow.as_ref().is_some_and(|a| a.on_fire()) { self.handle_mob_events(vec![MobEvent::Ignite { target: who, seconds: 5, @@ -2587,6 +2676,9 @@ impl Game<'_> { }); } } + if a.arrow.as_ref().is_some_and(|s| s.on_fire()) { + flame_geometry(atlas, c, 0.5, 0.5, self.yaw, light, out); + } continue; } // WindChargeRenderer. diff --git a/crates/horizon-client/src/game/enchant_effects.rs b/crates/horizon-client/src/game/enchant_effects.rs index 5f98fa52a..7f0bd133e 100644 --- a/crates/horizon-client/src/game/enchant_effects.rs +++ b/crates/horizon-client/src/game/enchant_effects.rs @@ -412,6 +412,45 @@ impl Game<'_> { ) == 0.0; (f64::from(power), infinity) } + /// `EnchantmentHelper.onProjectileSpawned` ignite effects of the held bow + /// (flame): the seconds the new arrow burns for. + pub(super) fn bow_projectile_ignite(&mut self) -> Option { + let bow = self.inventory[self.selected].clone()?; + let ctx = EffectContext { + this: Some("minecraft:arrow"), + items: Some(&self.res.items), + ..Default::default() + }; + let mut ignite: Option = None; + for (id, level) in bow.enchantments() { + let Some(def) = self.res.stations.enchantments.get(id) else { + continue; + }; + for effect in def.effects["minecraft:projectile_spawned"] + .as_array() + .into_iter() + .flatten() + { + if effect["effect"]["type"] != "minecraft:ignite" { + continue; + } + let ok = effect.get("requirements").is_none_or(|r| { + self.res.stations.enchantments.condition( + r, + *level, + &ctx, + &mut self.world.random, + ) + }); + if ok { + let seconds = + horizon_client::enchant::level_value(&effect["effect"]["duration"], *level); + ignite = Some(ignite.map_or(seconds, |s: f32| s.max(seconds))); + } + } + } + ignite + } /// Enchantment attribute modifiers of worn armor (respiration, depth strider...). pub(super) fn apply_enchantment_attributes(&mut self) { let mut wanted: Vec<(String, String, f64, String)> = Vec::new(); diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index c14931e14..1b83adf61 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -1042,18 +1042,46 @@ impl Game<'_> { if !self.before_block(d) || self.mob_hit().is_some_and(|m| m.1 < d) { return false; } + let burning = self + .held() + .is_some_and(|s| s.enchantment_level("minecraft:fire_aspect") > 0); + self.hurt_cart(i, damage, self.creative, burning); + self.swing_arm(); + true + } + /// An arrow hit cart `i` (`MinecartTNT.hurtServer`, then + /// `VehicleEntity.hurtServer`): a burning arrow sets off a TNT minecart. + pub(super) fn arrow_hits_cart( + &mut self, + i: usize, + damage: f32, + arrow_velocity: Vec3, + burning: bool, + creative: bool, + ) { + if i >= self.carts.len() { + return; + } + if burning && self.carts[i].kind == CartKind::Tnt { + let c = self.carts.remove(i); + self.explode_cart(&c, arrow_velocity.length_squared()); + return; + } + self.hurt_cart(i, damage, creative, false); + } + /// `VehicleEntity.hurtServer`: shake, add the damage, break past 40 (at + /// once for creative players); TNT minecarts prime instead when moving + /// or hurt by fire. + fn hurt_cart(&mut self, i: usize, damage: f32, creative: bool, fire: bool) { let c = &mut self.carts[i]; c.hurt_dir = -c.hurt_dir; c.hurt_time = 10; c.damage += damage * 10.0; - let destroyed = self.creative || c.damage > 40.0; + let destroyed = creative || c.damage > 40.0; if destroyed { let mut c = self.carts.remove(i); let speed = c.velocity.x * c.velocity.x + c.velocity.z * c.velocity.z; - let burning = self - .held() - .is_some_and(|s| s.enchantment_level("minecraft:fire_aspect") > 0); - if c.kind == CartKind::Tnt && (burning || speed >= 0.01) { + if c.kind == CartKind::Tnt && (fire || speed >= 0.01) { // MinecartTNT.destroy: prime instead of breaking. if c.fuse < 0 { self.prime_cart(&mut c); @@ -1067,14 +1095,12 @@ impl Game<'_> { for s in c.items.iter().flatten() { self.spawn_item(s.clone(), at, [0.0, 0.1, 0.0], 10); } - if !self.creative { + if !creative { self.spawn_item(ItemStack::new(c.kind.id(), 1), at, [0.0, 0.1, 0.0], 10); } } } } - self.swing_arm(); - true } /// A block model's faces under `m` (block space 0..1), lit flat. fn block_model_vertices( diff --git a/crates/horizon-client/src/mobs/illager.rs b/crates/horizon-client/src/mobs/illager.rs index 15be02a1d..45ef076d3 100644 --- a/crates/horizon-client/src/mobs/illager.rs +++ b/crates/horizon-client/src/mobs/illager.rs @@ -541,7 +541,7 @@ fn shoot_crossbow(m: &mut Mob, who: Who, cx: &mut Cx) { start, Some(Who::Mob(m.id)), ); - p.bonus = super::gear::arrow_bonus(m); + p.set_bonus(super::gear::arrow_bonus(m)); // rangedAttackUncertainty at normal difficulty: 14 - 2 * 4. p.shoot( &mut crate::projectiles::own_random(m), diff --git a/crates/horizon-client/src/mobs/undead.rs b/crates/horizon-client/src/mobs/undead.rs index b6986f6d1..197321dea 100644 --- a/crates/horizon-client/src/mobs/undead.rs +++ b/crates/horizon-client/src/mobs/undead.rs @@ -755,7 +755,7 @@ pub fn perform_ranged_attack(m: &mut Mob, who: Who, cx: &mut Cx, power: f32) { start, Some(Who::Mob(m.id)), ); - p.bonus = super::gear::arrow_bonus(m); + p.set_bonus(super::gear::arrow_bonus(m)); p.shoot( &mut arrow_random, [xd, yd + dist * 0.2, zd], diff --git a/crates/horizon-client/src/projectiles.rs b/crates/horizon-client/src/projectiles.rs index 1fd9495c1..220ebb236 100644 --- a/crates/horizon-client/src/projectiles.rs +++ b/crates/horizon-client/src/projectiles.rs @@ -156,6 +156,16 @@ impl Projectile { } self } + /// The shooter's bow enchantments; Flame spawns the arrow burning for 100 + /// seconds (`projectile_spawned` ignite). + pub fn set_bonus(&mut self, bonus: crate::mobs::gear::ArrowBonus) { + if bonus.flame + && let Some(a) = self.arrow.as_mut() + { + a.ignite_for_seconds(100.0); + } + self.bonus = bonus; + } /// `AbstractArrow.isCritArrow`. pub fn critical(&self) -> bool { matches!(self.kind, ProjectileKind::Arrow { critical: true, .. }) diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaArrowOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaArrowOracle.java index bcbf66c7d..88b7fcee3 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaArrowOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaArrowOracle.java @@ -24,15 +24,16 @@ import static dev.horizonlab.parity.VanillaRegistryCollisionScanOracle.*; /** Real arrows (`Arrow`, through `AbstractArrow.tick`) over an independently * built copy of the development client's resident scene: flight, water inertia * and bubbles, fluid currents and splashes, bubble columns, sticking in blocks, - * falling out when the block goes, and despawning. No entities to hit, no rain, - * no owner; sounds, particles and game events are recorded in order. */ + * falling out when the block goes, and despawning. Burning arrows: lava and fire along + * the path, water putting them out, and the blocks they light (TNT, campfires, + * candles). No entities to hit, no rain, no owner; sounds, particles and game events are recorded in order. */ public final class VanillaArrowOracle { static final class Border extends WorldBorder { @Override public boolean isInsideCloseToBorder(Entity e,AABB b){return false;} } static String bits(Vec3 v){return String.format("%016x,%016x,%016x",Double.doubleToLongBits(v.x),Double.doubleToLongBits(v.y),Double.doubleToLongBits(v.z));} static String sound(SoundEvent s){ - if(s==SoundEvents.ARROW_HIT)return "hit";if(s==SoundEvents.GENERIC_SPLASH)return "splash";if(s==SoundEvents.GENERIC_EXTINGUISH_FIRE)return "extinguish"; + if(s==SoundEvents.ARROW_HIT)return "hit";if(s==SoundEvents.TNT_PRIMED)return "tnt_primed";if(s==SoundEvents.GENERIC_SPLASH)return "splash";if(s==SoundEvents.GENERIC_EXTINGUISH_FIRE)return "extinguish"; throw new AssertionError("unexpected sound "+s); } static String particle(net.minecraft.core.particles.ParticleOptions p){ @@ -40,6 +41,14 @@ public final class VanillaArrowOracle { if(p==net.minecraft.core.particles.ParticleTypes.SPLASH)return "splash"; throw new AssertionError("unexpected particle "+p); } + /** Lava, fire and burning hurt arrows not at all (Projectile.hurtServer only + * marks them hurt): untagged stand-in sources. */ + static final class Sources extends net.minecraft.world.damagesource.DamageSources { + net.minecraft.world.damagesource.DamageSource any;Sources(){super(null);} + @Override public net.minecraft.world.damagesource.DamageSource lava(){return any;} + @Override public net.minecraft.world.damagesource.DamageSource inFire(){return any;} + @Override public net.minecraft.world.damagesource.DamageSource onFire(){return any;} + } static final class Level extends net.minecraft.server.level.ServerLevel { Map chunks;WorldBorder border;net.minecraft.util.RandomSource rng;List events;net.minecraft.server.MinecraftServer server; static final net.minecraft.world.attribute.EnvironmentAttributeSystem ATTRIBUTES=net.minecraft.world.attribute.EnvironmentAttributeSystem.builder().build(); @@ -62,7 +71,20 @@ public final class VanillaArrowOracle { if(event==GameEvent.PROJECTILE_SHOOT)events.add("shoot-event");else if(event==GameEvent.SPLASH)events.add("splash-event");else throw new AssertionError(event); } // Projectile.onHit's PROJECTILE_LAND: the game posts it from the hit it is handed. - @Override public void gameEvent(Holder event,BlockPos pos,GameEvent.Context context){if(event!=GameEvent.PROJECTILE_LAND)throw new AssertionError(event);} + @Override public void gameEvent(Holder event,BlockPos pos,GameEvent.Context context){ + if(event==GameEvent.PRIME_FUSE)events.add("prime-event");else if(event!=GameEvent.PROJECTILE_LAND)throw new AssertionError(event); + } + net.minecraft.world.level.gamerules.GameRules rules;Sources sources; + @Override public net.minecraft.world.damagesource.DamageSources damageSources(){return sources;} + @Override public net.minecraft.world.level.gamerules.GameRules getGameRules(){return rules;} + // onProjectileHit's block changes (campfires, candles, TNT's removal). + @Override public boolean setBlock(BlockPos p,BlockState state,int flags){ + chunks.get(key(p.getX()>>4,p.getZ()>>4)).write(p,Block.getId(state));events.add("write "+p.getX()+","+p.getY()+","+p.getZ()+" "+Block.getId(state)+" "+flags);return true; + } + @Override public boolean addFreshEntity(Entity e){ + if(!(e instanceof net.minecraft.world.entity.item.PrimedTnt tnt))throw new AssertionError(e); + events.add("spawn tnt "+bits(tnt.position())+" "+tnt.getFuse());return true; + } @Override public void playSound(Entity except,double x,double y,double z,SoundEvent s,SoundSource source,float volume,float pitch){ events.add(String.format("sound %s %08x %08x",sound(s),Float.floatToIntBits(volume),Float.floatToIntBits(pitch))); } @@ -90,6 +112,10 @@ public final class VanillaArrowOracle { var trace=new Trace();trace.out=new PrintWriter(OutputStream.nullOutputStream());trace.fail=-1; var level=(Level)allocate.invoke(unsafe,Level.class);level.chunks=VanillaSceneCollisionOracle.scene(description,trace);level.border=new Border(); level.rng=net.minecraft.util.RandomSource.create(0);level.events=new ArrayList<>(); + field(net.minecraft.world.level.Level.class,"random").set(level,level.rng); + level.rules=new net.minecraft.world.level.gamerules.GameRules(net.minecraft.world.flag.FeatureFlagSet.of()); + level.sources=(Sources)allocate.invoke(unsafe,Sources.class); + level.sources.any=new net.minecraft.world.damagesource.DamageSource(Holder.direct(new net.minecraft.world.damagesource.DamageType("generic",0.0F))); var server=(VanillaBlockLandingOracle.Server)allocate.invoke(unsafe,VanillaBlockLandingOracle.Server.class); server.d=new VanillaBlockLandingOracle.Data();server.d.out=new PrintWriter(OutputStream.nullOutputStream());server.d.f=JsonParser.parseString("{\"fail\":-1,\"protected\":false}").getAsJsonObject();level.server=server; field(net.minecraft.server.MinecraftServer.class,"debugSubscribers").set(server,new net.minecraft.util.debug.ServerDebugSubscribers(server)); @@ -114,6 +140,8 @@ public final class VanillaArrowOracle { VanillaSceneCollisionOracle.put(level.chunks,v.get(0).getAsInt(),v.get(1).getAsInt(),v.get(2).getAsInt(),state); } case "velocity"->a.setDeltaMovement(VanillaSceneCollisionOracle.vector(op.get("value"))); + // Flame's projectile_spawned ignite. + case "ignite"->a.igniteForSeconds(Float.intBitsToFloat(Integer.parseUnsignedInt(op.get("value").getAsString(),16))); case "level_seed"->level.rng.setSeed(seed(op.get("value"))); default->throw new AssertionError(op); } diff --git a/tools/test_arrow_parity.py b/tools/test_arrow_parity.py index ca6bbd7d4..d511b5db5 100644 --- a/tools/test_arrow_parity.py +++ b/tools/test_arrow_parity.py @@ -11,8 +11,10 @@ order. Cases: flights in the air with and without crits or physics, into and through water (inertia, bubbles, splashes, currents of flowing water, eyes), kelp, seagrass and waterlogged blocks, bubble columns with and without drag and with air or water above, sticking in full and partial blocks, falling out -when the block goes, starting inside a block, and despawning after 1200 ticks. -No entities, owner, rain, lava or fire. +when the block goes, starting inside a block, and despawning after 1200 ticks; +burning arrows: lava and fire blocks lighting them, water putting them out, +Flame (ignited at spawn), and TNT, campfires, candles and candle cakes hit by +burning and non-burning arrows. No entities, owner or rain. """ import json import os @@ -106,6 +108,51 @@ def corpus(): # Starting inside a block: stopped in place. for name in ['stone', 'oak_slab', 'oak_fence']: yield arrow((25.5, 9.25, 25.5), (.4, 0, .1), place(name, [(25, 9, 25)]) + ticks(10) + restore([(25, 9, 25)])) + # Fire: lava pools and fire blocks light arrows (LAVA_IGNITE 15 s, fireIgnite + # 8 s after counting up from below zero), water puts them out with the + # extinguish sound, burning arrows keep their fire while stuck. + def ignite(seconds): + return op('ignite', struct.pack('>f', seconds).hex()) + lava = [(x, y, z) for x in range(20, 27) for y in range(4, 6) for z in range(20, 27)] + for level in ['0', '0', '4']: + for _ in range(6): + v = aim(rng.choice([.4, 1.3, 2.6]), rng.uniform(-50, 50), rng.uniform(0, 50)) + ops = place('lava', lava, {'level': level}) + ticks(60) + restore(lava) + yield arrow((rng.uniform(20, 27), rng.uniform(7, 11), rng.uniform(16, 19)), v, ops) + for _ in range(6): + # Through lava, then into water beyond it (and the other way round). + lava_wall = [(23, y, z) for y in range(4, 9) for z in range(20, 27)] + water_wall = [(26, y, z) for y in range(4, 9) for z in range(20, 27)] + first, second = rng.choice([('lava', 'water'), ('water', 'lava')]) + ops = place(first, lava_wall) + place(second, water_wall) + ticks(40) + restore(lava_wall + water_wall) + yield arrow((20.5, 6.5, rng.uniform(21, 26)), aim(rng.choice([.8, 2.0, 3.0]), -90, rng.uniform(-5, 5)), ops) + for name in ['fire', 'soul_fire']: + flames = [(x, 4, z) for x in range(22, 27) for z in range(22, 27)] + base = [] if name == 'fire' else place('soul_sand', [(x, 3, z) for x in range(22, 27) for z in range(22, 27)]) + for _ in range(5): + ops = base + place(name, flames) + ticks(50) + restore(flames) + if name == 'soul_fire': + ops += place('stone', [(x, 3, z) for x in range(22, 27) for z in range(22, 27)]) + v = aim(rng.choice([.3, 1.0, 2.0]), rng.uniform(-40, 40), rng.uniform(10, 60)) + yield arrow((rng.uniform(22, 27), rng.uniform(6, 9), rng.uniform(19, 21)), v, ops) + # Flame arrows (100 s): flying, into water, stuck. + pool = [(x, y, z) for x in range(20, 29) for y in range(4, 7) for z in range(20, 29)] + for target in [None, 'water']: + for _ in range(5): + ops = [ignite(100.0)] + (place('water', pool) if target else []) + ticks(70) + (restore(pool) if target else []) + v = aim(rng.choice([.5, 1.5, 3.0]), rng.uniform(-60, 60), rng.uniform(-20, 40)) + yield arrow((rng.uniform(20, 28), rng.uniform(7, 12), rng.uniform(16, 19)), v, ops, crit=rng.random() < .5) + # Burning (and not burning) arrows hitting the blocks a burning projectile lights. + lights = [('tnt', {}), ('campfire', {'lit': 'false'}), ('campfire', {'lit': 'true'}), ('campfire', {'lit': 'false', 'waterlogged': 'true'}), + ('soul_campfire', {'lit': 'false'}), ('candle', {'candles': '3', 'lit': 'false'}), ('red_candle', {'lit': 'false', 'waterlogged': 'true'}), + ('candle', {'lit': 'true'}), ('candle_cake', {'lit': 'false'}), ('blue_candle_cake', {'lit': 'true'}), ('stone', {})] + for name, properties in lights: + for burning in [False, True]: + target = [(25, 9, 25)] + v = rng.choice([(0, -1.2, 0), (.9, -.2, 0), (0, -.3, -.9)]) + start = (25.5 - v[0] * 3, 9.3 - v[1] * 3, 25.5 - v[2] * 3) + ops = ([ignite(rng.choice([1.0, 8.5, 100.0]))] if burning else []) + place(name, target, properties) + ticks(30) + restore(target) + yield arrow(start, v, ops) # Despawning 1200 ticks after sticking in the floor. for _ in range(2): yield arrow((rng.uniform(18, 30), 6, rng.uniform(4, 30)), (0, -1, 0), ticks(1215))