Skip to content

Minecraft: Java Edition 26.3 rewritten from scratch in Rust, checked against vanilla with 281 differential harnesses. Get it with the Horizon launcher.

Entity walk: static dispatch, no allocation

HrafnaValkyrjaa651e476a332
diff --git a/crates/horizon-client/src/game/entity.rs b/crates/horizon-client/src/game/entity.rs
index 1bca4af31..e35d6a47f 100644
--- a/crates/horizon-client/src/game/entity.rs
+++ b/crates/horizon-client/src/game/entity.rs
@@ -3,8 +3,9 @@
//!
//! Default methods follow vanilla's `Entity`; a kind overrides one only where
//! its vanilla class does. [`EntityHandle`] names one entity by list and index,
-//! so a system can collect handles and reach each entity after other borrows of
-//! `Game` end. A new kind is one line in `entity_lists!` and one `impl Entity`.
+//! so a system can walk handles and reach each entity after other borrows of
+//! `Game` end. The walk allocates nothing and dispatch is static: hot paths pay
+//! no vtable. A new kind is one line in `entity_lists!` and one `impl Entity`.
use super::{FallingBlock, Game};
use super::{
@@ -69,9 +70,30 @@ macro_rules! stored_motion {
};
}
-/// The game's lists of entities, in the order systems walk them.
+/// The game's lists of entities, in the order systems walk them. Hands them to
+/// `$then`, so one list drives the handles and every typed dispatch.
macro_rules! entity_lists {
- ($($kind:ident: $($list:ident).+,)*) => {
+ ($then:ident, $($args:tt)*) => {
+ $crate::game::entity::$then! {
+ ($($args)*)
+ Mob: mobs,
+ Item: dropped,
+ Boat: boats,
+ Cart: carts,
+ ArmorStand: armor_stands,
+ Tnt: tnts,
+ Falling: falling,
+ Orb: orbs,
+ Projectile: creatures.projectiles,
+ Rocket: rockets,
+ Trident: tridents,
+ }
+ };
+}
+pub(crate) use entity_lists;
+
+macro_rules! define_entity_handles {
+ (() $($kind:ident: $($list:ident).+,)*) => {
/// One entity, by list and index.
#[derive(Clone, Copy, Hash, PartialEq, Eq)]
pub(super) enum EntityHandle {
@@ -79,40 +101,48 @@ macro_rules! entity_lists {
}
impl Game<'_> {
- pub(super) fn entity_handles(&self) -> Vec<EntityHandle> {
- let mut handles = Vec::new();
- $(handles.extend((0..self$(.$list)+.len()).map(EntityHandle::$kind));)*
- handles
+ /// Every entity's handle: lengths read now, nothing allocated, and
+ /// no borrow of `Game` held, so the caller can change it mid-walk.
+ pub(super) fn entity_handles(&self) -> impl Iterator<Item = EntityHandle> + use<> {
+ std::iter::empty()
+ $(.chain((0..self$(.$list)+.len()).map(EntityHandle::$kind)))*
}
+ }
+ };
+}
+pub(crate) use define_entity_handles;
- pub(super) fn entity(&self, handle: EntityHandle) -> &dyn Entity {
- match handle {
- $(EntityHandle::$kind(i) => &self$(.$list)+[i],)*
- }
- }
+entity_lists!(define_entity_handles,);
- pub(super) fn entity_mut(&mut self, handle: EntityHandle) -> &mut dyn Entity {
- match handle {
- $(EntityHandle::$kind(i) => &mut self$(.$list)+[i],)*
- }
- }
+macro_rules! match_entity {
+ (($binding:pat, $game:expr, $handle:expr, $body:expr)
+ $($kind:ident: $($list:ident).+,)*) => {
+ match $handle {
+ $($crate::game::entity::EntityHandle::$kind(i) => {
+ let $binding = $game$(.$list)+[i];
+ $body
+ })*
}
};
}
+pub(crate) use match_entity;
+
+/// Runs `$body` with `$entity` bound to the handle's entity, as its own type:
+/// one match, each arm compiled for its kind, so nothing goes through a vtable.
+macro_rules! with_entity {
+ ($game:expr, $handle:expr, $entity:ident => $body:expr) => {
+ $crate::game::entity::entity_lists!(match_entity, ref $entity, $game, $handle, $body)
+ };
+}
+pub(super) use with_entity;
-entity_lists! {
- Mob: mobs,
- Item: dropped,
- Boat: boats,
- Cart: carts,
- ArmorStand: armor_stands,
- Tnt: tnts,
- Falling: falling,
- Orb: orbs,
- Projectile: creatures.projectiles,
- Rocket: rockets,
- Trident: tridents,
+/// [`with_entity`], with the entity mutable.
+macro_rules! with_entity_mut {
+ ($game:expr, $handle:expr, $entity:ident => $body:expr) => {
+ $crate::game::entity::entity_lists!(match_entity, ref mut $entity, $game, $handle, $body)
+ };
}
+pub(super) use with_entity_mut;
impl Entity for Mob {
stored_motion!();
diff --git a/crates/horizon-client/src/game/piston_push.rs b/crates/horizon-client/src/game/piston_push.rs
index 1c5b4d777..3c78b52bf 100644
--- a/crates/horizon-client/src/game/piston_push.rs
+++ b/crates/horizon-client/src/game/piston_push.rs
@@ -9,7 +9,10 @@
//! then run through the block collision scan, so a pushed entity stops at a
//! wall instead of passing through it.
//!
-use super::{Game, entity::EntityHandle};
+use super::{
+ Game,
+ entity::{Entity, EntityHandle, with_entity, with_entity_mut},
+};
use horizon_client::collisions::{EntityCollisions, SceneCollisions, with_piston_noclip};
use horizon_core::geometry::{Aabb, Axis, Direction, ShapeOp, Vec3, border::BorderGeometry};
use horizon_core::position::BlockPos;
@@ -177,8 +180,7 @@ impl Game<'_> {
delta_progress,
)
});
- let targets = self.push_targets();
- for &target in &targets {
+ for target in self.push_targets() {
let Some(body) = self.push_body(target, pos, &steps) else {
continue;
};
@@ -235,7 +237,7 @@ impl Game<'_> {
// Vanilla selects honey passengers after all collided entities have moved.
if honey && movement.normal()[1] == 0 {
let area = piston_push::sticky_area(pos, piston.shape_state(), sticky_top);
- for target in targets {
+ for target in self.push_targets() {
let Some(body) = self.push_body(target, pos, &steps) else {
continue;
};
@@ -335,22 +337,21 @@ impl Game<'_> {
/// The entities a moving block can run into: the window's player, the LAN
/// guests in the level, then the mobs.
- fn push_targets(&self) -> Vec<Target> {
- let mut targets = Vec::new();
- if self.player.is_some() {
- targets.push(Target::Player);
- }
- if let Some(host) = self.lan.as_ref() {
- targets.extend(
- host.hub
- .guests
- .iter()
- .filter(|g| host.hub.here(g) && g.loaded && !g.dead)
- .map(|g| Target::Guest(g.conn)),
- );
- }
- targets.extend(self.entity_handles().into_iter().map(Target::Entity));
- targets
+ fn push_targets(&self) -> impl Iterator<Item = Target> + use<> {
+ let player = self.player.is_some().then_some(Target::Player);
+ // Empty, and so unallocated, unless guests are here.
+ let guests: Vec<Target> = self.lan.as_ref().map_or_else(Vec::new, |host| {
+ host.hub
+ .guests
+ .iter()
+ .filter(|g| host.hub.here(g) && g.loaded && !g.dead)
+ .map(|g| Target::Guest(g.conn))
+ .collect()
+ });
+ player
+ .into_iter()
+ .chain(guests)
+ .chain(self.entity_handles().map(Target::Entity))
}
/// What the push needs from one entity, or `None` when it is not pushed:
@@ -391,19 +392,18 @@ impl Game<'_> {
.is_some_and(|m| m.ground.supporting_block == Some(pos)),
})
}
- Target::Entity(handle) => {
- let entity = self.entity(handle);
+ Target::Entity(handle) => with_entity!(self, handle, entity => {
if !entity.is_alive() || entity.get_piston_push_reaction() == IgnoreEntity {
return None;
}
Some(Body {
- bounds: entity.bounds(),
+ bounds: Entity::bounds(entity),
position: entity.position(),
on_ground: entity.on_ground(),
step_height: entity.get_step_height(),
supported: entity.is_supported_by(pos),
})
- }
+ }),
}
}
@@ -503,7 +503,9 @@ impl Game<'_> {
}
}
}
- Target::Entity(handle) => self.entity_mut(handle).move_by_piston(movement),
+ Target::Entity(handle) => {
+ with_entity_mut!(self, handle, entity => entity.move_by_piston(movement))
+ }
}
}
@@ -523,7 +525,9 @@ impl Game<'_> {
motion.velocity = piston_push::bounce_velocity(movement, motion.velocity);
}
}
- Target::Entity(handle) => self.entity_mut(handle).piston_slime_bounce(movement),
+ Target::Entity(handle) => {
+ with_entity_mut!(self, handle, entity => Entity::piston_slime_bounce(entity, movement))
+ }
}
}
}