Minecraft: Java Edition 26.3 rewritten from scratch in Rust, checked against vanilla with 281 differential harnesses. Get it with the Horizon launcher.
Rust differential-testinggame-enginegamedevlinuxminecraftminecraft-javareimplementationrustvoxelvulkanwgpu
Mesher: ~21% less CPU per section, same meshes
Ludovic Marie44b03616c1ac
diff --git a/crates/horizon-client-render/src/mesher.rs b/crates/horizon-client-render/src/mesher.rsindex 876177636..1f9862a17 100644--- a/crates/horizon-client-render/src/mesher.rs+++ b/crates/horizon-client-render/src/mesher.rs@@ -12,7 +12,7 @@ use crate::{assets::{Assets, RenderAssets},biome::Biomes,blocks::{BlockFacts, RenderShape},- chunk::{Chunk, MIN_Y},+ chunk::{Chunk, Light, MIN_Y},graphics::LeafCullingMode,models::catalog::BakedFace,};@@ -505,6 +505,10 @@ pub struct MeshFacts {}pub struct MeshTables {info: Vec<Info>,+ /// `Info::solid` by state, packed apart: the opacity mask of a section+ /// reads 8,000 states, and a few bytes each stay in cache where `Info`+ /// does not.+ solid: Vec<bool>,pub visibility: FaceVisibility,water_still: u16,water_flow: u16,@@ -673,6 +677,7 @@ impl MeshTables {});}Ok(Self {+ solid: info.iter().map(|i| i.solid).collect(),info,visibility,water_still: layer("minecraft:block/water_still")?,@@ -842,43 +847,66 @@ impl Padded {}fn fill(&mut self, region: &[[Option<&Chunk>; 3]; 3], sy: i32, own: &mut [u32; 4096]) {self.blocks.resize(P * P * P, 0);- self.blocks.fill(0);self.light.resize(P * P * P, 0);let (blocks, light) = (&mut self.blocks, &mut self.light);let base_y = region[1][1].map_or(MIN_Y, Chunk::min_y) + sy * 16;- // The section itself is unpacked in one pass; the border cells of the- // neighbouring sections are read one by one.+ // The section itself is unpacked in one pass and copied row by row;+ // the border cells of the neighbouring sections are read one by one,+ // each run of them from a section found once.own.fill(0);let center = region[1][1].map(|c| &c.sections[sy as usize]);if let Some(section) = center {section.unpack(own);}+ // The x runs of a padded row by the chunk column they fall in.+ const RUNS: [(usize, i32, i32); 3] = [(0, -B, 0), (1, 0, 16), (2, 16, 16 + B)];for y in -B..16 + B {let wy = base_y + y;for z in -B..16 + B {- for x in -B..16 + B {- let chunk = region[((z + 16) >> 4) as usize][((x + 16) >> 4) as usize];- let i = pi(x, y, z);- if let Some(c) = chunk {- blocks[i] =- if (0..16).contains(&x) && (0..16).contains(&y) && (0..16).contains(&z)- {- own[(y << 8 | z << 4 | x) as usize]- } else {- c.get(x & 15, wy, z & 15)- };- light[i] = c.light(x & 15, wy, z & 15);- } else if let Some(c) = region[1][1] {- // A neighbour not loaded continues this chunk's edge- // column. As lit air, the outermost chunks' water drew- // a wall toward it (fluids show both sides), a light- // sheet in the water where far terrain carries on.- // Vanilla draws no chunk without its neighbours.- let (ex, ez) = (x.clamp(0, 15), z.clamp(0, 15));- blocks[i] = c.get(ex, wy, ez);- light[i] = c.light(ex, wy, ez);+ let row = pi(-B, y, z);+ let rz = ((z + 16) >> 4) as usize;+ for (rx, x0, x1) in RUNS {+ let (start, end) = (row + (x0 + B) as usize, row + (x1 + B) as usize);+ let (blocks, light) = (&mut blocks[start..end], &mut light[start..end]);+ let Some(c) = region[rz][rx] else {+ match region[1][1] {+ // A neighbour not loaded continues this chunk's edge+ // column. As lit air, the outermost chunks' water drew+ // a wall toward it (fluids show both sides), a light+ // sheet in the water where far terrain carries on.+ // Vanilla draws no chunk without its neighbours.+ Some(c) => {+ let ez = z.clamp(0, 15);+ for (k, x) in (x0..x1).enumerate() {+ let ex = x.clamp(0, 15);+ blocks[k] = c.get(ex, wy, ez);+ light[k] = c.light(ex, wy, ez);+ }+ }+ None => {+ blocks.fill(0);+ light.fill(0xF0);+ }+ }+ continue;+ };+ // `Chunk::get` and `Chunk::light` with the section found once.+ let s = (wy - c.min_y()) >> 4;+ let Some(section) = c.sections.get(s as usize).filter(|_| s >= 0) else {+ blocks.fill(0);+ light.fill(if s < 0 { 0 } else { 0xF0 });+ continue;+ };+ let at = crate::chunk::index(x0, wy, z);+ if rx == 1 && rz == 1 && (0..16).contains(&y) {+ let own_row = (y << 8 | z << 4) as usize;+ blocks.copy_from_slice(&own[own_row..own_row + 16]);} else {- light[i] = 0xF0;+ section.blocks.get_run(at, blocks);+ }+ match §ion.light {+ Light::Uniform(v) => light.fill(*v),+ Light::Full(all) => light.copy_from_slice(&all[at..at + light.len()]),}}}@@ -894,6 +922,28 @@ pub struct MeshScratch {own: Option<Box<[u32; 4096]>>,visibility: Vec<usize>,leaf: leaf_culling::LeafMask,+ /// Per padded row (`pi(-B, y, z) / P`), bit `x + B` set where the block+ /// is `isSolidRender`.+ opaque: Vec<u32>,+}+/// Fills `rows` with the padded section's opacity, one bit per block (`MeshScratch::opaque`).+fn opaque_rows(pad: &Padded, solid: &[bool], rows: &mut Vec<u32>) {+ rows.clear();+ rows.extend(pad.blocks.chunks_exact(P).map(|row| {+ row.iter().enumerate().fold(0u32, |bits, (x, &id)| {+ bits | u32::from(solid[id as usize]) << x+ })+ }));+}+/// Whether the block at `(x, y, z)` (section-local) and its six neighbours+/// are all `isSolidRender`: none of its faces can show.+#[inline]+fn hidden(rows: &[u32], x: i32, y: i32, z: i32) -> bool {+ let row = |y: i32, z: i32| rows[((y + B) as usize) * P + (z + B) as usize];+ let r = row(y, z);+ let around =+ r & r << 1 & r >> 1 & row(y - 1, z) & row(y + 1, z) & row(y, z - 1) & row(y, z + 1);+ around >> (x + B) & 1 != 0}#[cfg(test)]mod leaf_culling_tests;@@ -990,6 +1040,12 @@ enum Resolver {/// layer plus the blend radius around it, and the blended colours per column.struct Layer {zoomed: Vec<u16>,+ /// Each resolver's colour of every cell of `zoomed`, filled on first use:+ /// a cell is in the blend square of up to `(2r+1)^2` columns.+ cells: [Vec<u32>; 4],+ /// `BiomeZoom::corner_jitter` of the quart cells `zoomed` reaches, by+ /// their offset from the first: each is shared by up to 16 cells of the layer.+ jitter: Vec<Option<[[f64; 3]; 8]>>,colors: [[u32; 256]; 4],}/// `ClientLevel.calculateBlockTint` behind a per-layer `BlockTintCache`: each@@ -1041,6 +1097,16 @@ impl<'a> Tints<'a> {[x, y, z]: [i32; 3],) -> u16 {let q = zoom.quart_at_block(BlockPos::new(cx * 16 + x, base_y + y, cz * 16 + z));+ Self::quart_biome(region, plains, [cx, cz], q)+ }+ /// The biome of quart cell `q` in the loaded chunks around chunk `(cx, cz)`, plains where+ /// there is none.+ fn quart_biome(+ region: &[[Option<&Chunk>; 3]; 3],+ plains: u16,+ [cx, cz]: [i32; 2],+ q: [i32; 3],+ ) -> u16 {let (rx, rz) = ((q[0] >> 2) - cx + 1, (q[2] >> 2) - cz + 1);if (0..3).contains(&rx) && (0..3).contains(&rz) {region[rz as usize][rx as usize].map_or(plains, |c| {@@ -1057,6 +1123,8 @@ impl<'a> Tints<'a> {let layer = self.layers[y as usize].get_or_insert_with(|| {Box::new(Layer {zoomed: vec![NO_BIOME; dim * dim],+ cells: Default::default(),+ jitter: Vec::new(),colors: [[UNSET; 256]; 4],})});@@ -1065,21 +1133,45 @@ impl<'a> Tints<'a> {if cached != UNSET {return cached;}- let [cx, cz, _] = self.origin;- let (bx, bz) = (cx * 16, cz * 16);+ let [cx, cz, base_y] = self.origin;+ let (bx, by, bz) = (cx * 16, base_y + y, cz * 16);let (mut red, mut green, mut blue) = (0, 0, 0);+ let cells = &mut layer.cells[resolver as usize];+ if cells.is_empty() {+ cells.resize(dim * dim, UNSET);+ }for dz in -r..=r {for dx in -r..=r {let cell = ((z + dz + r) as usize) * dim + (x + dx + r) as usize;+ let known = cells[cell];+ if known != UNSET {+ red += known >> 16 & 255;+ green += known >> 8 & 255;+ blue += known & 255;+ continue;+ }let mut biome = layer.zoomed[cell];if biome == NO_BIOME {- biome = Self::biome_id(- &self.zoom,- self.region,- self.plains,- self.origin,- [x + dx, y, z + dz],- );+ // BiomeManager.getBiome over the loaded chunks (plains+ // where there is none): `quart_at_block`, its cell's+ // corner jitter mixed once per layer.+ let block = BlockPos::new(bx + x + dx, by, bz + z + dz);+ let base = [block.x, block.y, block.z].map(|v| v.wrapping_sub(2) >> 2);+ let first = [bx - r, bz - r].map(|v| v.wrapping_sub(2) >> 2);+ let span = dim / 4 + 2;+ let at = (base[2] - first[1]) as usize * span + (base[0] - first[0]) as usize;+ if layer.jitter.is_empty() {+ layer.jitter.resize(span * span, None);+ }+ let jitter =+ layer.jitter[at].get_or_insert_with(|| self.zoom.corner_jitter(base));+ let corner = BiomeZoom::select_corner(block, jitter);+ let q = [+ base[0].wrapping_add((corner >> 2 & 1) as i32),+ base[1].wrapping_add((corner >> 1 & 1) as i32),+ base[2].wrapping_add((corner & 1) as i32),+ ];+ biome = Self::quart_biome(self.region, self.plains, [cx, cz], q);layer.zoomed[cell] = biome;}let c = match resolver {@@ -1091,6 +1183,7 @@ impl<'a> Tints<'a> {Resolver::Dry => self.biomes.get(biome).dry_foliage,Resolver::Water => self.biomes.get(biome).water,};+ cells[cell] = c;red += c >> 16 & 255;green += c >> 8 & 255;blue += c & 255;@@ -1163,6 +1256,8 @@ impl Mesher<'_> {scratch.padded.fill(region, sy, own);let pad = &scratch.padded;out.visibility = visibility_reusing(pad, &self.tables.info, &mut scratch.visibility);+ opaque_rows(pad, &self.tables.solid, &mut scratch.opaque);+ let opaque = &scratch.opaque;let base_y = center.min_y() + sy * 16;if self.leaf_culling.is_interior() {scratch@@ -1195,12 +1290,7 @@ impl Mesher<'_> {out.lights.push(([center.x * 16 + x, base_y + y, center.z * 16 + z], id));}- if state.solid- && Direction::ALL.iter().all(|d| {- let [dx, dy, dz] = d.normal();- info[pad.blocks[pi(x + dx, y + dy, z + dz)] as usize].solid- })- {+ if hidden(opaque, x, y, z) {continue;}if state.fluid.kind() != FluidKind::Empty {diff --git a/crates/horizon-client-render/src/mesher/sides.rs b/crates/horizon-client-render/src/mesher/sides.rsindex d7a5fbc43..2b22aab8f 100644--- a/crates/horizon-client-render/src/mesher/sides.rs+++ b/crates/horizon-client-render/src/mesher/sides.rs@@ -210,6 +210,29 @@ pub fn sort(solid: &mut Vec<TerrainVertex>) -> Sides {/// `sort`, with all the opaque parts first when `grouped`.fn sort_parts(solid: &mut Vec<TerrainVertex>, grouped: bool) -> Sides {+ SORT_SCRATCH.with_borrow_mut(|scratch| sort_with(solid, grouped, scratch))+}++/// `sort`'s buffers, kept by each meshing thread: a section's quads went+/// through fresh vectors, and the sorted copy replaced the mesh's own+/// (recycled) buffer.+#[derive(Default)]+struct SortScratch {+ slots: Vec<u8>,+ keys: Vec<u64>,+ sorted: Vec<[TerrainVertex; 4]>,+}+thread_local! {+ static SORT_SCRATCH: std::cell::RefCell<SortScratch> = Default::default();+}++/// `f32::total_cmp`'s order as an unsigned integer's.+fn total_order_key(v: f32) -> u32 {+ let bits = v.to_bits() as i32;+ (bits ^ (((bits >> 31) as u32) >> 1) as i32) as u32 ^ 0x8000_0000+}++fn sort_with(solid: &mut Vec<TerrainVertex>, grouped: bool, scratch: &mut SortScratch) -> Sides {let (quads, rest) = solid.as_chunks::<4>();debug_assert!(rest.is_empty(), "solid vertices come in quads");let cutout = |q: &[TerrainVertex; 4]| q[0].layer & OPAQUE_LAYER == 0;@@ -218,15 +241,14 @@ fn sort_parts(solid: &mut Vec<TerrainVertex>, grouped: bool) -> Sides {true => b + 7 * usize::from(cutout),false => b * 2 + usize::from(cutout),};- let slots: Vec<u8> = quads- .iter()- .map(|q| position(bucket(q), cutout(q)) as u8)- .collect();+ let slots = &mut scratch.slots;+ slots.clear();+ slots.extend(quads.iter().map(|q| position(bucket(q), cutout(q)) as u8));let has_cutout = quads.iter().any(cutout);let mut counts = [0u32; 7];let mut slot_counts = [0u32; 14];let mut planes = [0f32; 7];- for (quad, &part) in quads.iter().zip(&slots) {+ for (quad, &part) in quads.iter().zip(slots.iter()) {slot_counts[usize::from(part)] += 1;let b = slot(grouped, usize::from(part)).0;if let Bucket::Side(axis, positive) = BUCKETS[b] {@@ -246,33 +268,34 @@ fn sort_parts(solid: &mut Vec<TerrainVertex>, grouped: bool) -> Sides {*end = total;}if has_cutout || counts.iter().filter(|&&c| c > 0).count() > 1 {- let mut next: [u32; 14] = std::array::from_fn(|s| slot_ends[s] - slot_counts[s]);- let mut sorted = vec![quads[0]; quads.len()];- for (quad, &part) in quads.iter().zip(&slots) {- let at = &mut next[usize::from(part)];- sorted[*at as usize] = *quad;- *at += 1;- }- if has_cutout {- let mut start = 0;- for (s, &end) in slot_ends.iter().enumerate() {- let end = end as usize;- let slice = &mut sorted[start..end];- if let Bucket::Side(axis, positive) = BUCKETS[slot(grouped, s).0] {- slice.sort_by(|a, b| {- let a = a[0].pos[axis];- let b = b[0].pos[axis];- if positive {- b.total_cmp(&a)- } else {- a.total_cmp(&b)+ // One integer key per quad: its part, then (cutout meshes, side+ // buckets) its plane from the outside in, then its index, which keeps+ // the order of equal quads as a stable sort does.+ let keys = &mut scratch.keys;+ keys.clear();+ keys.extend(+ quads+ .iter()+ .zip(slots.iter())+ .enumerate()+ .map(|(i, (quad, &part))| {+ let plane = match BUCKETS[slot(grouped, usize::from(part)).0] {+ Bucket::Side(axis, positive) if has_cutout => {+ let key = total_order_key(quad[0].pos[axis]);+ if positive { !key } else { key }}- });- }- start = end;- }- }- *solid = sorted.into_flattened();+ _ => 0,+ };+ u64::from(part) << 56 | u64::from(plane) << 24 | i as u64+ }),+ );+ debug_assert!(quads.len() < 1 << 24);+ keys.sort_unstable();+ let sorted = &mut scratch.sorted;+ sorted.clear();+ sorted.extend(keys.iter().map(|&k| quads[(k & 0xFF_FFFF) as usize]));+ solid.clear();+ solid.extend_from_slice(sorted.as_flattened());}Sides {ends: slot_ends,@@ -286,6 +309,74 @@ fn sort_parts(solid: &mut Vec<TerrainVertex>, grouped: bool) -> Sides {mod tests {use super::*;+ /// The sort as it was before the integer keys: quads moved to their+ /// parts in order, then a stable sort by plane in each side bucket.+ fn reference(solid: &[TerrainVertex], grouped: bool) -> Vec<TerrainVertex> {+ let quads = solid.as_chunks::<4>().0;+ let has_cutout = quads.iter().any(|q| q[0].layer & OPAQUE_LAYER == 0);+ let mut sorted = Vec::new();+ for n in 0..14 {+ let (b, cutout) = slot(grouped, n);+ let mut part: Vec<[TerrainVertex; 4]> = quads+ .iter()+ .filter(|q| bucket(q) == b && (q[0].layer & OPAQUE_LAYER == 0) == cutout)+ .copied()+ .collect();+ if let (Bucket::Side(axis, positive), true) = (BUCKETS[b], has_cutout) {+ part.sort_by(|a, b| {+ let (a, b) = (a[0].pos[axis], b[0].pos[axis]);+ if positive {+ b.total_cmp(&a)+ } else {+ a.total_cmp(&b)+ }+ });+ }+ sorted.extend(part);+ }+ sorted.into_flattened()+ }++ #[test]+ fn integer_keys_sort_as_the_stable_sort_did() {+ let mut state = 0x2545_F491_4F6C_DD1Du64;+ let mut next = move || {+ state ^= state << 13;+ state ^= state >> 7;+ state ^= state << 17;+ state+ };+ for round in 0..100 {+ let grouped = round % 2 == 1;+ let mut solid = Vec::new();+ for _ in 0..(next() % 300) {+ let origin = [0, 1, 2].map(|_| (next() % 34) as f32 / 2.0 - 0.5);+ // Some negative and signed-zero planes too.+ let origin = if next() % 9 == 0 {+ origin.map(|v| -v)+ } else {+ origin+ };+ let layer = if round % 3 == 0 {+ OPAQUE_LAYER+ } else {+ (next() % 2) as u16 * OPAQUE_LAYER+ };+ let faces = cube(origin, layer);+ let face = (next() % 6) as usize;+ solid.extend_from_slice(&faces[face * 4..face * 4 + 4]);+ }+ let expected = reference(&solid, grouped);+ let sides = sort_parts(&mut solid, grouped);+ assert_eq!(+ bytemuck::cast_slice::<_, u8>(&solid),+ bytemuck::cast_slice::<_, u8>(&expected),+ "round {round}"+ );+ assert_eq!(sides.quads() as usize * 4, solid.len());+ }+ }+fn quad(corners: [[f32; 3]; 4], layer: u16) -> [TerrainVertex; 4] {corners.map(|p| TerrainVertex::new(p, [0.0; 2], layer, 0, 0))}diff --git a/crates/horizon-core/src/paletted.rs b/crates/horizon-core/src/paletted.rsindex 269798bb2..1ffc3c2c6 100644--- a/crates/horizon-core/src/paletted.rs+++ b/crates/horizon-core/src/paletted.rs@@ -272,6 +272,23 @@ impl PalettedContainer {Palette::Global => self.raw(i) as u32,}}+ /// `get` of the entries `start..start + out.len()`, the palette matched once.+ #[inline]+ pub fn get_run(&self, start: usize, out: &mut [u32]) {+ match &self.palette {+ Palette::Single(value) => out.fill(*value),+ Palette::List(list) => {+ for (k, cell) in out.iter_mut().enumerate() {+ *cell = list[self.raw(start + k)];+ }+ }+ Palette::Global => {+ for (k, cell) in out.iter_mut().enumerate() {+ *cell = self.raw(start + k) as u32;+ }+ }+ }+ }/// The value when every entry is equal, without the palette having to be/// minimal.pub fn uniform(&self) -> Option<u32> {@@ -736,6 +753,26 @@ mod tests {*state}#[test]+ fn runs_read_what_get_reads() {+ let mut state = 0x9E37_79B9_7F4A_7C15;+ // One value, a list palette, and the global palette.+ for distinct in [1u64, 5, 3000] {+ let values: Vec<u32> = (0..4096)+ .map(|_| (rng(&mut state) % distinct) as u32)+ .collect();+ let container = PalettedContainer::from_values(BLOCKS, &values);+ for _ in 0..200 {+ let start = (rng(&mut state) % 4096) as usize;+ let len = (rng(&mut state) % 20) as usize;+ let len = len.min(4096 - start);+ let mut run = vec![u32::MAX; len];+ container.get_run(start, &mut run);+ let expected: Vec<u32> = (start..start + len).map(|i| container.get(i)).collect();+ assert_eq!(run, expected, "{distinct} values, {start}+{len}");+ }+ }+ }+ #[test]fn containers_stored_alike_are_the_same() {let values: Vec<u32> = (0..4096).map(|i| (i % 7) as u32).collect();let a = PalettedContainer::from_values(BLOCKS, &values);