Merge pull request #1427 from ludovic111/fix/st-particles

🤖 Agent: merged after verify and CI parity passed, built merged with current main (st1: /particle and explosion particles from a server reach its players; lan_e2e evidence in the PR body).
This commit is contained in:
Ludovic Marie
2026-10-23 21:06:12 +02:00
committed by GitHub
21 changed files with 746 additions and 45 deletions
@@ -121,6 +121,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
tick_frozen: false,
tick_steps: (0, 0),
collision: None,
border: &horizon_client::worldborder::WorldBorder::default(),
};
for event in hub.tick(&mut ctx) {
match event {
@@ -78,6 +78,7 @@ fn main() -> Result<()> {
let mut selected = collisions::EntityCollisions {
blocks: scene,
entities: &entities,
border: None,
};
let movement = world_movement::resolve_world_movement(
&mut selected,
+13 -2
View File
@@ -3,7 +3,7 @@
//! Entity-dependent rules use the defaults for players and the supported mobs.
use crate::{Result, world::World};
use horizon_core::{
geometry::{Aabb, Vec3, VoxelShape},
geometry::{Aabb, Vec3, VoxelShape, border::BorderGeometry},
position::{BlockPos, ChunkPos},
};
use horizon_world::{
@@ -64,6 +64,9 @@ pub struct SceneCollisions<'w, 'r> {
pub struct EntityCollisions<'a, W> {
pub blocks: W,
pub entities: &'a [Aabb],
/// The world border and the moving entity's x and z
/// (`CollisionGetter.borderCollision`); None: the blocks' answer.
pub border: Option<(&'a BorderGeometry, [f64; 2])>,
}
impl<W: BlockCollisionWorld> BlockCollisionWorld for EntityCollisions<'_, W> {
type Error = W::Error;
@@ -114,12 +117,20 @@ impl<W: EntityMovementWorld<Error = io::Error>> EntityMovementWorld for EntityCo
}
Ok(shapes)
}
/// `WorldBorder.isInsideCloseToBorder`: an entity inside the border and
/// near it collides with its walls.
fn movement_border(
&mut self,
entity: EntityIdentity,
bounds: Aabb,
) -> io::Result<Option<VoxelShape>> {
self.blocks.movement_border(entity, bounds)
let Some((border, [x, z])) = self.border else {
return self.blocks.movement_border(entity, bounds);
};
if !border.is_inside_close_to_border(x, z, bounds) {
return Ok(None);
}
border.collision_shape().map(Some).map_err(io::Error::other)
}
}
impl SceneCollisions<'_, '_> {
+1
View File
@@ -73,6 +73,7 @@ mod lan_crafting;
mod lan_entities;
mod lan_mobs;
mod lan_mount_menu;
mod lan_particles;
mod lan_pvp;
mod lan_screen;
mod lan_stations;
@@ -248,8 +248,32 @@ impl Game<'_> {
/// Every tick: the size change, the wall the player cannot pass and
/// damage outside the border.
/// `BorderChangeListener.DelegateBorderChangeListener`'s packets: what
/// changed on the border since the guests were last told of it.
pub(in crate::game) fn lan_sync_border(&mut self, host: &mut crate::game::lan::LanHost) {
let now = horizon_client::lan::border::Sent::of(&self.border);
if let Some(sent) = host.border_sent.replace(now) {
for packet in sent.changes(&self.border) {
host.hub.broadcast(&packet);
}
}
}
pub(in crate::game) fn tick_worldborder(&mut self) {
self.border.tick();
self.player_border();
self.border_damage();
}
/// The player's movement collides with the border as it is now
/// (`CollisionGetter.borderCollision`): from inside, its walls stop it.
pub(in crate::game) fn player_border(&mut self) {
if let Some(p) = self.player.as_mut() {
p.border = Some(self.border.geometry().clone());
}
}
/// `LivingEntity.baseTick`: a player outside the border, further than
/// its safe zone, is hurt by the blocks beyond it. The game's player, or
/// a guest's in their turn (`as_guest`).
pub(in crate::game) fn border_damage(&mut self) {
let Some((px, pz, half)) = self.player.as_ref().map(|p| {
(
p.position.x,
@@ -269,20 +293,6 @@ impl Game<'_> {
let amount = (-dist * self.border.damage_per_block).floor().max(1.0) as f32;
self.hurt_player_by("minecraft:outside_border", amount);
}
// From inside the border the wall stops movement.
if self.border.distance(px, pz) >= 0.0 {
let [x, z] = self.border.clamp(px, pz, half);
if let Some(p) = self.player.as_mut() {
if x != px {
p.velocity.x = 0.0;
}
if z != pz {
p.velocity.z = 0.0;
}
p.position.x = x;
p.position.z = z;
}
}
}
pub(super) fn cmd_worldborder(&mut self, id: &str, ctx: &Context) -> R<i32> {
let float2 = |v: f64| format!("{v:.2}");
@@ -8,6 +8,7 @@ use horizon_client::{
text::Text,
};
use horizon_core::random::RandomSource;
use horizon_protocol::packets::play::{self, Clientbound as C};
use horizon_world::attribute_map::ValueKind;
use horizon_world::nbt::Tag;
@@ -409,6 +410,8 @@ impl Game<'_> {
],
_ => [1.0, 0.0, 0.0],
};
// The block state of a block particle, for its packet.
let mut block_state = None;
let options = match ty {
ParticleType::Dust => ParticleOptions::dust(
rgb,
@@ -470,6 +473,7 @@ impl Game<'_> {
match block {
Ok(Arg::Block(b)) => {
let state = self.block_state(&b)?;
block_state = Some(state);
let at = self
.position_arg(ctx, "pos")
.unwrap_or_else(|| self.source_position())
@@ -487,10 +491,9 @@ impl Game<'_> {
let pos = self
.position_arg(ctx, "pos")
.unwrap_or_else(|| self.source_position());
let delta = self.position_arg(ctx, "delta").map_or([0.0; 3], |d| {
let s = self.source_position();
[d[0] - s[0], d[1] - s[1], d[2] - s[2]]
});
// Vec3Argument.getVec3: the spread as given (relative parts from the
// source), not a position to measure from the source.
let delta = self.position_arg(ctx, "delta").unwrap_or([0.0; 3]);
let speed = match ctx.get("speed") {
Some(Arg::Float(v)) => *v,
_ => 0.0,
@@ -501,27 +504,74 @@ impl Game<'_> {
};
// ParticleCommand.sendParticles: the viewers it reached, each within
// 32 blocks (512 with `force`) of the particle's block centre.
// Without viewers, every player (PlayerList.getPlayers).
let viewers = if ctx.get("viewers").is_some() {
self.entities(ctx, "viewers", true)?
} else {
vec![Target::Player]
let acting = self.lan_acting;
let guests = self.lan.iter().flat_map(|h| h.hub.guests.iter());
self.player
.as_ref()
.map(|_| Target::Player)
.into_iter()
.chain(
guests
.filter(|g| g.placed && Some(g.conn) != acting)
.map(|g| Target::Guest(g.conn)),
)
.collect()
};
let limit = if ctx.has("force") { 512.0 } else { 32.0 };
let reached = viewers
.iter()
.filter(|&&t| {
let force = ctx.has("force");
let limit = if force { 512.0 } else { 32.0 };
let reached: Vec<Target> = viewers
.into_iter()
.filter(|&t| {
self.target_position(t).is_some_and(|p| {
let c = p.map(|v| v.floor() + 0.5);
(c[0] - pos[0]).powi(2) + (c[1] - pos[1]).powi(2) + (c[2] - pos[2]).powi(2)
< limit * limit
})
})
.count() as i32;
if reached == 0 {
.collect();
if reached.is_empty() {
return Err(err("commands.particle.failed", &[]));
}
// `ServerLevel.sendParticles`: no count means one particle with the delta as velocity.
if count <= 0 {
// ServerLevel.sendParticles: each viewer a server serves is sent the
// particles (the player in place too when it is a guest); the
// window's own player draws them.
let packet = self
.network_particle(&options, block_state)
.map(|particle| {
C::LevelParticles(play::LevelParticles {
particle,
override_limiter: force,
always_show: false,
pos,
dist: delta.map(|d| d as f32),
max_speed: [speed; 3],
count: count.max(0),
randomization: 0,
})
});
let mut local = false;
for &t in &reached {
match (t, &packet) {
(Target::Player, Some(p)) if self.lan_acting.is_some() => {
self.guest_packets.push(p.clone());
}
(Target::Player, _) => local = true,
(Target::Guest(conn), Some(p)) => {
if let Some(host) = self.lan.as_ref() {
host.hub.send_to(conn, p);
}
}
_ => {}
}
}
let reached = reached.len() as i32;
if !local {
} else if count <= 0 {
// No count: one particle with the delta as velocity.
self.particles.create(&options, pos, delta);
} else {
for _ in 0..count {
@@ -979,6 +979,8 @@ impl Game<'_> {
status["projectiles"] = json!(self.projectiles_status());
// The particles made so far, by type.
status["particles"] = json!(self.particles.made());
// The world border this side knows of.
status["border"] = json!({ "center": self.border.center(), "size": self.border.size() });
// The scoreboard sidebar the HUD shows.
status["sidebar"] = self.sidebar_status();
status
@@ -580,6 +580,7 @@ impl Game<'_> {
self.particles.explosion(center, radius, block_count, &|b| {
facts.is_air(world.block(b[0], b[1], b[2]))
});
self.lan_explode(center, radius, block_count);
Ok(())
}
/// `BlockBehaviour.onExplosionHit` (TNT: `wasExploded` primes a short fuse).
+6
View File
@@ -66,6 +66,8 @@ pub(super) struct LanHost {
/// whose respawn replaces their waypoint.
pub waypoints: std::collections::HashMap<String, lan::waypoints::Waypoints>,
pub waypoint_dead: std::collections::HashSet<u128>,
/// The world border as the guests were last told of it (lan/border.rs).
pub border_sent: Option<lan::border::Sent>,
/// Guests' commands waiting for the hub to be back in `self.lan`, where
/// a command can reach every player (game/lan_actions.rs).
pub commands: Vec<super::lan_actions::GuestCommand>,
@@ -561,6 +563,7 @@ impl Game<'_> {
owner: None,
waypoints: Default::default(),
waypoint_dead: Default::default(),
border_sent: None,
commands: Vec::new(),
states: Default::default(),
});
@@ -891,6 +894,7 @@ impl Game<'_> {
tick_frozen: self.clock.frozen(),
tick_steps: self.clock.step_state(),
collision: Some(self.collision),
border: &self.border,
};
host.hub.movement_checks = (
self.ui.rules.bool("player_movement_check"),
@@ -998,6 +1002,7 @@ impl Game<'_> {
self.lan_update_models(&mut host);
self.lan_update_waypoints(&mut host, state.as_ref());
self.lan_sync_scoreboard(&mut host);
self.lan_sync_border(&mut host);
drop(holding);
lan::flush_all(host.hub.guests.iter().map(|g| &g.sender));
self.lan = Some(host);
@@ -1074,6 +1079,7 @@ impl Game<'_> {
tick_frozen: self.clock.frozen(),
tick_steps: self.clock.step_state(),
collision: Some(self.collision),
border: &self.border,
};
host.hub.place_new_player(conn, &mut ctx);
if elsewhere && let Err(e) = self.enter_level(Some(host), back) {
@@ -1581,6 +1581,7 @@ impl Game<'_> {
tick_frozen: self.clock.frozen(),
tick_steps: self.clock.step_state(),
collision: Some(self.collision),
border: &self.border,
};
host.hub.respawn(i, spawn, &ctx);
if let Some(config) = elsewhere {
@@ -1918,7 +1919,8 @@ impl Game<'_> {
for d in travelled {
game.movement_stats(Vec3::new(d[0], d[1], d[2]));
}
// LivingEntity.baseTick ends with tickEffects.
// LivingEntity.baseTick: outside the world border, then tickEffects.
game.border_damage();
game.tick_mob_effects();
let Some(player) = game.player.as_mut() else {
return Vec::new();
@@ -0,0 +1,228 @@
//! Particles a server sends its players and its clients draw:
//! `ClientboundLevelParticlesPacket` (`ServerLevel.sendParticles`, which
//! `/particle` uses) and `ClientboundExplodePacket` (`ServerLevel.explode`).
use super::Game;
use horizon_client::particles::{ParticleOptions, ParticleType};
use horizon_core::random::RandomSource;
use horizon_protocol::{
entity_data::{Particle, ParticleData},
packets::play::{self, Clientbound as C},
};
use horizon_world::registry::BlockStateId;
/// An ARGB colour as the options' RGBA.
fn rgba(argb: i32) -> [f32; 4] {
let c = |shift: i32| ((argb >> shift) & 255) as f32 / 255.0;
[c(16), c(8), c(0), c(24)]
}
/// The options' RGB as an RGB colour (`ARGB.colorFromFloat` without alpha).
fn rgb_int(c: [f32; 3]) -> i32 {
let b = |v: f32| ((v.clamp(0.0, 1.0) * 255.0).round() as i32) & 255;
(b(c[0]) << 16) | (b(c[1]) << 8) | b(c[2])
}
fn rgb(c: [f32; 4]) -> [f32; 3] {
[c[0], c[1], c[2]]
}
impl Game<'_> {
/// `ParticleTypes.STREAM_CODEC`'s value for `options`: the type's
/// network id and the data it carries (`state` for the block particles).
/// None while not serving, or for a particle whose data isn't sent from
/// here (items, vibrations, trails).
pub(super) fn network_particle(
&self,
options: &ParticleOptions,
state: Option<BlockStateId>,
) -> Option<Particle> {
let name = format!("minecraft:{}", options.ty.name());
let id = self
.lan
.as_ref()?
.hub
.registry_id("minecraft:particle_type", &name)?;
use ParticleType as T;
let c = options.color;
let data = match options.ty {
T::Block | T::BlockMarker | T::FallingDust | T::DustPillar | T::BlockCrumble => {
Some(ParticleData::State(state?.0 as i32))
}
T::Dust => Some(ParticleData::ColorScale(rgb_int(rgb(c)), options.scale)),
T::DustColorTransition => Some(ParticleData::ColorScale2(
rgb_int(rgb(c)),
rgb_int(options.to_color),
options.scale,
)),
T::Effect | T::InstantEffect => {
Some(ParticleData::ColorPower(rgb_int(rgb(c)), options.scale))
}
T::EntityEffect | T::TintedLeaves => Some(ParticleData::Color(
(((c[3].clamp(0.0, 1.0) * 255.0).round() as i32) << 24) | rgb_int(rgb(c)),
)),
T::DragonBreath | T::SculkCharge => Some(ParticleData::Scalar(options.scale)),
T::Shriek => Some(ParticleData::Delay(options.scale as i32)),
T::Item | T::Trail | T::Vibration => return None,
_ => None,
};
Some(Particle { id, data })
}
/// The options a server's particle stands for (None for a type or data
/// this client doesn't draw).
fn received_particle(&mut self, p: &Particle, at: [f64; 3]) -> Option<ParticleOptions> {
let name = self
.remote
.as_ref()?
.builtin
.get("minecraft:particle_type")?
.name(p.id)?
.to_owned();
let ty = ParticleType::from_name(&name)?;
Some(match &p.data {
None => ParticleOptions::simple(ty),
Some(ParticleData::State(s)) => {
let pos = at.map(|v| v.floor() as i32);
let (sprite, tint) = self
.particle_sprite(BlockStateId(*s as u32), pos)
.unwrap_or_else(|| ("block/stone".into(), 0xFFFFFF));
ParticleOptions::block(ty, sprite, tint)
}
Some(ParticleData::ColorScale(c, scale)) => {
ParticleOptions::dust(rgb(rgba(*c)), *scale)
}
Some(ParticleData::ColorScale2(from, to, scale)) => {
ParticleOptions::dust_transition(rgb(rgba(*from)), rgb(rgba(*to)), *scale)
}
Some(ParticleData::ColorPower(c, power)) => ParticleOptions {
scale: *power,
..ParticleOptions::colored(ty, [rgba(*c)[0], rgba(*c)[1], rgba(*c)[2], 1.0])
},
Some(ParticleData::Color(c)) => ParticleOptions::colored(ty, rgba(*c)),
Some(ParticleData::Scalar(v)) if ty == ParticleType::SculkCharge => {
ParticleOptions::sculk_charge(*v)
}
Some(ParticleData::Scalar(v)) => ParticleOptions {
scale: *v,
..ParticleOptions::simple(ty)
},
Some(ParticleData::Delay(d)) => ParticleOptions::shriek(*d),
Some(ParticleData::Trail(target, color, duration)) => {
ParticleOptions::trail(*target, *color as u32 & 0xFF_FFFF, *duration)
}
Some(_) => return None,
})
}
/// `ClientPacketListener.handleParticleEvent`: no count is one particle
/// moving by speed times spread; otherwise each is spread and sped up by
/// gaussians on each axis.
pub(super) fn remote_level_particles(&mut self, p: &play::LevelParticles) {
let Some(options) = self.received_particle(&p.particle, p.pos) else {
return;
};
let (d, s) = (p.dist.map(f64::from), p.max_speed.map(f64::from));
// ClientLevel.addParticle: the camera's 32 blocks unless the packet
// (`force`) or the type overrides the limiter.
let add = |particles: &mut horizon_client::particles::ParticleEngine, at, v| {
if p.override_limiter {
particles.create(&options, at, v);
} else {
particles.add(&options, at, v);
}
};
if p.count == 0 {
add(
&mut self.particles,
p.pos,
[s[0] * d[0], s[1] * d[1], s[2] * d[2]],
);
return;
}
for _ in 0..p.count {
let r = self.particles.random();
let at = [
p.pos[0] + r.next_gaussian() * d[0],
p.pos[1] + r.next_gaussian() * d[1],
p.pos[2] + r.next_gaussian() * d[2],
];
let v = [
r.next_gaussian() * s[0],
r.next_gaussian() * s[1],
r.next_gaussian() * s[2],
];
add(&mut self.particles, at, v);
}
}
/// `ClientPacketListener.handleExplosion`: the blast's particles (and its
/// sound, when the packet carries it).
pub(super) fn remote_explode(&mut self, p: &play::Explode) {
if p.play_sound {
let pitch = (1.0
+ (self.particles.random().next_float() - self.particles.random().next_float())
* 0.2)
* 0.7;
self.audio.play(
"minecraft:entity.generic.explode",
Some(p.center),
4.0,
pitch,
);
}
let (world, facts) = (&self.world, self.res.facts());
self.particles
.explosion(p.center, p.radius, p.block_count.max(0) as usize, &|b| {
facts.is_air(world.block(b[0], b[1], b[2]))
});
}
/// `ServerLevel.explode`'s packet to each player within 64 blocks. The
/// sound and the push reach them on their own (the level's sounds, the
/// players' motion), so the packet carries neither.
pub(super) fn lan_explode(&self, center: [f64; 3], radius: f32, block_count: usize) {
let Some(host) = self.lan.as_ref() else {
return;
};
let particle = |name: &str| {
Some(Particle {
id: host.hub.registry_id("minecraft:particle_type", name)?,
data: None,
})
};
let emitter = if radius < 2.0 {
"minecraft:explosion"
} else {
"minecraft:explosion_emitter"
};
let (Some(at_center), Some(poof), Some(smoke)) = (
particle(emitter),
particle("minecraft:poof"),
particle("minecraft:smoke"),
) else {
return;
};
// Level.DEFAULT_EXPLOSION_BLOCK_PARTICLES.
let info = |particle, scaling| play::ExplosionParticle {
particle,
scaling,
speed: 1.0,
weight: 1,
};
let packet = C::Explode(play::Explode {
center,
radius,
block_count: block_count as i32,
knockback: None,
particle: at_center,
sound: match host
.hub
.registry_id("minecraft:sound_event", "minecraft:entity.generic.explode")
{
Some(id) => (id, None),
None => (-1, Some(("minecraft:entity.generic.explode".into(), None))),
},
block_particles: vec![info(poof, 0.5), info(smoke, 1.0)],
play_sound: false,
});
host.hub.broadcast_near(center, 64.0, &packet, None);
}
}
+4 -1
View File
@@ -101,7 +101,7 @@ fn place_interpolated(m: &mut Mob, at: PosRot) {
pub(super) struct Remote {
pub session: Session,
pub brand: String,
builtin: Arc<Builtin>,
pub(super) builtin: Arc<Builtin>,
lang: Arc<Language>,
pub(super) registries: Arc<Dynamic>,
joined: bool,
@@ -1733,6 +1733,8 @@ impl Game<'_> {
// level plays them (particles and sounds: a spawner's burst, bone
// meal, waxing, a block broken by someone else).
C::LevelEvent(p) => self.level_event_at(p.kind, p.pos, p.data),
C::LevelParticles(p) => self.remote_level_particles(&p),
C::Explode(p) => self.remote_explode(&p),
C::Sound(p) => {
let name = match &p.sound.1 {
Some((location, _)) => Some(location.clone()),
@@ -3043,6 +3045,7 @@ impl Game<'_> {
self.remote_handle_input();
// ClientLevel.tick: the border's size change.
self.border.tick();
self.player_border();
self.tick_remote_entities(running);
// ClientLevel.tickBlockEntities: chest lids, shulker boxes, bells.
self.tick_block_entity_anims();
@@ -455,6 +455,7 @@ impl Game<'_> {
tick_frozen: self.clock.frozen(),
tick_steps: self.clock.step_state(),
collision: Some(self.collision),
border: &self.border,
}
}
}
+130
View File
@@ -0,0 +1,130 @@
//! The world border a server's players see: all of it when they enter a
//! level (`PlayerList.sendLevelInfo`), then each change as
//! `BorderChangeListener` broadcasts it: a new centre, a new size, a size
//! change in progress, a new warning time or distance.
use crate::worldborder::WorldBorder;
use horizon_protocol::packets::play::{self, Clientbound as C};
/// `ClientboundInitializeBorderPacket`.
pub fn initialize(b: &WorldBorder) -> play::InitializeBorder {
let [center_x, center_z] = b.center();
play::InitializeBorder {
center_x,
center_z,
old_size: b.size(),
new_size: b.target_size(),
lerp_time: b.remaining_ticks(),
absolute_max_size: b.absolute_max_size(),
warning_blocks: b.warning_distance,
warning_time: b.warning_time,
}
}
/// The border as the players were last told of it.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Sent {
center: [f64; 2],
size: f64,
target: f64,
remaining: i64,
warning_distance: i32,
warning_time: i32,
}
impl Sent {
pub fn of(b: &WorldBorder) -> Self {
Self {
center: b.center(),
size: b.size(),
target: b.target_size(),
remaining: b.remaining_ticks(),
warning_distance: b.warning_distance,
warning_time: b.warning_time,
}
}
/// The packets that tell the players what changed since `self`, other
/// than a size change going on (which each client runs itself).
pub fn changes(&self, b: &WorldBorder) -> Vec<C> {
let now = Self::of(b);
let mut out = Vec::new();
if now.center != self.center {
out.push(C::SetBorderCenter(play::SetBorderCenter {
x: now.center[0],
z: now.center[1],
}));
}
// A change going on counts down a tick at a time (or not at all
// while the game is frozen), towards the same size.
let going_on = self.remaining > 0
&& now.target == self.target
&& (now.remaining == self.remaining || now.remaining == self.remaining - 1);
if now.remaining > 0 {
if !going_on {
out.push(C::SetBorderLerpSize(play::SetBorderLerpSize {
old_size: now.size,
new_size: now.target,
lerp_time: now.remaining,
}));
}
} else if now.size != self.size && !(self.remaining > 0 && now.size == self.target) {
out.push(C::SetBorderSize(play::SetBorderSize { size: now.size }));
}
if now.warning_time != self.warning_time {
out.push(C::SetBorderWarningDelay(play::SetBorderWarningDelay {
delay: now.warning_time,
}));
}
if now.warning_distance != self.warning_distance {
out.push(C::SetBorderWarningDistance(
play::SetBorderWarningDistance {
blocks: now.warning_distance,
},
));
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn kinds(packets: &[C]) -> Vec<&'static str> {
packets
.iter()
.map(|p| match p {
C::SetBorderCenter(_) => "center",
C::SetBorderSize(_) => "size",
C::SetBorderLerpSize(_) => "lerp",
C::SetBorderWarningDelay(_) => "delay",
C::SetBorderWarningDistance(_) => "distance",
_ => "other",
})
.collect()
}
#[test]
fn each_change_is_sent_once() {
let mut b = WorldBorder::default();
let mut sent = Sent::of(&b);
assert!(sent.changes(&b).is_empty());
b.set_center([4.0, -2.0]);
b.set_size(10.0);
b.warning_time = 30;
assert_eq!(kinds(&sent.changes(&b)), ["center", "size", "delay"]);
sent = Sent::of(&b);
// A change over 3 ticks: sent once, then each client runs it.
b.lerp_to(20.0, 3);
assert_eq!(kinds(&sent.changes(&b)), ["lerp"]);
for _ in 0..4 {
sent = Sent::of(&b);
b.tick();
assert!(sent.changes(&b).is_empty(), "{:?}", sent.changes(&b));
}
assert_eq!(b.size(), 20.0);
b.warning_distance = 1;
assert_eq!(kinds(&Sent::of(&b).changes(&b)), [] as [&str; 0]);
assert_eq!(kinds(&sent.changes(&b)), ["distance"]);
}
}
+3 -11
View File
@@ -111,6 +111,8 @@ pub struct TickCtx<'a> {
/// Block collisions, for ServerGamePacketListenerImpl's moved-wrongly
/// check (none: moves are not checked against blocks).
pub collision: Option<&'a BlockCollisionRegistry<'a>>,
/// The level's world border (PlayerList.sendLevelInfo sends it).
pub border: &'a crate::worldborder::WorldBorder,
}
/// What the gameplay code has to do for a guest.
@@ -891,17 +893,7 @@ impl Hub {
fn send_level_info(&mut self, i: usize, ctx: &TickCtx) {
let spawn = ctx.spawn;
let g = &self.guests[i];
g.send(&C::InitializeBorder(play::InitializeBorder {
center_x: 0.0,
center_z: 0.0,
old_size: 59_999_968.0,
new_size: 59_999_968.0,
lerp_time: 0,
absolute_max_size: 29_999_984,
warning_blocks: 5,
// WorldBorder.DEFAULT_WARNING_TIME, in ticks.
warning_time: 300,
}));
g.send(&C::InitializeBorder(super::border::initialize(ctx.border)));
g.send(&self.time_packet(ctx.world, ctx.clock_rate));
g.send(&self.default_spawn(spawn));
let w = &ctx.world.weather;
+1
View File
@@ -6,6 +6,7 @@
//! world that is not open to the network pays nothing.
mod advancements;
pub mod attributes;
pub mod border;
pub mod chunks;
mod command_order;
pub mod command_suggestions;
+6
View File
@@ -307,6 +307,9 @@ pub struct PlayerMotion {
pub hurt_log: Vec<crate::health::HurtRecord>,
/// The last melee attacks made on mobs, newest last.
pub attack_log: Vec<crate::health::AttackRecord>,
/// The level's world border, whose walls stop the player's movement
/// from inside (the game keeps it current; None: no border).
pub border: Option<horizon_core::geometry::border::BorderGeometry>,
}
fn attribute_error(error: impl std::fmt::Debug) -> io::Error {
io::Error::other(format!("movement attribute: {error:?}"))
@@ -461,6 +464,7 @@ impl PlayerMotion {
powder_snow_entered: Vec::new(),
hurt_log: Vec::new(),
attack_log: Vec::new(),
border: None,
})
}
/// `Entity.getTicksRequiredToFreeze`.
@@ -678,9 +682,11 @@ impl MotionWorld<'_, '_, '_> {
fn movement_collisions(
&self,
) -> crate::collisions::EntityCollisions<'_, SceneCollisions<'_, '_>> {
let at = [self.player.position.x, self.player.position.z];
crate::collisions::EntityCollisions {
blocks: self.collisions(),
entities: self.entities,
border: self.player.border.as_ref().map(|b| (b, at)),
}
}
/// `Level.noCollision(player, bounds)`: blocks and the host's entity boxes.
+4
View File
@@ -80,6 +80,10 @@ impl PartialEq for WorldBorder {
}
}
impl WorldBorder {
/// Its extent, for collisions.
pub fn geometry(&self) -> &BorderGeometry {
&self.geometry
}
pub fn center(&self) -> [f64; 2] {
self.geometry.center()
}
+1
View File
@@ -200,6 +200,7 @@ impl Server {
tick_frozen: false,
tick_steps: (0, 0),
collision: None,
border: &horizon_client::worldborder::WorldBorder::default(),
};
let events = self.hub.tick(&mut ctx);
for event in events {
+141 -1
View File
@@ -7,7 +7,7 @@ use crate::{
Vec3d, Writer,
},
chunk::{ChunkData, LightData},
entity_data::{EntityData, Value},
entity_data::{EntityData, Particle, Value},
item::{Hashed, HashedSlot, Slot, Stack},
packet, packet_enum,
packets::{
@@ -883,6 +883,116 @@ impl Codec<SetObjective> for SetObjective {
}
}
}
/// ClientboundLevelParticlesPacket: a particle, whether it ignores the
/// client's particle setting (`overrideLimiter`) and its distance limit
/// (`alwaysShow`), where, the spread and the speed on each axis, how many
/// (0: one, moving by speed times spread) and the randomization type
/// (0 default: gaussian spread and speed).
#[derive(Clone, Debug, PartialEq)]
pub struct LevelParticles {
pub particle: Particle,
pub override_limiter: bool,
pub always_show: bool,
pub pos: [f64; 3],
pub dist: [f32; 3],
pub max_speed: [f32; 3],
pub count: i32,
pub randomization: i32,
}
impl Codec<LevelParticles> for LevelParticles {
fn read(r: &mut Reader) -> Result<Self> {
Ok(Self {
particle: Particle::read(r)?,
override_limiter: r.bool()?,
always_show: r.bool()?,
pos: Vec3d::read(r)?,
dist: [r.f32()?, r.f32()?, r.f32()?],
max_speed: [r.f32()?, r.f32()?, r.f32()?],
count: r.varint()?,
randomization: r.varint()?,
})
}
fn write(v: &Self, w: &mut Writer) {
v.particle.write(w);
w.bool(v.override_limiter);
w.bool(v.always_show);
Vec3d::write(&v.pos, w);
for f in v.dist.iter().chain(&v.max_speed) {
w.f32(*f);
}
w.varint(v.count);
w.varint(v.randomization);
}
}
/// `ExplosionParticleInfo` in a `WeightedList`: a particle the blast
/// scatters, its scaling and speed, then its weight.
#[derive(Clone, Debug, PartialEq)]
pub struct ExplosionParticle {
pub particle: Particle,
pub scaling: f32,
pub speed: f32,
pub weight: i32,
}
/// ClientboundExplodePacket: the centre, radius and blocks destroyed, the
/// push the receiving player takes, the particle at the centre, the sound,
/// the particles the blast scatters, and whether the sound plays.
#[derive(Clone, Debug, PartialEq)]
pub struct Explode {
pub center: [f64; 3],
pub radius: f32,
pub block_count: i32,
pub knockback: Option<[f64; 3]>,
pub particle: Particle,
pub sound: (i32, Option<(String, Option<f32>)>),
pub block_particles: Vec<ExplosionParticle>,
pub play_sound: bool,
}
impl Codec<Explode> for Explode {
fn read(r: &mut Reader) -> Result<Self> {
let center = Vec3d::read(r)?;
let radius = r.f32()?;
let block_count = r.i32()?;
let knockback = <Opt<Vec3d>>::read(r)?;
let particle = Particle::read(r)?;
let sound = SoundHolder::read(r)?;
let n = r.varint()?;
let mut block_particles = Vec::new();
for _ in 0..n {
block_particles.push(ExplosionParticle {
particle: Particle::read(r)?,
scaling: r.f32()?,
speed: r.f32()?,
weight: r.varint()?,
});
}
Ok(Self {
center,
radius,
block_count,
knockback,
particle,
sound,
block_particles,
play_sound: r.bool()?,
})
}
fn write(v: &Self, w: &mut Writer) {
Vec3d::write(&v.center, w);
w.f32(v.radius);
w.i32(v.block_count);
<Opt<Vec3d>>::write(&v.knockback, w);
v.particle.write(w);
SoundHolder::write(&v.sound, w);
w.varint(v.block_particles.len() as i32);
for b in &v.block_particles {
b.particle.write(w);
w.f32(b.scaling);
w.f32(b.speed);
w.varint(b.weight);
}
w.bool(v.play_sound);
}
}
/// `ClientboundSetPlayerTeamPacket.Parameters`.
#[derive(Clone, Debug, PartialEq)]
pub struct TeamParameters {
@@ -1566,6 +1676,8 @@ packet_enum!(Clientbound, crate::ids::play::clientbound {
TickingStep(TickingStep) = TICKING_STEP,
UpdateAdvancements(UpdateAdvancements) = UPDATE_ADVANCEMENTS,
UpdateAttributes(UpdateAttributes) = UPDATE_ATTRIBUTES,
LevelParticles(LevelParticles) = LEVEL_PARTICLES,
Explode(Explode) = EXPLODE,
UpdateMobEffect(UpdateMobEffect) = UPDATE_MOB_EFFECT,
UpdateTags(UpdateTags) = UPDATE_TAGS,
TrackedWaypoint(TrackedWaypoint) = WAYPOINT,
@@ -2270,6 +2382,34 @@ mod tests {
passengers: vec![3, 300],
}),
Clientbound::SetEntityLink(SetEntityLink { source: 2, dest: 0 }),
Clientbound::LevelParticles(LevelParticles {
particle: Particle {
id: 21,
data: Some(crate::entity_data::ParticleData::ColorScale(0xFF0000, 1.5)),
},
override_limiter: true,
always_show: false,
pos: [0.5, 101.0, 3.0],
dist: [0.2, 0.0, 0.2],
max_speed: [0.0; 3],
count: 60,
randomization: 0,
}),
Clientbound::Explode(Explode {
center: [1.0, 2.0, 3.0],
radius: 4.0,
block_count: 12,
knockback: Some([0.5, 0.1, 0.0]),
particle: Particle { id: 29, data: None },
sound: (-1, Some(("minecraft:entity.generic.explode".into(), None))),
block_particles: vec![ExplosionParticle {
particle: Particle { id: 69, data: None },
scaling: 0.5,
speed: 1.0,
weight: 1,
}],
play_sound: true,
}),
Clientbound::ProjectilePower(ProjectilePower { id: 4, power: 0.1 }),
Clientbound::SetEquipment(SetEquipment {
id: 2,
+112 -2
View File
@@ -213,7 +213,7 @@ ROOT = Path(__file__).resolve().parents[1]
GUEST_NAME = 'Guest'
# The host plays single player on its server thread (--server-thread).
SERVER_THREAD = False
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'thrown', 'sparks', 'hud', 'sidebar', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater']
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'thrown', 'sparks', 'hud', 'sidebar', 'border', 'particles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater']
class Game:
@@ -2794,6 +2794,114 @@ def check_sidebar(host, guest, out):
return result
def check_border(host, guest, out):
spots = apart(host, guest)
result = {}
try:
for label, player, other in (('host', host, guest), ('guest', guest, host)):
x, y, z = spots[label]
# A whole-block centre: the wall's collision box is the border's, rounded out to blocks.
cx, cz = float(x), float(z)
# The other player keeps out of harm outside the border meanwhile.
other('command', command='gamemode creative')
host('command', command=f'fill {x - 3} {y - 1} {z} {x + 4} {y - 1} {z + 10} minecraft:stone')
host('command', command=f'fill {x - 3} {y} {z} {x + 4} {y + 3} {z + 10} minecraft:air')
# A border 10 wide around the player, its wall 5 blocks ahead: both sides know it.
host('command', command=f'worldborder center {cx} {cz}')
host('command', command='worldborder set 10')
seen = None
for _ in range(10):
player.wait(2)
seen = [g('status').get('border') for g in (player, other)]
if all(b and b['size'] == 10 and b['center'] == [cx, cz] for b in seen):
break
result[f'{label} border'] = seen
# Sprint-jumping into the wall: it stops the player at the border.
player('command', command=f'tp @s {cx} {y} {cz} 0 0')
player.wait(10)
player.raw('look-at', f'{cx:.2f}', f'{y + 1.6:.2f}', f'{cz + 20:.2f}')
for k in ('w', 'ctrl', 'space'):
player.raw('key', k, 'down')
player.wait(40)
for k in ('space', 'ctrl', 'w'):
player.raw('key', k, 'up')
player.wait(10)
result[f'{label} reached'] = round(pos_of(player)[2] - cz, 2)
player.shot(out, f'border-{label}')
# Two blocks outside, with no safe zone: the border hurts.
host('command', command='worldborder damage buffer 0')
host('command', command='worldborder damage amount 1')
player('command', command='effect give @s minecraft:instant_health 1 5')
player.wait(20)
player('command', command=f'tp @s {cx} {y} {cz + 7}')
player.wait(5)
before = player('status')['player']['health']
player.wait(40)
result[f'{label} hurt'] = [before, player('status')['player']['health']]
player('command', command=f'tp @s {cx} {y} {cz}')
player('command', command='effect give @s minecraft:instant_health 1 5')
host('command', command='worldborder damage amount 0.2')
host('command', command='worldborder damage buffer 5')
other('command', command='gamemode survival')
finally:
guest('command', command='gamemode survival')
host('command', command='gamemode survival')
host('command', command='worldborder damage amount 0.2')
host('command', command='worldborder damage buffer 5')
host('command', command='worldborder center 0 0')
host('command', command='worldborder set 59999968')
wrong = {}
for label in ('host', 'guest'):
x, y, z = spots[label]
known = result[f'{label} border']
if not all(b and b['size'] == 10 and b['center'] == [x, z] for b in known):
wrong[f'{label} border'] = known
if not 4.0 < result[f'{label} reached'] <= 4.71:
wrong[f'{label} reached'] = result[f'{label} reached']
before, after = result[f'{label} hurt']
if not after < before:
wrong[f'{label} hurt'] = result[f'{label} hurt']
assert not wrong, f'border: {wrong}\n{result}'
return result
def check_particles(host, guest, out):
spots = apart(host, guest)
result = {}
for label, player, other in (('host', host, guest), ('guest', guest, host)):
# For the player alone (`@s`), then for every player near.
before = {side: made(g, 'flame') for side, g in (('own', player), ('other', other))}
player('command', command='particle minecraft:flame ~ ~1 ~3 .2 .2 .2 0 60 force @s')
player.wait(10)
result[f'{label} @s'] = {side: made(g, 'flame') - before[side] for side, g in (('own', player), ('other', other))}
player.shot(out, f'flame-{label}')
# No spread: one point, wherever the player stands.
player('command', command='particle minecraft:flame ~ ~1 ~3 0 0 0 0 200 force @s')
player.wait(3)
player.shot(out, f'zero-spread-{label}')
result[f'{label} all'] = sparked(player, other, ['dust'], lambda: player(
'command', command='particle minecraft:dust{color:[1,0,0],scale:2} ~ ~1 ~3 0 0 0 0 10'))
# A TNT's blast between the players: its burst on both sides.
x, y, z = spots['host']
host('command', command='gamemode creative')
guest('command', command='gamemode creative')
try:
result['blast'] = sparked(host, guest, ['explosion_emitter'], lambda: host(
'command', command=f'summon minecraft:tnt {x + 6.5} {y} {z + 4.5} {{fuse:10s}}'), ticks=40)
host.shot(out, 'blast')
finally:
host('command', command='gamemode survival')
guest('command', command='gamemode survival')
host('command', command=f'fill {x - 3} {y - 1} {z - 3} {x + 16} {y - 1} {z + 8} minecraft:stone')
# Without the server thread a guest's command reaches no host player (as `@a` doesn't).
if not SERVER_THREAD:
result['guest all'].pop('other dust')
wrong = {k: v for k, v in result.items() if not k.endswith('@s') and not all(n > 0 for n in v.values())}
wrong.update({k: v for k, v in result.items() if k.endswith('@s') and not (v['own'] >= 30 and v['other'] == 0)})
assert not wrong, f'particles: {wrong}\n{result}'
return result
def check_blast(host, guest, out):
guest('command', command='gamemode survival')
guest('command', command='clear @s')
@@ -4131,7 +4239,9 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour,
'thrown': check_thrown,
'sparks': check_sparks,
'hud': check_hud,
'sidebar': check_sidebar}
'sidebar': check_sidebar,
'border': check_border,
'particles': check_particles}
def run(ctl, out, resources, checks):