From 0281365907e0d71346101b2734bbc28c11046b3e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 28 Oct 2026 17:28:08 +0100 Subject: [PATCH] Signs: keep laid-out sign text between frames, batch entity quads in runs A wall of 3458 text signs ran at 128 fps against 1642 without them: each frame laid every sign's text out again glyph by glyph (Font::glyph_of was a quarter of the main thread), then regrouped every entity quad by material through a per-quad index list. - block_entity_render: a sign's text vertices are kept relative to its block and moved to the camera each frame. They are laid out again when the sign data, block state, light, glowing outline distance or font (Font::epoch: a new font, a glyph cache reset, the Unicode and Japanese options) changes; signs out of view for 100 ticks are dropped. - gfx/entity_batch: quads are grouped in runs of one material and whole runs copied (2-4x faster on model-like input, the same when every quad changes material). Fixes #1461 (the cost per sign; the vanilla text distance of 64 blocks and the look are unchanged). Co-Authored-By: Claude Opus 5.5 --- .../probe/block_entity_render_fixture.rs | 1 + .../horizon-client/src/block_entity_render.rs | 243 +++++++++++++++++- crates/horizon-client/src/font.rs | 15 ++ crates/horizon-client/src/game.rs | 1 + crates/horizon-client/src/game/minecarts.rs | 1 + crates/horizon-client/src/gfx/entity_batch.rs | 91 +++---- 6 files changed, 295 insertions(+), 57 deletions(-) diff --git a/crates/horizon-client/examples/probe/block_entity_render_fixture.rs b/crates/horizon-client/examples/probe/block_entity_render_fixture.rs index 1db978b77..0b2a52a62 100644 --- a/crates/horizon-client/examples/probe/block_entity_render_fixture.rs +++ b/crates/horizon-client/examples/probe/block_entity_render_fixture.rs @@ -369,6 +369,7 @@ pub fn main() -> Result<()> { banner: &|_| layers.clone(), skull: &|_| None, glyph: &|c| atlas.glyph_cell(c), + glyphs: atlas.font.epoch(), }; let mut verts = Vec::new(); renderer.render_block(&scene, pos, state, Mat4::IDENTITY, packed, &mut verts); diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index 280dd9d21..b415748c4 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -597,6 +597,18 @@ fn first_line(line: &str, max_width: f32, advance: &dyn Fn(char) -> f32) -> Stri line.to_owned() } +/// `AbstractSignRenderer.isOutlineVisible`: the camera within 16 blocks of +/// the sign's centre. +fn sign_text_near(pos: [i32; 3], camera: DVec3) -> bool { + DVec3::new( + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ) + .distance_squared(camera) + < 256.0 +} + /// `AbstractSignRenderer.submitSignText`: four centred lines, glowing text /// full-bright with an 8x outline in the dark colour. fn sign_text_calls( @@ -757,6 +769,9 @@ pub struct Scene<'a> { pub skull: &'a dyn Fn([i32; 3]) -> Option, /// Font glyph cell (none for blank glyphs such as the space) and advance. pub glyph: &'a dyn Fn(char) -> (Option, f32), + /// Changes whenever `glyph` may answer differently (`Font::epoch`): sign + /// text laid out under another value is laid out again. + pub glyphs: u64, } pub struct BlockEntityRenderer { @@ -768,7 +783,30 @@ pub struct BlockEntityRenderer { pot_patterns: HashMap, /// `Block.shouldRenderFace` for End gateway faces (its occlusion pair cache needs a lock). visibility: Option>, + sign_texts: Mutex, } +/// Laid-out sign text by position. `AbstractSignRenderer` lays the text out +/// again each frame, glyph by glyph; its vertices only change with what is +/// in the key, so they are kept relative to the block and moved to the camera. +#[derive(Default)] +struct SignTexts { + signs: crate::fast_hash::FxHashMap<[i32; 3], SignTextEntry>, + /// Game time of the last sweep of signs out of view. + swept: i64, +} +struct SignTextEntry { + state: u32, + data: crate::signs::SignData, + packed: u8, + /// Within the glowing text outline's distance (only kept for glowing text). + near: bool, + glyphs: u64, + /// Game time it was last drawn. + used: i64, + vertices: Vec, +} +/// Game ticks a sign's text is kept after it was last drawn. +const SIGN_TEXT_KEEP: i64 = 100; const MODELS: [(&str, &str); 27] = [ ("chest", "minecraft:chest#main"), ("double_chest_left", "minecraft:double_chest_left#main"), @@ -898,6 +936,7 @@ impl BlockEntityRenderer { closed_chests, pot_patterns: HashMap::new(), visibility: None, + sign_texts: Mutex::default(), } } fn kind(&self, state: u32) -> &Kind { @@ -932,11 +971,81 @@ impl BlockEntityRenderer { let origin = (DVec3::new(f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])) - scene.camera) .as_vec3(); - let base = Mat4::from_translation(origin); let packed = scene.world.light(pos[0], pos[1], pos[2]); + if matches!(kind, Kind::Sign { .. }) && scene.texts.is_none() { + self.sign_text(scene, *pos, *state, origin, packed, out); + continue; + } + let base = Mat4::from_translation(origin); self.render_one(scene, *pos, kind, base, packed, lights, false, true, out); } } + /// A sign's text from the cache, laid out again when its data, light, + /// state, outline or font changed. + fn sign_text( + &self, + scene: &Scene, + pos: [i32; 3], + state: u32, + origin: Vec3, + packed: u8, + out: &mut Vec, + ) { + let Some(data) = (scene.sign)(pos) else { + return; + }; + let near = (data.front.glowing || data.back.glowing) && sign_text_near(pos, scene.camera); + let Ok(mut cache) = self.sign_texts.lock() else { + return; + }; + let now = scene.game_time; + if (now - cache.swept).abs() >= SIGN_TEXT_KEEP { + cache.swept = now; + cache + .signs + .retain(|_, e| (now - SIGN_TEXT_KEEP..=now).contains(&e.used)); + } + let glyphs = scene.glyphs; + let signs = &mut cache.signs; + if !signs.get(&pos).is_some_and(|e| { + (e.state, e.packed, e.near, e.glyphs) == (state, packed, near, glyphs) + && e.data == *data + }) { + let mut vertices = signs.remove(&pos).map_or_else(Vec::new, |e| e.vertices); + vertices.clear(); + self.render_one( + scene, + pos, + self.kind(state), + Mat4::IDENTITY, + packed, + diffuse_lights(scene.nether), + false, + true, + &mut vertices, + ); + signs.insert( + pos, + SignTextEntry { + state, + data: data.clone(), + packed, + near, + glyphs, + used: now, + vertices, + }, + ); + } + let Some(entry) = signs.get_mut(&pos) else { + return; + }; + entry.used = now; + out.extend(entry.vertices.iter().map(|v| Vertex { + pos: (Vec3::from_array(v.pos) + origin).to_array(), + ..*v + })); + } /// One block entity at `pos` drawn under `base` with the given packed light /// (the parity fixture's entry point). pub fn render_block( @@ -1168,13 +1277,7 @@ impl BlockEntityRenderer { m *= Mat4::from_translation(Vec3::new(0.0, 1.0 / 3.0, 0.046_666_667)) * Mat4::from_scale(s * 0.010_416_667); } - let near = DVec3::new( - f64::from(pos[0]) + 0.5, - f64::from(pos[1]) + 0.5, - f64::from(pos[2]) + 0.5, - ) - .distance_squared(scene.camera) - < 256.0; + let near = sign_text_near(pos, scene.camera); let calls = sign_text_calls(scene, data, text, m, packed, near); match scene.texts { Some(sink) => sink.borrow_mut().extend(calls), @@ -1954,6 +2057,7 @@ mod tests { banner: &|_| Vec::new(), skull: &|_| None, glyph: &|_| (None, 0.0), + glyphs: 0, }; // Compare the cached world path with the original model renderer, // including atlas replacement, current light and animated fallback. @@ -2154,6 +2258,128 @@ mod tests { assert_eq!(out[2].uv, [0.5, 0.5]); } + #[test] + fn cached_sign_text_matches_and_follows_changes() { + let renderer = BlockEntityRenderer { + models: HashMap::new(), + kinds: vec![ + Kind::Sign { + hanging: false, + wall: false, + angle: 180.0, + }, + Kind::Sign { + hanging: true, + wall: true, + angle: 90.0, + }, + ], + closed_chests: Default::default(), + pot_patterns: HashMap::new(), + visibility: None, + sign_texts: Mutex::default(), + }; + let world = World::new(BlockStateId(0), 1); + let sprites = HashMap::new(); + let text = |line: &str, glowing| crate::signs::SignText { + lines: [line.into(), "two".into(), String::new(), "four".into()], + color: 3, + glowing, + }; + let first_text = crate::signs::SignData { + front: text("one", false), + ..Default::default() + }; + let changed = crate::signs::SignData { + front: text("changed", false), + ..Default::default() + }; + let glowing = crate::signs::SignData { + back: text("glow", true), + ..changed.clone() + }; + let wide = std::cell::Cell::new(6.0); + let glyph = |c: char| { + let u = f32::from(c as u8 % 16) / 16.0; + let rect = Rect { + u0: u, + v0: 0.0, + u1: u + 0.0625, + v1: 0.0625, + w: 8, + h: 8, + }; + ((c != ' ').then_some(rect), wide.get()) + }; + let (first_sign, changed_sign, glowing_sign) = ( + |_| Some(&first_text), + |_| Some(&changed), + |_| Some(&glowing), + ); + let mut scene = Scene { + camera: DVec3::new(3.25, 70.5, -4.75), + orientation: Quat::IDENTITY, + anim: &|_| BlockAnim::default(), + texts: None, + partial: 0.0, + game_time: 0, + max_y: 320, + world: &world, + sprites: &sprites, + nether: false, + lid: &|_| 0.0, + sign: &first_sign, + banner: &|_| Vec::new(), + skull: &|_| None, + glyph: &glyph, + glyphs: 0, + }; + let check = |scene: &Scene, pos: [i32; 3], state: u32| { + let mut cached = Vec::new(); + renderer.render(scene, [(pos, state)].iter(), &mut cached); + let corner = DVec3::new(f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])); + let mut original = Vec::new(); + renderer.render_one( + scene, + pos, + renderer.kind(state), + Mat4::from_translation((corner - scene.camera).as_vec3()), + world.light(pos[0], pos[1], pos[2]), + diffuse_lights(false), + false, + true, + &mut original, + ); + assert!(!cached.is_empty()); + assert_eq!(cached.len(), original.len()); + for (a, b) in cached.iter().zip(&original) { + assert!((Vec3::from_array(a.pos) - Vec3::from_array(b.pos)).length() < 1e-5); + assert_eq!((a.uv, a.color, a.light), (b.uv, b.color, b.light)); + } + cached.len() + }; + let (pos, other) = ([1, 70, 2], [-3, 64, 9]); + let first = check(&scene, pos, 0); + // The camera moves: the same text, moved. + scene.camera.x += 0.5; + check(&scene, pos, 0); + // New text, glowing text near and far, another state, other glyphs. + scene.sign = &changed_sign; + assert_ne!(check(&scene, pos, 0), first); + scene.sign = &glowing_sign; + check(&scene, pos, 0); + scene.camera.z -= 20.0; + check(&scene, pos, 0); + check(&scene, pos, 1); + check(&scene, other, 1); + wide.set(5.0); + scene.glyphs = 1; + check(&scene, pos, 1); + // Signs out of view for a while are dropped. + scene.game_time = 2 * SIGN_TEXT_KEEP; + check(&scene, pos, 0); + assert_eq!(renderer.sign_texts.lock().unwrap().signs.len(), 1); + } #[test] fn first_line_wraps_on_bytes_without_splitting_a_char() { let advance = |c: char| if c == ' ' { 4.0 } else { 6.0 }; @@ -2214,6 +2440,7 @@ mod tests { banner: &|_| Vec::new(), skull: &|_| None, glyph: &|_| (None, 0.0), + glyphs: 0, }; let mut verts = Vec::new(); renderer.render_block(&scene, [0; 3], state.0, Mat4::IDENTITY, 0xff, &mut verts); diff --git a/crates/horizon-client/src/font.rs b/crates/horizon-client/src/font.rs index 2bb712612..a76ed8171 100644 --- a/crates/horizon-client/src/font.rs +++ b/crates/horizon-client/src/font.rs @@ -130,6 +130,8 @@ pub struct Font { atlas: (u32, u32), region: (u32, u32), cache: RefCell, + /// Set anew for each font and each `reset_cache` (see `epoch`). + generation: std::cell::Cell, /// "Force Unicode Font": the `uniform` filter option. pub uniform: bool, /// "Japanese Glyph Variants": the `jp` filter option. @@ -559,6 +561,11 @@ impl Region { Some((ax, ay)) } } +/// A value no font has had yet (`Font::epoch`). +fn next_generation() -> u64 { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) +} impl Font { /// Build from the atlas holding the bitmap font sheets (`sprites`, of /// `atlas` size) with `region` the reserved rows. @@ -603,6 +610,7 @@ impl Font { .map_or(0, |d| d.as_nanos() as i64), ), }), + generation: std::cell::Cell::new(next_generation()), uniform: false, japanese: false, }; @@ -661,6 +669,13 @@ impl Font { } cache.region.cursor = (0, 0); cache.region.row = 0; + self.generation.set(next_generation()); + } + /// Changes whenever a glyph may come out different: another font, a + /// cache reset (glyphs move in the atlas) or other font options. Text laid + /// out under one epoch can be kept until it changes. + pub fn epoch(&self) -> u64 { + self.generation.get() << 2 | u64::from(self.uniform) << 1 | u64::from(self.japanese) } /// The glyph for a character in the default font (FontSet.getGlyph). pub fn glyph(&self, c: char) -> Glyph { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index dddd4f56b..febef3254 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -8081,6 +8081,7 @@ impl Game<'_> { banner: &|p| self.banner_layers_at(p), skull: &|p| self.skull_skin_at(p), glyph: &|c| self.gui.atlas.glyph_cell(c), + glyphs: self.gui.atlas.font.epoch(), }; // Block entities outside the view frustum are skipped (with a // block of margin for models larger than their block). diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index a56f107a2..6b01ae76a 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -1459,6 +1459,7 @@ impl Game<'_> { banner: &|_| Vec::new(), skull: &|_| None, glyph: &|c| self.gui.atlas.glyph_cell(c), + glyphs: self.gui.atlas.font.epoch(), }; self.res .block_entity_render() diff --git a/crates/horizon-client/src/gfx/entity_batch.rs b/crates/horizon-client/src/gfx/entity_batch.rs index f71545f2c..c9a9303ed 100644 --- a/crates/horizon-client/src/gfx/entity_batch.rs +++ b/crates/horizon-client/src/gfx/entity_batch.rs @@ -25,12 +25,26 @@ pub const TRANSLUCENT_ITEM_OVERLAY: u32 = 32; /// A translucent item with an enchantment glint. pub const TRANSLUCENT_GLINT_ITEM_OVERLAY: u32 = 33; +/// The material of a quad by its overlay (`MATERIALS` order). +fn material(layer: u32) -> usize { + match layer { + 11 => 1, + 12 => 2, + WATER_MASK_OVERLAY => 3, + ENERGY_SWIRL_OVERLAY => 4, + SHADOW_OVERLAY => 5, + TRANSLUCENT_PARTICLE_OVERLAY => 6, + TRANSLUCENT_ITEM_OVERLAY | TRANSLUCENT_GLINT_ITEM_OVERLAY => 7, + _ => 0, + } +} + #[derive(Default)] pub(super) struct EntityBatch { - // Quad indices avoid copying vertices twice while grouping materials. - // Keep initialized high-water storage; local counts delimit active entries. - // Each bucket can hold all quads, removing per-quad Vec growth checks. - buckets: [Vec; MATERIALS], + // Runs of consecutive quads of one material (first quad, quad count): a + // model's quads share one, so whole runs are copied at once. Cleared each + // frame, keeping their storage. + runs: [Vec<(usize, usize)>; MATERIALS], pub(super) combined: Vec, } @@ -43,50 +57,29 @@ impl EntityBatch { see_through: &[Vertex], ) -> [u32; MATERIALS] { let quads = entities.as_chunks::<4>().0; - for bucket in &mut self.buckets { - if bucket.len() < quads.len() { - bucket.resize(quads.len(), 0); - } + for runs in &mut self.runs { + runs.clear(); } let mut counts = [0usize; MATERIALS]; - for (index, quad) in quads.iter().enumerate() { - let material = match quad[0].layer { - 11 => 1, - 12 => 2, - WATER_MASK_OVERLAY => 3, - ENERGY_SWIRL_OVERLAY => 4, - SHADOW_OVERLAY => 5, - TRANSLUCENT_PARTICLE_OVERLAY => 6, - TRANSLUCENT_ITEM_OVERLAY | TRANSLUCENT_GLINT_ITEM_OVERLAY => 7, - _ => 0, - }; - self.buckets[material][counts[material]] = index; - counts[material] += 1; + let mut start = 0; + while start < quads.len() { + let kind = material(quads[start][0].layer); + let end = quads[start + 1..] + .iter() + .position(|quad| material(quad[0].layer) != kind) + .map_or(quads.len(), |n| start + 1 + n); + self.runs[kind].push((start, end - start)); + counts[kind] += end - start; + start = end; } let entity_vertices = quads.len() * 4; - self.combined.reserve( - (entity_vertices + additive.len() + hand.len() + see_through.len()) - .saturating_sub(self.combined.len()), - ); + self.combined.clear(); self.combined - .resize(entity_vertices, bytemuck::Zeroable::zeroed()); - if counts.contains(&quads.len()) { - // Uniform materials are already ordered; copy the whole batch. - self.combined.copy_from_slice(&entities[..entity_vertices]); - } else { - let mut offset = 0; - for (bucket, &count) in self.buckets.iter().zip(&counts) { - let bucket = &bucket[..count]; - let end = offset + count * 4; - for (output, &index) in self.combined[offset..end] - .as_chunks_mut::<4>() - .0 - .iter_mut() - .zip(bucket) - { - *output = quads[index]; - } - offset = end; + .reserve(entity_vertices + additive.len() + hand.len() + see_through.len()); + for runs in &self.runs { + for &(first, count) in runs { + self.combined + .extend_from_slice(&entities[first * 4..(first + count) * 4]); } } self.combined.extend_from_slice(additive); @@ -174,12 +167,12 @@ mod tests { let hand = geometry(2, false); // Warm every bucket and the combined buffer to their maximum sizes. equivalent(&mut batch, &entities, &additive, &hand); - let capacities = batch.buckets.each_ref().map(|b| b.capacity()); + let capacities = batch.runs.each_ref().map(|b| b.capacity()); let capacity = batch.combined.capacity(); let pointer = batch.combined.as_ptr(); for length in [0, 1, 3, 4, 511, entities.len(), 17, 0, entities.len()] { equivalent(&mut batch, &entities[..length], &additive[..5], &hand[..3]); - assert_eq!(batch.buckets.each_ref().map(|b| b.capacity()), capacities); + assert_eq!(batch.runs.each_ref().map(|b| b.capacity()), capacities); assert_eq!(batch.combined.capacity(), capacity); assert_eq!(batch.combined.as_ptr(), pointer); } @@ -188,11 +181,11 @@ mod tests { // Grow again, then confirm empty/small frames retain the new storage. let larger = geometry(8192, true); equivalent(&mut batch, &larger, &additive, &hand); - let capacities = batch.buckets.each_ref().map(|b| b.capacity()); + let capacities = batch.runs.each_ref().map(|b| b.capacity()); let capacity = batch.combined.capacity(); for entities in [&larger[..7], &larger[..], &[]] { equivalent(&mut batch, entities, &[], &[]); - assert_eq!(batch.buckets.each_ref().map(|b| b.capacity()), capacities); + assert_eq!(batch.runs.each_ref().map(|b| b.capacity()), capacities); assert_eq!(batch.combined.capacity(), capacity); } } @@ -255,9 +248,9 @@ mod tests { before[7] as f64 / after[7] as f64, batch.combined.capacity() * std::mem::size_of::() + batch - .buckets + .runs .iter() - .map(|b| b.capacity() * std::mem::size_of::()) + .map(|b| b.capacity() * std::mem::size_of::<(usize, usize)>()) .sum::() ); }