Add primed TNT with an 80-tick fuse and port ServerExplosion

PrimedTnt entities (gravity, drag, bounce, fuse) spawn from redstone, fire,
flint and steel / fire charges, unstable TNT broken by players and chain
explosions (random short fuse). TntRenderer swell and white flash via a new
entity overlay. Explosions use vanilla ray marching over a Java HashSet
(matching iteration and shuffle draws), exposure-scaled damage and knockback
for players, mobs, items and TNT, TNT drops without decay, merged drops and
container contents.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-08 15:29:46 +02:00
parent cc32d9e8a0
commit 33396ebff1
5 changed files with 741 additions and 82 deletions
+5 -1
View File
@@ -21,6 +21,7 @@ struct Out {
@location(1) color: vec4<f32>,
@location(2) spherical: f32,
@location(3) cylindrical: f32,
@location(4) flash: f32,
}
@vertex fn vs_entity(@location(0) position: vec3<f32>, @location(1) uv: vec2<f32>,
@location(2) overlay: u32, @location(3) color: vec4<f32>, @location(4) light: vec4<u32>) -> Out {
@@ -35,6 +36,8 @@ struct Out {
// Hurt overlay (OverlayTexture red tint).
if overlay == 1u { c = vec4(mix(c.rgb, vec3(1.0, 0.0, 0.0), 0.3), c.a); }
out.color = c;
// Overlay 4: OverlayTexture white flash (primed TNT), applied after texturing.
out.flash = select(0.0, 0.75, overlay == 4u);
// Sky geometry (clouds, celestial bodies) is exempt from render-distance fog.
out.spherical = select(length(position), 0.0, overlay >= 2u);
out.cylindrical = select(max(length(position.xz), abs(position.y)), 0.0, overlay >= 2u);
@@ -46,8 +49,9 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 {
return (d - start) / (end - start);
}
@fragment fn fs_entity(in: Out) -> @location(0) vec4<f32> {
let color = textureSample(atlas, atlas_sampler, in.uv) * in.color;
var color = textureSample(atlas, atlas_sampler, in.uv) * in.color;
if color.a < 0.1 { discard; }
color = vec4(mix(color.rgb, vec3(1.0), in.flash), color.a);
let f = max(linear_fog(in.spherical, globals.fog.x, globals.fog.y),
linear_fog(in.cylindrical, globals.fog.z, globals.fog.w));
return vec4(mix(color.rgb, globals.fog_color.rgb, f * globals.fog_color.a), color.a);
+13 -80
View File
@@ -2,7 +2,9 @@
//! block interaction, inventory and HUD.
mod blockctl;
mod control;
mod explosion;
mod growth;
mod tnt;
use horizon_client::{
Result,
assets::Assets,
@@ -393,6 +395,7 @@ struct Game<'a> {
tick_chunks: HashSet<(i32, i32)>,
level_events: Vec<LevelEvent>,
falling: Vec<FallingBlock>,
tnts: Vec<tnt::PrimedTnt>,
creative_screen: Creative,
control: Option<horizon_client::control::Server>,
frame_stats: horizon_client::control::FrameStats,
@@ -821,10 +824,7 @@ impl Game<'_> {
}
PlayerEffect::InteractLoot(_) | PlayerEffect::RespawnAnchor => {}
},
LevelEvent::PrimeTnt { pos } => {
// Simplified: TNT explodes after its 80-tick fuse immediately.
self.explode([f64::from(pos.x) + 0.5, f64::from(pos.y), f64::from(pos.z) + 0.5], 4.0)?;
}
LevelEvent::PrimeTnt { pos } => self.spawn_primed_tnt(pos, false),
LevelEvent::BlockEvent { pos, state, kind: "pop_block_item" } => {
let item = self.res.facts.get(state).item.clone();
self.pop_resource([pos.x, pos.y, pos.z], ItemStack { item, count: 1, damage: 0 });
@@ -1000,7 +1000,7 @@ impl Game<'_> {
}
return Ok(());
}
if self.use_bone_meal(&stack)? {
if self.use_bone_meal(&stack)? || self.ignite_tnt(&stack)? {
return Ok(());
}
if self.use_tool(&stack)? {
@@ -1403,6 +1403,7 @@ impl Game<'_> {
self.tick_portal()?;
self.tick_blocks()?;
self.tick_falling()?;
self.tick_tnt()?;
if let Some(p) = &self.player {
// Player.aiStep bob and Entity.walkDist (0.6 per block).
let (dx, dz) = (p.position.x - self.previous_position.x, p.position.z - self.previous_position.z);
@@ -2234,6 +2235,7 @@ impl Game<'_> {
}
}
}
self.tnt_geometry(camera, alpha, &mut out);
// Camera-facing particle quads.
let (yaw, pitch) = (self.yaw.to_radians(), self.pitch.to_radians());
let forward = glam::Vec3::new(-yaw.sin() * pitch.cos(), -pitch.sin(), yaw.cos() * pitch.cos());
@@ -2489,82 +2491,10 @@ impl Game<'_> {
true
}
/// ServerExplosion: rays from a 16^3 grid lose (resistance + 0.3) * 0.3 per step.
/// A mob explosion (`Level.ExplosionInteraction.MOB`: drop decay with the
/// default mobGriefing rule).
fn explode(&mut self, center: [f64; 3], radius: f32) -> Result<()> {
let mut destroyed = HashSet::new();
for j in 0..16 {
for k in 0..16 {
for l in 0..16 {
if !(j == 0 || j == 15 || k == 0 || k == 15 || l == 0 || l == 15) {
continue;
}
let mut d = [f64::from(j) / 15.0 * 2.0 - 1.0, f64::from(k) / 15.0 * 2.0 - 1.0, f64::from(l) / 15.0 * 2.0 - 1.0];
let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
d = d.map(|v| v / len);
let mut h = radius * (0.7 + self.world.random.next_float() * 0.6);
let mut p = center;
while h > 0.0 {
let b = [p[0].floor() as i32, p[1].floor() as i32, p[2].floor() as i32];
let state = self.world.block(b[0], b[1], b[2]);
if !self.res.facts.is_air(state) {
let f = self.res.facts.get(state);
let resistance = if f.fluid != Fluid::None && !f.waterlogged { 100.0 } else { f.explosion_resistance };
h -= (resistance + 0.3) * 0.3;
if h > 0.0 && f.hardness >= 0.0 {
destroyed.insert(b);
}
}
p = [p[0] + d[0] * 0.3, p[1] + d[1] * 0.3, p[2] + d[2] * 0.3];
h -= 0.225_000_01;
}
}
}
}
for b in destroyed {
let state = self.world.block(b[0], b[1], b[2]);
if self.res.facts.is_air(state) {
continue;
}
// Explosion decay: each drop survives with probability 1 / radius.
if self.world.random.next_float() < 1.0 / radius {
let drops = self.res.items.block_drops(&self.res.assets.registry, state, None, &mut self.world.random);
for d in drops {
self.pop_resource(b, d);
}
}
self.world.set(b[0], b[1], b[2], self.world.air)?;
}
self.audio.play("minecraft:entity.generic.explode", Some(center), 4.0, (1.0 + (self.world.random.next_float() - self.world.random.next_float()) * 0.2) * 0.7);
// Entity damage by distance (exposure approximated as unobstructed).
let diameter = f64::from(radius) * 2.0;
let mut armor_damage = None;
if let Some(player) = self.player.as_mut() {
let p = [player.position.x, player.position.y, player.position.z];
let dist = ((p[0] - center[0]).powi(2) + (p[1] - center[1]).powi(2) + (p[2] - center[2]).powi(2)).sqrt() / diameter;
if dist <= 1.0 {
let impact = 1.0 - dist;
let damage = ((impact * impact + impact) / 2.0 * 7.0 * diameter + 1.0) as f32;
if let Some(id) = self.motion.health.damage.id("minecraft:explosion") {
let _ = player.hurt(&self.motion.health, self.world.health_rules, id, damage);
armor_damage = Some(damage);
}
let (dx, dy, dz) = (p[0] - center[0], p[1] - center[1], p[2] - center[2]);
let l = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-4);
player.velocity = Vec3::new(player.velocity.x + dx / l * impact, player.velocity.y + dy / l * impact, player.velocity.z + dz / l * impact);
}
}
if let Some(d) = armor_damage
&& !self.creative
{
self.hurt_armor(d);
}
for m in &mut self.mobs {
let dist = ((m.position.x - center[0]).powi(2) + (m.position.y - center[1]).powi(2) + (m.position.z - center[2]).powi(2)).sqrt() / diameter;
if dist <= 1.0 && m.alive() {
let impact = 1.0 - dist;
m.hurt(((impact * impact + impact) / 2.0 * 7.0 * diameter + 1.0) as f32, Some(center), &mut self.world.random);
}
}
Ok(())
self.server_explode(center, radius, explosion::BlockInteraction::DestroyWithDecay, false)
}
fn tick_block_entities(&mut self) -> Result<()> {
// ChestLidController: 0.1 per tick towards open/closed.
@@ -2943,6 +2873,7 @@ impl Game<'_> {
self.install_live_features();
self.tick_chunks.clear();
self.falling.clear();
self.tnts.clear();
self.travelling = None;
self.player = None;
self.spawn = None;
@@ -3021,6 +2952,7 @@ impl Game<'_> {
self.block_ticks = Ticks::new(self.level.seed as i32);
self.tick_chunks.clear();
self.falling.clear();
self.tnts.clear();
self.mobs.clear();
self.arrows.clear();
self.dropped.clear();
@@ -4821,6 +4753,7 @@ pub fn run() -> Result<()> {
tick_chunks: HashSet::new(),
level_events: Vec::new(),
falling: Vec::new(),
tnts: Vec::new(),
creative_screen: Creative::load(&game_root)?,
control: None,
frame_stats: Default::default(),
+460
View File
@@ -0,0 +1,460 @@
//! `ServerExplosion`: exploded positions (vanilla ray march over a Java
//! HashSet, so iteration and the following shuffle match vanilla's random
//! draws), entity damage with exposure and knockback, block interaction with
//! merged drops and TNT chain priming, and optional fire.
use super::Game;
use horizon_client::{Result, blocks::Fluid, items::ItemStack};
use horizon_core::{
geometry::Vec3,
position::BlockPos,
random::{LegacyRandom, RandomSource},
};
use horizon_world::java_hash_map::{JavaHashMap, JavaKey};
use std::cmp::Ordering;
/// `BlockPos` with Java `Vec3i.hashCode` / `compareTo`.
#[derive(Clone, Copy, PartialEq, Eq)]
struct Key([i32; 3]);
impl JavaKey for Key {
fn java_hash(&self) -> i32 {
let [x, y, z] = self.0;
y.wrapping_add(z.wrapping_mul(31))
.wrapping_mul(31)
.wrapping_add(x)
}
fn comparable_compare(&self, other: &Self) -> Option<Ordering> {
let ([x, y, z], [ox, oy, oz]) = (self.0, other.0);
Some(y.cmp(&oy).then(z.cmp(&oz)).then(x.cmp(&ox)))
}
fn tie_break(&self, _other: &Self) -> Ordering {
Ordering::Less
}
}
/// `Explosion.BlockInteraction` for the explosions Horizon produces.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum BlockInteraction {
Keep,
Destroy,
DestroyWithDecay,
}
thread_local! {
/// Client-side randomness (explosion sound pitch), separate from the level random.
static CLIENT_RANDOM: std::cell::RefCell<LegacyRandom> = std::cell::RefCell::new(LegacyRandom::new(0x5eed));
}
pub(super) fn client_float() -> f32 {
CLIENT_RANDOM.with(|r| r.borrow_mut().next_float())
}
impl Game<'_> {
/// `Level.clip(from, to, COLLIDER, NONE)` missing every block, with full
/// collision cubes as obstacles.
fn clear_line(&self, from: [f64; 3], to: [f64; 3]) -> bool {
let d = [to[0] - from[0], to[1] - from[1], to[2] - from[2]];
let length = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
let steps = (length / 0.1).ceil().max(1.0) as i32;
let mut last = [i32::MIN; 3];
for i in 0..=steps {
let t = f64::from(i) / f64::from(steps);
let b = [
(from[0] + d[0] * t).floor() as i32,
(from[1] + d[1] * t).floor() as i32,
(from[2] + d[2] * t).floor() as i32,
];
if b == last {
continue;
}
last = b;
if self
.res
.facts
.get(self.world.block(b[0], b[1], b[2]))
.full_collision
{
return false;
}
}
true
}
/// `ServerExplosion.getSeenPercent` for an entity box.
fn seen_percent(&self, center: [f64; 3], min: [f64; 3], max: [f64; 3]) -> f32 {
let xs = 1.0 / ((max[0] - min[0]) * 2.0 + 1.0);
let ys = 1.0 / ((max[1] - min[1]) * 2.0 + 1.0);
let zs = 1.0 / ((max[2] - min[2]) * 2.0 + 1.0);
let x_offset = (1.0 - (1.0 / xs).floor() * xs) / 2.0;
let z_offset = (1.0 - (1.0 / zs).floor() * zs) / 2.0;
if xs < 0.0 || ys < 0.0 || zs < 0.0 {
return 0.0;
}
let (mut hits, mut count) = (0, 0);
let mut xx = 0.0;
while xx <= 1.0 {
let mut yy = 0.0;
while yy <= 1.0 {
let mut zz = 0.0;
while zz <= 1.0 {
let x = min[0] + (max[0] - min[0]) * xx;
let y = min[1] + (max[1] - min[1]) * yy;
let z = min[2] + (max[2] - min[2]) * zz;
if self.clear_line([x + x_offset, y, z + z_offset], center) {
hits += 1;
}
count += 1;
zz += zs;
}
yy += ys;
}
xx += xs;
}
hits as f32 / count as f32
}
/// `ServerExplosion.calculateExplodedPositions`.
fn exploded_positions(&mut self, center: [f64; 3], radius: f32) -> Vec<[i32; 3]> {
let (min_y, max_y) = self.with_level(|_, level, _| {
use horizon_world::level::LevelAccess;
(level.min_y(), level.max_y())
});
let mut set: JavaHashMap<Key, ()> = JavaHashMap::default();
for xx in 0..16 {
for yy in 0..16 {
for zz in 0..16 {
if !(xx == 0 || xx == 15 || yy == 0 || yy == 15 || zz == 0 || zz == 15) {
continue;
}
let mut xd = f64::from(xx as f32 / 15.0 * 2.0 - 1.0);
let mut yd = f64::from(yy as f32 / 15.0 * 2.0 - 1.0);
let mut zd = f64::from(zz as f32 / 15.0 * 2.0 - 1.0);
let d = (xd * xd + yd * yd + zd * zd).sqrt();
xd /= d;
yd /= d;
zd /= d;
let mut power = radius * (0.7 + self.world.random.next_float() * 0.6);
let (mut xp, mut yp, mut zp) = (center[0], center[1], center[2]);
while power > 0.0 {
let pos = [xp.floor() as i32, yp.floor() as i32, zp.floor() as i32];
if pos[1] < min_y
|| pos[1] >= max_y
|| !(-30_000_000..30_000_000).contains(&pos[0])
|| !(-30_000_000..30_000_000).contains(&pos[2])
{
break;
}
let state = self.world.block(pos[0], pos[1], pos[2]);
let f = self.res.facts.get(state);
let fluid = if f.fluid != Fluid::None {
100.0f32
} else {
0.0
};
if !self.res.facts.is_air(state) || f.fluid != Fluid::None {
power -= (f.explosion_resistance.max(fluid) + 0.3) * 0.3;
}
if power > 0.0 {
set.put(Key(pos), ());
}
xp += xd * f64::from(0.3f32);
yp += yd * f64::from(0.3f32);
zp += zd * f64::from(0.3f32);
power -= 0.225_000_01;
}
}
}
}
set.entries().map(|(k, _)| k.0).collect()
}
/// `ServerExplosion.hurtEntities` (player, mobs, items, primed TNT).
fn explosion_hurt_entities(&mut self, center: [f64; 3], radius: f32) {
if radius < 1.0e-5 {
return;
}
let diameter = f64::from(radius * 2.0);
let distance = |p: [f64; 3]| {
((p[0] - center[0]).powi(2) + (p[1] - center[1]).powi(2) + (p[2] - center[2]).powi(2))
.sqrt()
};
let damage = |dist: f64, exposure: f32| {
let pow = (1.0 - dist) * f64::from(exposure);
((pow * pow + pow) / 2.0 * 7.0 * diameter + 1.0) as f32
};
let direction = |origin: [f64; 3]| {
let d = [
origin[0] - center[0],
origin[1] - center[1],
origin[2] - center[2],
];
let l = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
if l < 1.0e-4 {
[0.0; 3]
} else {
[d[0] / l, d[1] / l, d[2] / l]
}
};
// Player.
if let Some(p) = self.player.as_ref() {
let feet = [p.position.x, p.position.y, p.position.z];
let dist = distance(feet) / diameter;
if dist <= 1.0 && !p.health.dead_or_dying() {
let w = f64::from(p.dimensions.width) / 2.0;
let h = f64::from(p.dimensions.height);
let eye = [
feet[0],
feet[1] + f64::from(p.dimensions.eye_height),
feet[2],
];
let exposure = self.seen_percent(
center,
[feet[0] - w, feet[1], feet[2] - w],
[feet[0] + w, feet[1] + h, feet[2] + w],
);
let amount = damage(dist, exposure);
let dir = direction(eye);
let power = (1.0 - dist) * f64::from(exposure);
let mut hurt = false;
let creative = self.creative;
if let Some(p) = self.player.as_mut()
&& let Some(id) = self.motion.health.damage.id("minecraft:explosion")
{
// Creative players are invulnerable to explosions.
if !creative {
hurt = p
.hurt(&self.motion.health, self.world.health_rules, id, amount)
.unwrap_or(false);
}
p.velocity = Vec3::new(
p.velocity.x + dir[0] * power,
p.velocity.y + dir[1] * power,
p.velocity.z + dir[2] * power,
);
}
if hurt && !self.creative {
self.hurt_armor(amount);
}
}
}
// Mobs.
let mut mobs = std::mem::take(&mut self.mobs);
for m in mobs.iter_mut().filter(|m| m.alive()) {
let feet = [m.position.x, m.position.y, m.position.z];
let dist = distance(feet) / diameter;
if dist > 1.0 {
continue;
}
let (w, h) = (m.kind.width / 2.0, m.kind.height);
let eye = [feet[0], feet[1] + m.kind.eye_height, feet[2]];
let exposure = self.seen_percent(
center,
[feet[0] - w, feet[1], feet[2] - w],
[feet[0] + w, feet[1] + h, feet[2] + w],
);
m.hurt(damage(dist, exposure), None, &mut self.world.random);
let dir = direction(eye);
let power = (1.0 - dist) * f64::from(exposure);
m.velocity = Vec3::new(
m.velocity.x + dir[0] * power,
m.velocity.y + dir[1] * power,
m.velocity.z + dir[2] * power,
);
}
self.mobs = mobs;
// Dropped items: 5 health, destroyed by the explosion damage (nether stars resist).
let mut items = std::mem::take(&mut self.dropped);
items.retain_mut(|item| {
let feet = [item.position.x, item.position.y, item.position.z];
let dist = distance(feet) / diameter;
if dist > 1.0 {
return true;
}
let half = 0.125;
let exposure = self.seen_percent(
center,
[feet[0] - half, feet[1], feet[2] - half],
[feet[0] + half, feet[1] + 0.25, feet[2] + half],
);
if &*item.stack.item != "minecraft:nether_star" && damage(dist, exposure) >= 5.0 {
return false;
}
let dir = direction([feet[0], feet[1] + 0.2125, feet[2]]);
let power = (1.0 - dist) * f64::from(exposure);
item.velocity = Vec3::new(
item.velocity.x + dir[0] * power,
item.velocity.y + dir[1] * power,
item.velocity.z + dir[2] * power,
);
true
});
self.dropped = items;
// Primed TNT: knockback only, from its position (not its eyes).
let mut tnts = std::mem::take(&mut self.tnts);
for t in &mut tnts {
let feet = [t.position.x, t.position.y, t.position.z];
let dist = distance(feet) / diameter;
if dist > 1.0 {
continue;
}
let half = 0.49;
let exposure = self.seen_percent(
center,
[feet[0] - half, feet[1], feet[2] - half],
[feet[0] + half, feet[1] + 0.98, feet[2] + half],
);
let dir = direction(feet);
let power = (1.0 - dist) * f64::from(exposure);
t.velocity = Vec3::new(
t.velocity.x + dir[0] * power,
t.velocity.y + dir[1] * power,
t.velocity.z + dir[2] * power,
);
}
self.tnts = tnts;
}
/// `Level.explode` on the server: positions, entities, blocks, fire; then
/// the client's explosion sound.
pub(super) fn server_explode(
&mut self,
center: [f64; 3],
radius: f32,
interaction: BlockInteraction,
fire: bool,
) -> Result<()> {
let mut targets = self.exploded_positions(center, radius);
self.explosion_hurt_entities(center, radius);
if interaction != BlockInteraction::Keep {
// Util.shuffle(list, level.random)
for i in (2..=targets.len()).rev() {
let swap = self.world.random.next_int_bound(i as i32).unwrap_or(0) as usize;
targets.swap(i - 1, swap);
}
let mut stacks: Vec<([i32; 3], ItemStack)> = Vec::new();
for &pos in &targets {
self.explosion_hit_block(pos, radius, interaction, &mut stacks)?;
}
for (pos, stack) in stacks {
self.pop_resource(pos, stack);
}
}
if fire {
for &pos in &targets {
if self.world.random.next_int_bound(3).unwrap_or(1) == 0
&& self
.res
.facts
.is_air(self.world.block(pos[0], pos[1], pos[2]))
&& self
.res
.facts
.get(self.world.block(pos[0], pos[1] - 1, pos[2]))
.solid_render
&& let Some(fire) = self.res.assets.registry.default_state("minecraft:fire")
{
self.level_set(pos, fire)?;
}
}
}
let pitch = (1.0 + (client_float() - client_float()) * 0.2) * 0.7;
self.audio
.play("minecraft:entity.generic.explode", Some(center), 4.0, pitch);
Ok(())
}
/// `BlockBehaviour.onExplosionHit` (TNT: `wasExploded` primes a short fuse).
fn explosion_hit_block(
&mut self,
pos: [i32; 3],
radius: f32,
interaction: BlockInteraction,
stacks: &mut Vec<([i32; 3], ItemStack)>,
) -> Result<()> {
let state = self.world.block(pos[0], pos[1], pos[2]);
if self.res.facts.is_air(state) {
return Ok(());
}
let name = self.res.facts.get(state).name.clone();
let is_tnt = &*name == "minecraft:tnt";
if !is_tnt {
let drops = self.res.items.block_drops(
&self.res.assets.registry,
state,
None,
&mut self.world.random,
);
for stack in drops {
if &*stack.item == "minecraft:air" || stack.count == 0 {
continue;
}
// survives_explosion / explosion_decay: 1 / radius per stack.
if interaction == BlockInteraction::DestroyWithDecay
&& self.world.random.next_float() > 1.0 / radius
{
continue;
}
add_or_append_stack(stacks, stack, pos);
}
}
let contents = self.world.block_entities.remove(&(pos[0], pos[1], pos[2]));
self.level_set(pos, self.world.air)?;
if let Some(entity) = contents {
for stack in entity.contents() {
self.pop_resource(pos, stack);
}
}
if is_tnt {
self.spawn_primed_tnt(BlockPos::new(pos[0], pos[1], pos[2]), true);
}
Ok(())
}
}
/// `ServerExplosion.addOrAppendStack` with `ItemEntity.merge(.., 16)`.
fn add_or_append_stack(
stacks: &mut Vec<([i32; 3], ItemStack)>,
mut stack: ItemStack,
pos: [i32; 3],
) {
for (_, existing) in stacks.iter_mut() {
if existing.item == stack.item && existing.damage == stack.damage && existing.count < 16 {
let moved = (16 - existing.count).min(stack.count);
existing.count += moved;
stack.count -= moved;
if stack.count == 0 {
return;
}
}
}
stacks.push((pos, stack));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn block_pos_hash_matches_vec3i() {
// Vec3i.hashCode: (y + z * 31) * 31 + x
assert_eq!(Key([1, 2, 3]).java_hash(), (2 + 3 * 31) * 31 + 1);
assert_eq!(Key([-5, 64, -7]).java_hash(), (64 - 7 * 31) * 31 - 5);
assert_eq!(
Key([0, 1, 0]).comparable_compare(&Key([5, 0, 9])),
Some(Ordering::Greater)
);
assert_eq!(
Key([1, 0, 2]).comparable_compare(&Key([0, 0, 3])),
Some(Ordering::Less)
);
}
#[test]
fn drops_merge_up_to_sixteen() {
let stack = |item: &str| ItemStack {
item: item.into(),
count: 1,
damage: 0,
};
let mut stacks = Vec::new();
for _ in 0..20 {
add_or_append_stack(&mut stacks, stack("minecraft:dirt"), [0, 0, 0]);
}
add_or_append_stack(&mut stacks, stack("minecraft:stone"), [1, 0, 0]);
let counts: Vec<u32> = stacks.iter().map(|(_, s)| s.count).collect();
assert_eq!(counts, vec![16, 4, 1]);
}
}
+258
View File
@@ -0,0 +1,258 @@
//! Primed TNT (`PrimedTnt`): 80-tick fuse, gravity and drag, explosion of
//! power 4, `TntRenderer` swell and white flash, and `TntBlock.useItemOn`
//! (flint and steel / fire charge).
use super::{Game, explosion::BlockInteraction};
use horizon_client::{Result, collisions::SceneCollisions, items::ItemStack, mesher::Vertex};
use horizon_core::{
geometry::{Aabb, Vec3},
position::BlockPos,
random::RandomSource,
};
use horizon_world::level::flags as level_flags;
#[derive(Clone, Debug)]
pub(super) struct PrimedTnt {
pub position: Vec3,
pub previous: Vec3,
pub velocity: Vec3,
pub fuse: i32,
pub on_ground: bool,
}
impl PrimedTnt {
const SIZE: f64 = 0.98;
fn bounds(&self) -> Aabb {
let h = Self::SIZE / 2.0;
Aabb::new(
Vec3::new(self.position.x - h, self.position.y, self.position.z - h),
Vec3::new(
self.position.x + h,
self.position.y + Self::SIZE,
self.position.z + h,
),
)
}
}
impl Game<'_> {
/// `new PrimedTnt(level, x + 0.5, y, z + 0.5, owner)`; `short` applies
/// `wasExploded`'s random short fuse. Plays `entity.tnt.primed` for primes.
pub(super) fn spawn_primed_tnt(&mut self, pos: BlockPos, short: bool) {
let r = &mut self.world.random;
let rot = r.next_double() * f64::from(std::f32::consts::TAU);
let position = Vec3::new(
f64::from(pos.x) + 0.5,
f64::from(pos.y),
f64::from(pos.z) + 0.5,
);
let mut tnt = PrimedTnt {
position,
previous: position,
velocity: Vec3::new(-rot.sin() * 0.02, f64::from(0.2f32), -rot.cos() * 0.02),
fuse: 80,
on_ground: false,
};
if short {
// PrimedTnt.getRandomShortFuse
tnt.fuse = r.next_int_bound((tnt.fuse / 4).max(1)).unwrap_or(0) + tnt.fuse / 8;
} else {
self.audio.play(
"minecraft:entity.tnt.primed",
Some([position.x, position.y, position.z]),
1.0,
1.0,
);
}
self.tnts.push(tnt);
}
/// `PrimedTnt.tick` for every primed TNT, in order; an expired fuse
/// explodes immediately (later TNT in the list feel its knockback this
/// tick). TNT primed by an explosion starts ticking next tick.
pub(super) fn tick_tnt(&mut self) -> Result<()> {
let mut count = self.tnts.len();
let mut i = 0;
while i < count {
let t = &mut self.tnts[i];
t.previous = t.position;
t.velocity.y -= 0.04;
let mut scene = SceneCollisions {
world: &self.world,
binding: self.collision,
};
let wanted = t.velocity;
let moved = scene
.resolve(t.bounds(), wanted, 0.0, t.on_ground)
.unwrap_or(Vec3::ZERO);
t.position = Vec3::new(
t.position.x + moved.x,
t.position.y + moved.y,
t.position.z + moved.z,
);
t.on_ground = wanted.y < 0.0 && moved.y != wanted.y;
if moved.x != wanted.x {
t.velocity.x = 0.0;
}
if moved.z != wanted.z {
t.velocity.z = 0.0;
}
if moved.y != wanted.y {
t.velocity.y = 0.0;
}
t.velocity = Vec3::new(
t.velocity.x * 0.98,
t.velocity.y * 0.98,
t.velocity.z * 0.98,
);
if t.on_ground {
t.velocity = Vec3::new(t.velocity.x * 0.7, t.velocity.y * -0.5, t.velocity.z * 0.7);
}
t.fuse -= 1;
if t.fuse <= 0 {
let center = [
t.position.x,
t.position.y + PrimedTnt::SIZE * 0.0625,
t.position.z,
];
self.tnts.remove(i);
count -= 1;
self.server_explode(center, 4.0, BlockInteraction::Destroy, false)?;
} else {
i += 1;
}
}
Ok(())
}
/// `TntBlock.useItemOn`: flint and steel or a fire charge primes TNT.
pub(super) fn ignite_tnt(&mut self, stack: &ItemStack) -> Result<bool> {
let item = &*stack.item;
if item != "minecraft:flint_and_steel" && item != "minecraft:fire_charge" {
return Ok(false);
}
let Some(hit) = self.pick() else {
return Ok(false);
};
let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]);
if &*self.res.facts.get(state).name != "minecraft:tnt" {
return Ok(false);
}
let pos = BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]);
self.spawn_primed_tnt(pos, false);
let air = self.world.air;
self.with_level(|b, level, ticks| {
b.set_block(level, ticks, pos, air, level_flags::UPDATE_ALL_IMMEDIATE)
});
self.process_level_events()?;
self.swing_arm();
if item == "minecraft:flint_and_steel" {
self.damage_held(1);
} else {
self.consume_held();
}
Ok(true)
}
/// `TntRenderer`: the block centred on the entity, swelling over the last
/// 10 ticks and flashing white every 5 ticks.
pub(super) fn tnt_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
if self.tnts.is_empty() {
return;
}
let Some(state) = self.res.assets.registry.default_state("minecraft:tnt") else {
return;
};
// Face sprites from the block model: up, down, north, south, west, east.
let Ok(models) = self
.res
.assets
.model_catalog
.collect(state, BlockPos::new(0, 0, 0))
else {
return;
};
let mut sprites = [None; 6];
for face in models.iter().flat_map(|(_, m)| m.faces.iter()) {
use horizon_assets::model::Direction as D;
let index = match face.quad.facing {
D::Up => 0,
D::Down => 1,
D::North => 2,
D::South => 3,
D::West => 4,
D::East => 5,
};
if sprites[index].is_none() {
sprites[index] = self
.res
.layer_names
.get(&face.layer)
.and_then(|name| self.res.atlas.sprites.get(name).copied());
}
}
for t in &self.tnts {
let fuse = t.fuse as f32 - alpha as f32 + 1.0;
let scale = if fuse < 10.0 {
let g = (1.0 - fuse / 10.0).clamp(0.0, 1.0);
1.0 + g * g * g * g * 0.3
} else {
1.0
};
let lit = fuse >= 0.0 && (fuse / 5.0) as i32 % 2 == 0;
let base = glam::DVec3::new(
t.previous.x + (t.position.x - t.previous.x) * alpha,
t.previous.y + (t.position.y - t.previous.y) * alpha + 0.5,
t.previous.z + (t.position.z - t.previous.z) * alpha,
) - camera;
let o = base.as_vec3();
let light = self.world.light(
t.position.x.floor() as i32,
(t.position.y + 0.5).floor() as i32,
t.position.z.floor() as i32,
);
let packed = u32::from(light >> 4) * 16 | (u32::from(light & 15) * 16) << 8;
let v = |x: f32, y: f32, z: f32| o + glam::Vec3::new(x - 0.5, y - 0.5, z - 0.5) * scale;
let faces = [
(
[v(0., 1., 1.), v(1., 1., 1.), v(1., 1., 0.), v(0., 1., 0.)],
1.0,
),
(
[v(0., 0., 0.), v(1., 0., 0.), v(1., 0., 1.), v(0., 0., 1.)],
0.5,
),
(
[v(1., 0., 0.), v(0., 0., 0.), v(0., 1., 0.), v(1., 1., 0.)],
0.8,
),
(
[v(0., 0., 1.), v(1., 0., 1.), v(1., 1., 1.), v(0., 1., 1.)],
0.8,
),
(
[v(0., 0., 0.), v(0., 0., 1.), v(0., 1., 1.), v(0., 1., 0.)],
0.6,
),
(
[v(1., 0., 1.), v(1., 0., 0.), v(1., 1., 0.), v(1., 1., 1.)],
0.6,
),
];
for ((corners, shade), sprite) in faces.into_iter().zip(sprites) {
let Some(r) = sprite else { continue };
let c = (255.0 * shade) as u32;
let color = 0xFF00_0000 | c << 16 | c << 8 | c;
for (p, uv) in
corners
.iter()
.zip([[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]])
{
// Overlay 4: OverlayTexture white flash.
out.push(Vertex {
pos: p.to_array(),
uv,
layer: if lit { 4 } else { 0 },
color,
light: packed,
});
}
}
}
}
}
+5 -1
View File
@@ -1,7 +1,7 @@
//! `neighborChanged`, `onPlace`, `affectNeighborsAfterRemoval` and
//! `updateIndirectNeighbourShapes` for the overriding vanilla classes.
use super::{
LevelAccess, Sim,
LevelAccess, LevelEvent, Sim,
classes::Class,
states::BlockId,
update::{below, rel},
@@ -389,6 +389,10 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
self.level_event(2001, head_pos, head.0 as i32);
}
}
// TntBlock.playerWillDestroy: unstable TNT primes unless instabuild.
if !creative && data.is(Class::Tnt) && b.table.bool(state, p.unstable) {
self.emit(LevelEvent::PrimeTnt { pos });
}
self.level_event(2001, pos, state.0 as i32);
self.game_event(pos, "minecraft:block_destroy");
self.remove_block(pos, false)