From 85e43462ac55f8ecadc8cd4cb9f5244799ce4c9c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 00:37:51 +0200 Subject: [PATCH] Block entity order as vanilla's chunk map iterates; chunk comparison without light values Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/lan/chunks.rs | 55 +++++++++++++++---- .../parity/VanillaProtocolClient.java | 43 ++++++++++++--- 2 files changed, 78 insertions(+), 20 deletions(-) diff --git a/crates/horizon-client/src/lan/chunks.rs b/crates/horizon-client/src/lan/chunks.rs index f178ecfe1..c7295b4ec 100644 --- a/crates/horizon-client/src/lan/chunks.rs +++ b/crates/horizon-client/src/lan/chunks.rs @@ -284,20 +284,53 @@ impl ChunkEncoder { } } -/// The iteration order of a java.util.HashMap keyed by BlockPos (LevelChunk's -/// block entities) filled in the given order: by bucket at the capacity the -/// map grew to, insertion order within a bucket (resizes keep it). -fn java_hash_order(items: &mut [T], pos: impl Fn(&T) -> (i32, i32, i32)) { +/// The order LevelChunk.getBlockEntities() iterates in: a fastutil +/// Object2ObjectOpenHashMap keyed by BlockPos (linear probing from +/// HashCommon.mix(hashCode), grown at 3/4 by reinserting from the top of +/// the table, iterated from the top down), filled in the order of the +/// java.util.HashMap of pending block entities that the loaded chunk's list +/// (`items` in section order) went through. +fn java_hash_order(items: &mut Vec, pos: impl Fn(&T) -> (i32, i32, i32)) { + // Vec3i.hashCode. + let hash = |&(x, y, z): &(i32, i32, i32)| y.wrapping_add(z.wrapping_mul(31)).wrapping_mul(31).wrapping_add(x); + let keys: Vec = items.iter().map(|i| hash(&pos(i))).collect(); + // java.util.HashMap: buckets in index order, insertion order within one. let mut capacity = 16usize; - while items.len() * 4 > capacity * 3 { + while keys.len() * 4 > capacity * 3 { capacity *= 2; } - items.sort_by_key(|item| { - let (x, y, z) = pos(item); - // Vec3i.hashCode, then HashMap.hash. - let h = y.wrapping_add(z.wrapping_mul(31)).wrapping_mul(31).wrapping_add(x); - ((h ^ ((h as u32) >> 16) as i32) as u32 as usize) & (capacity - 1) - }); + let mut order: Vec = (0..keys.len()).collect(); + order.sort_by_key(|&i| ((keys[i] ^ ((keys[i] as u32) >> 16) as i32) as u32 as usize) & (capacity - 1)); + // Object2ObjectOpenHashMap. + let mix = |h: i32| { + let h = h.wrapping_mul(0x9E37_79B9_u32 as i32) as u32; + (h ^ (h >> 16)) as usize + }; + let put = |table: &mut Vec>, i: usize| { + let mask = table.len() - 1; + let mut at = mix(keys[i]) & mask; + while table[at].is_some() { + at = (at + 1) & mask; + } + table[at] = Some(i); + }; + // Default expected size 16: HashCommon.arraySize(16, 0.75) = 32 slots. + let mut table: Vec> = vec![None; 32]; + for (size, &i) in order.iter().enumerate() { + put(&mut table, i); + // insert: `if (size++ >= maxFill) rehash(arraySize(size + 1, f))`. + let max_fill = (table.len() * 3).div_ceil(4).min(table.len() - 1); + if size >= max_fill { + let grown = ((size + 2) * 4).div_ceil(3).next_power_of_two().max(2); + let old = std::mem::replace(&mut table, vec![None; grown]); + for &j in old.iter().rev().flatten() { + put(&mut table, j); + } + } + } + let iteration: Vec = table.iter().rev().flatten().copied().collect(); + let mut slots: Vec> = items.drain(..).map(Some).collect(); + items.extend(iteration.into_iter().filter_map(|i| slots[i].take())); } /// The update tag of a block entity (getUpdateTag) for what the client shows. diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java index 1785bfdcd..28696ab9b 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java @@ -55,6 +55,7 @@ import net.minecraft.network.protocol.configuration.ServerboundFinishConfigurati import net.minecraft.network.protocol.configuration.ServerboundSelectKnownPacks; import net.minecraft.network.protocol.game.ClientboundChunkBatchFinishedPacket; import net.minecraft.network.protocol.game.ClientboundDisguisedChatPacket; +import net.minecraft.network.protocol.game.ClientboundLevelChunkPacketData; import net.minecraft.network.protocol.game.ClientboundLevelChunkWithLightPacket; import net.minecraft.network.protocol.game.ClientboundPlayerChatPacket; import net.minecraft.network.protocol.game.ClientboundPlayerPositionPacket; @@ -357,6 +358,19 @@ public final class VanillaProtocolClient { send(new ServerboundPongPacket(p.getId())); } else if (r.packet instanceof ClientboundCustomPayloadPacket p) { record("config", r.type + " " + text(p.payload())); + } else if (r.packet instanceof net.minecraft.network.protocol.common.ClientboundUpdateTagsPacket p) { + record("config", r.type + " sha=" + sha(r.payload)); + // Each registry's tags: what they hold, then the order sent. + for (var e : p.tags().entrySet()) { + var tags = new TreeMap(); + StringBuilder order = new StringBuilder(); + for (var t : e.getValue().tags().entrySet()) { + tags.put(t.getKey().toString(), t.getValue().toString()); + order.append(t.getKey()).append(';'); + } + record("config-tags", e.getKey().identifier() + " " + tags.size() + " content=" + sha(tags.toString().getBytes()) + + " order=" + sha(order.toString().getBytes())); + } } else if (r.packet instanceof ClientboundFinishConfigurationPacket) { record("config", r.type); send(ServerboundFinishConfigurationPacket.INSTANCE); @@ -425,7 +439,7 @@ public final class VanillaProtocolClient { } else if (packet instanceof ClientboundChunkBatchFinishedPacket) { send(new ServerboundChunkBatchReceivedPacket(64.0F)); } else if (packet instanceof ClientboundLevelChunkWithLightPacket p) { - chunks.put(p.x() + "," + p.z(), sha(r.payload)); + chunks.put(p.x() + "," + p.z(), chunkHash(p)); lastChunk = now; int px = (int) Math.floor(position.position().x) >> 4; int pz = (int) Math.floor(position.position().z) >> 4; @@ -466,6 +480,25 @@ public final class VanillaProtocolClient { record("error", "timed out in play, step " + step + ", chunks " + chunks.size()); } + /** + * A chunk's blocks, biomes, heightmaps and block entities (its + * ClientboundLevelChunkPacketData bytes) and which light layers it has. + * The light values are left out: both servers relight around chunks + * loaded with their saved light, which test_light_parity covers. + */ + private static String chunkHash(ClientboundLevelChunkWithLightPacket p) { + RegistryFriendlyByteBuf buf = new RegistryFriendlyByteBuf(Unpooled.buffer(), ParityData.access); + ClientboundLevelChunkPacketData.STREAM_CODEC.encode(buf, p.chunkData()); + byte[] bytes = new byte[buf.readableBytes()]; + buf.readBytes(bytes); + var light = p.lightData(); + BitSet sky = (BitSet) light.skyYMask().clone(); + sky.or(light.emptySkyYMask()); + BitSet block = (BitSet) light.blockYMask().clone(); + block.or(light.emptyBlockYMask()); + return sha(bytes) + "/" + sky + "/" + block; + } + /** The player's chunk part by part, so a difference in its bytes can be told apart. */ private void chunkParts(ClientboundLevelChunkWithLightPacket p) { var data = p.chunkData(); @@ -499,14 +532,6 @@ public final class VanillaProtocolClient { data.forEachBlockEntityTag(p.x(), p.z(), (pos, type, tag) -> entities.append(pos.toShortString()).append(' ') .append(net.minecraft.core.registries.BuiltInRegistries.BLOCK_ENTITY_TYPE.getKey(type)).append(' ').append(tag).append(';')); record("chunk-block-entities", entities.toString()); - var light = p.lightData(); - record("chunk-light-masks", light.skyYMask() + " " + light.blockYMask() + " " + light.emptySkyYMask() + " " + light.emptyBlockYMask()); - StringBuilder sky = new StringBuilder(); - for (byte[] b : light.skyUpdates()) sky.append(sha(b)).append(' '); - record("chunk-light-sky", sky.toString()); - StringBuilder block = new StringBuilder(); - for (byte[] b : light.blockUpdates()) block.append(sha(b)).append(' '); - record("chunk-light-block", block.toString()); } /** The first play packets: entity ids, seeds and times aside. */