Merge pull request #829 from ludovic111/perf/anim-tick-hash

🤖 Agent: merged: block-entity animation list rebuilt only when drawn block entities change (anim tick −82% with 32,768 chests). perf-ticks-7's four PRs together on main d85a3603: clippy, 861 client + world tests, 19 harnesses (light, lan, dedicated_server, save_roundtrip, world_reopen, disk, datafix ×6, world, server_world_gen, block_entity ×4, chunk_stage) PASS.
This commit is contained in:
Ludovic Marie
2026-10-18 09:45:28 +02:00
committed by GitHub
3 changed files with 73 additions and 35 deletions
+33 -22
View File
@@ -12,11 +12,11 @@
//! (blocks, entities, game time) as closures, so the parity fixture can drive //! (blocks, entities, game time) as closures, so the parity fixture can drive
//! them with scripted inputs (`tools/test_block_entity_anim_parity.py`). //! them with scripted inputs (`tools/test_block_entity_anim_parity.py`).
use crate::block_entity_render::BlockAnim; use crate::block_entity_render::BlockAnim;
use crate::fast_hash::FxHashMap;
use horizon_core::{ use horizon_core::{
geometry::trig::{self, Mth}, geometry::trig::{self, Mth},
random::{LegacyRandom, RandomSource}, random::{LegacyRandom, RandomSource},
}; };
use std::collections::HashMap;
/// `Direction` names by `get3DDataValue`. /// `Direction` names by `get3DDataValue`.
pub const DIRECTIONS: [&str; 6] = ["down", "up", "north", "south", "west", "east"]; pub const DIRECTIONS: [&str; 6] = ["down", "up", "north", "south", "west", "east"];
@@ -832,38 +832,44 @@ pub fn ticker(name: &str, prop: impl Fn(&str) -> Option<String>) -> Option<Ticke
/// The animated block entities of a level, by position. /// The animated block entities of a level, by position.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct BlockEntityAnims { pub struct BlockEntityAnims {
pub chests: HashMap<[i32; 3], ChestLid>, pub chests: FxHashMap<[i32; 3], ChestLid>,
pub books: HashMap<[i32; 3], EnchantingBook>, pub books: FxHashMap<[i32; 3], EnchantingBook>,
/// `EnchantingTableBlockEntity.RANDOM`, shared by every table. /// `EnchantingTableBlockEntity.RANDOM`, shared by every table.
pub book_random: LegacyRandom, pub book_random: LegacyRandom,
pub shulkers: HashMap<[i32; 3], Shulker>, pub shulkers: FxHashMap<[i32; 3], Shulker>,
pub bells: HashMap<[i32; 3], Bell>, pub bells: FxHashMap<[i32; 3], Bell>,
pub conduits: HashMap<[i32; 3], Conduit>, pub conduits: FxHashMap<[i32; 3], Conduit>,
pub skulls: HashMap<[i32; 3], Skull>, pub skulls: FxHashMap<[i32; 3], Skull>,
pub pots: HashMap<[i32; 3], PotWobble>, pub pots: FxHashMap<[i32; 3], PotWobble>,
pub gateways: HashMap<[i32; 3], EndGateway>, pub gateways: FxHashMap<[i32; 3], EndGateway>,
/// The integrated server's copies of the gateways (`portalTick`). /// The integrated server's copies of the gateways (`portalTick`).
pub gateway_servers: HashMap<[i32; 3], EndGateway>, pub gateway_servers: FxHashMap<[i32; 3], EndGateway>,
/// The client level's random (conduit particles). /// The client level's random (conduit particles).
pub random: LegacyRandom, pub random: LegacyRandom,
/// [`Ticker`] by block state id (see [`BlockEntityAnims::classify`]). /// [`Ticker`] by block state id (see [`BlockEntityAnims::classify`]).
pub kinds: Vec<Option<Ticker>>, pub kinds: Vec<Option<Ticker>>,
/// The drawn block entities with a ticker, sorted by position, and the
/// renderer's block entity revision they were read at.
pub present: Vec<([i32; 3], Ticker)>,
pub present_revision: Option<u64>,
} }
impl Default for BlockEntityAnims { impl Default for BlockEntityAnims {
fn default() -> Self { fn default() -> Self {
Self { Self {
chests: HashMap::new(), chests: FxHashMap::default(),
books: HashMap::new(), books: FxHashMap::default(),
book_random: LegacyRandom::new(0x626f6f6b), book_random: LegacyRandom::new(0x626f6f6b),
shulkers: HashMap::new(), shulkers: FxHashMap::default(),
bells: HashMap::new(), bells: FxHashMap::default(),
conduits: HashMap::new(), conduits: FxHashMap::default(),
skulls: HashMap::new(), skulls: FxHashMap::default(),
pots: HashMap::new(), pots: FxHashMap::default(),
gateways: HashMap::new(), gateways: FxHashMap::default(),
gateway_servers: HashMap::new(), gateway_servers: FxHashMap::default(),
random: LegacyRandom::new(0x6c6576656c), random: LegacyRandom::new(0x6c6576656c),
kinds: Vec::new(), kinds: Vec::new(),
present: Vec::new(),
present_revision: None,
} }
} }
} }
@@ -877,15 +883,20 @@ impl BlockEntityAnims {
.and_then(|s| ticker(&s.name, |k| s.properties.get(k).cloned())) .and_then(|s| ticker(&s.name, |k| s.properties.get(k).cloned()))
}) })
.collect(); .collect();
self.present_revision = None;
} }
/// The ticker of a block state. /// The ticker of a block state.
pub fn ticker(&self, state: u32) -> Option<Ticker> { pub fn ticker(&self, state: u32) -> Option<Ticker> {
self.kinds.get(state as usize).copied().flatten() self.kinds.get(state as usize).copied().flatten()
} }
/// Drops the state of block entities that are gone or changed kind: /// Drops the state of block entities that are gone or changed kind:
/// `present` maps the loaded block entities to their tickers. /// `present` holds the loaded block entities' tickers, sorted by position.
pub fn retain_present(&mut self, present: &HashMap<[i32; 3], Ticker>) { pub fn retain_present(&mut self, present: &[([i32; 3], Ticker)]) {
let is = |p: &[i32; 3], f: fn(&Ticker) -> bool| present.get(p).is_some_and(f); let is = |p: &[i32; 3], f: fn(&Ticker) -> bool| {
present
.binary_search_by_key(p, |(q, _)| *q)
.is_ok_and(|i| f(&present[i].1))
};
self.chests.retain(|p, _| is(p, |t| *t == Ticker::Lid)); self.chests.retain(|p, _| is(p, |t| *t == Ticker::Lid));
self.books.retain(|p, _| is(p, |t| *t == Ticker::Book)); self.books.retain(|p, _| is(p, |t| *t == Ticker::Book));
self.shulkers self.shulkers
@@ -13,7 +13,6 @@ use horizon_client::{
}; };
use horizon_core::geometry::{Aabb, Vec3}; use horizon_core::geometry::{Aabb, Vec3};
use horizon_world::nbt::Tag; use horizon_world::nbt::Tag;
use std::collections::HashMap;
/// The handle of the local player among a bell's gathered entities. /// The handle of the local player among a bell's gathered entities.
const PLAYER: u64 = u64::MAX; const PLAYER: u64 = u64::MAX;
@@ -174,11 +173,20 @@ impl Game<'_> {
let Some(r) = &self.renderer else { let Some(r) = &self.renderer else {
return; return;
}; };
let present: HashMap<[i32; 3], Ticker> = r // Sorted by position: the order they tick in, and a quick lookup.
.block_entities() // Read again only when the drawn block entities changed.
.filter_map(|(p, s)| Some((*p, self.be_anims.ticker(*s)?))) let revision = r.block_entity_revision();
.collect(); if self.be_anims.present_revision != Some(revision) {
self.be_anims.retain_present(&present); let mut present: Vec<([i32; 3], Ticker)> = r
.block_entities()
.filter_map(|(p, s)| Some((*p, self.be_anims.ticker(*s)?)))
.collect();
present.sort_unstable_by_key(|(p, _)| *p);
self.be_anims.retain_present(&present);
self.be_anims.present = present;
self.be_anims.present_revision = Some(revision);
}
let positions = std::mem::take(&mut self.be_anims.present);
let players: Vec<[f64; 3]> = match &self.player { let players: Vec<[f64; 3]> = match &self.player {
Some(p) if !self.spectator() => vec![[p.position.x, p.position.y, p.position.z]], Some(p) if !self.spectator() => vec![[p.position.x, p.position.y, p.position.z]],
_ => Vec::new(), _ => Vec::new(),
@@ -198,9 +206,7 @@ impl Game<'_> {
.get("minecraft:conduit_effect_block") .get("minecraft:conduit_effect_block")
.cloned() .cloned()
.unwrap_or_default(); .unwrap_or_default();
let mut positions: Vec<([i32; 3], Ticker)> = present.into_iter().collect(); for &(pos, ticker) in &positions {
positions.sort_unstable_by_key(|(p, _)| *p);
for (pos, ticker) in positions {
match ticker { match ticker {
Ticker::Lid => self.be_anims.chests.entry(pos).or_default().tick(), Ticker::Lid => self.be_anims.chests.entry(pos).or_default().tick(),
Ticker::Book => { Ticker::Book => {
@@ -322,6 +328,7 @@ impl Game<'_> {
} }
} }
} }
self.be_anims.present = positions;
} }
/// `EndGatewayBlock.entityInside` on the server: whether the gateway at /// `EndGatewayBlock.entityInside` on the server: whether the gateway at
/// `pos` let the entity in (`triggerCooldown`, with its block event). /// `pos` let the entity in (`triggerCooldown`, with its block event).
+24 -4
View File
@@ -69,6 +69,12 @@ pub mod translucency;
pub(crate) mod upload; pub(crate) mod upload;
mod world_post; mod world_post;
/// A new value for `Renderer::block_entity_revision`.
fn next_block_entity_revision() -> u64 {
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}
#[repr(C)] #[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] #[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct Globals { struct Globals {
@@ -348,6 +354,8 @@ pub struct Renderer {
draw_pages: Vec<(u32, Option<u32>)>, draw_pages: Vec<(u32, Option<u32>)>,
/// Block-entity blocks per meshed section (world position, state id). /// Block-entity blocks per meshed section (world position, state id).
block_entities: HashMap<SectionKey, Vec<([i32; 3], u32)>>, block_entities: HashMap<SectionKey, Vec<([i32; 3], u32)>>,
/// Changes whenever `block_entities` does (unique across renderers).
block_entity_revision: u64,
/// VisGraph face connectivity per meshed section (cave culling). /// VisGraph face connectivity per meshed section (cave culling).
occlusion: occlusion::Occlusion, occlusion: occlusion::Occlusion,
/// Resolution scale and FXAA (Horizon settings). /// Resolution scale and FXAA (Horizon settings).
@@ -1821,6 +1829,7 @@ impl Renderer {
draws: Vec::new(), draws: Vec::new(),
draw_pages: Vec::new(), draw_pages: Vec::new(),
block_entities: HashMap::new(), block_entities: HashMap::new(),
block_entity_revision: next_block_entity_revision(),
occlusion: occlusion::Occlusion::new(crate::chunk::HEIGHT / 16), occlusion: occlusion::Occlusion::new(crate::chunk::HEIGHT / 16),
world_post, world_post,
pack: None, pack: None,
@@ -1987,10 +1996,14 @@ impl Renderer {
} }
pub fn upload(&mut self, key: SectionKey, mesh: &SectionMesh) { pub fn upload(&mut self, key: SectionKey, mesh: &SectionMesh) {
self.occlusion.set(key, mesh.visibility); self.occlusion.set(key, mesh.visibility);
if mesh.block_entities.is_empty() { let changed = if mesh.block_entities.is_empty() {
self.block_entities.remove(&key); self.block_entities.remove(&key).is_some()
} else { } else {
self.block_entities.insert(key, mesh.block_entities.clone()); let old = self.block_entities.insert(key, mesh.block_entities.clone());
old.as_deref() != Some(&mesh.block_entities[..])
};
if changed {
self.block_entity_revision = next_block_entity_revision();
} }
let solid = (mesh.solid.len() / 4) as u32; let solid = (mesh.solid.len() / 4) as u32;
let translucent = (mesh.translucent.len() / 4) as u32; let translucent = (mesh.translucent.len() / 4) as u32;
@@ -2099,8 +2112,13 @@ impl Renderer {
pub fn block_entities(&self) -> impl Iterator<Item = &([i32; 3], u32)> { pub fn block_entities(&self) -> impl Iterator<Item = &([i32; 3], u32)> {
self.block_entities.values().flatten() self.block_entities.values().flatten()
} }
/// A value that changes whenever `block_entities` gives something else.
pub fn block_entity_revision(&self) -> u64 {
self.block_entity_revision
}
pub fn clear_sections(&mut self) { pub fn clear_sections(&mut self) {
self.block_entities.clear(); self.block_entities.clear();
self.block_entity_revision = next_block_entity_revision();
self.sections.clear(); self.sections.clear();
self.arena.clear(); self.arena.clear();
if let Some(flat) = &mut self.flat { if let Some(flat) = &mut self.flat {
@@ -2111,7 +2129,9 @@ impl Renderer {
self.occlusion.clear(); self.occlusion.clear();
} }
pub fn remove(&mut self, key: SectionKey) { pub fn remove(&mut self, key: SectionKey) {
self.block_entities.remove(&key); if self.block_entities.remove(&key).is_some() {
self.block_entity_revision = next_block_entity_revision();
}
self.occlusion.remove(key); self.occlusion.remove(key);
self.release_section(key); self.release_section(key);
} }