Skip to content

Optimise WorldStatisticsProvider regionising #506

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 8, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,16 @@
package me.lucko.spark.common.platform.world;

import me.lucko.spark.proto.SparkProtos.WorldStatistics;
import org.jetbrains.annotations.VisibleForTesting;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

Expand Down Expand Up @@ -122,37 +125,57 @@ private static <E> WorldStatistics.Chunk chunkToProto(ChunkInfo<E> chunk, CountM
return builder.build();
}

private static List<Region> groupIntoRegions(List<? extends ChunkInfo<?>> chunks) {
@VisibleForTesting
static List<Region> groupIntoRegions(List<? extends ChunkInfo<?>> chunks) {
List<Region> regions = new ArrayList<>();

LinkedHashMap<ChunkCoordinate, ChunkInfo<?>> chunkMap = new LinkedHashMap<>(chunks.size());

for (ChunkInfo<?> chunk : chunks) {
CountMap<?> counts = chunk.getEntityCounts();
if (counts.total().get() == 0) {
continue;
}
chunkMap.put(new ChunkCoordinate(chunk.getX(), chunk.getZ()), chunk);
}

boolean found = false;
ArrayDeque<ChunkInfo<?>> queue = new ArrayDeque<>();
ChunkCoordinate index = new ChunkCoordinate(); // avoid allocating per check

for (Region region : regions) {
if (region.isAdjacent(chunk)) {
found = true;
region.add(chunk);

// if the chunk is adjacent to more than one region, merge the regions together
for (Iterator<Region> iterator = regions.iterator(); iterator.hasNext(); ) {
Region otherRegion = iterator.next();
if (region != otherRegion && otherRegion.isAdjacent(chunk)) {
iterator.remove();
region.merge(otherRegion);
while (!chunkMap.isEmpty()) {
Map.Entry<ChunkCoordinate, ChunkInfo<?>> first = chunkMap.entrySet().iterator().next();
ChunkInfo<?> firstValue = first.getValue();

chunkMap.remove(first.getKey());

Region region = new Region(firstValue);
regions.add(region);

queue.add(firstValue);

ChunkInfo<?> queued;
while ((queued = queue.pollFirst()) != null) {
int queuedX = queued.getX();
int queuedZ = queued.getZ();

// merge adjacent chunks
for (int dz = -1; dz <= 1; ++dz) {
for (int dx = -1; dx <= 1; ++dx) {
if ((dx | dz) == 0) {
continue;
}
}

break;
}
}
index.setCoordinate(queuedX + dx, queuedZ + dz);
ChunkInfo<?> adjacent = chunkMap.remove(index);

if (adjacent == null) {
continue;
}

if (!found) {
regions.add(new Region(chunk));
region.add(adjacent);
queue.add(adjacent);
}
}
}
}

Expand All @@ -162,8 +185,7 @@ private static List<Region> groupIntoRegions(List<? extends ChunkInfo<?>> chunks
/**
* A map of nearby chunks grouped together by Euclidean distance.
*/
private static final class Region {
private static final int DISTANCE_THRESHOLD = 2;
static final class Region {
private final Set<ChunkInfo<?>> chunks;
private final AtomicInteger totalEntities;

Expand All @@ -181,30 +203,53 @@ public AtomicInteger getTotalEntities() {
return this.totalEntities;
}

public boolean isAdjacent(ChunkInfo<?> chunk) {
for (ChunkInfo<?> el : this.chunks) {
if (squaredEuclideanDistance(el, chunk) <= DISTANCE_THRESHOLD) {
return true;
}
}
return false;
}

public void add(ChunkInfo<?> chunk) {
this.chunks.add(chunk);
this.totalEntities.addAndGet(chunk.getEntityCounts().total().get());
}
}

static final class ChunkCoordinate implements Comparable<ChunkCoordinate> {
long key;

ChunkCoordinate() {}

public void merge(Region group) {
this.chunks.addAll(group.getChunks());
this.totalEntities.addAndGet(group.getTotalEntities().get());
ChunkCoordinate(int chunkX, int chunkZ) {
this.setCoordinate(chunkX, chunkZ);
}

private static long squaredEuclideanDistance(ChunkInfo<?> a, ChunkInfo<?> b) {
long dx = a.getX() - b.getX();
long dz = a.getZ() - b.getZ();
return (dx * dx) + (dz * dz);
ChunkCoordinate(long key) {
this.setKey(key);
}

public void setCoordinate(int chunkX, int chunkZ) {
this.setKey(((long) chunkZ << 32) | (chunkX & 0xFFFFFFFFL));
}
}

public void setKey(long key) {
this.key = key;
}

@Override
public int hashCode() {
// fastutil hash without the last step, as it is done by HashMap
// doing the last step twice (h ^= (h >>> 16)) is both more expensive and destroys the hash
long h = this.key * 0x9E3779B97F4A7C15L;
h ^= h >>> 32;
return (int) h;
}

@Override
public boolean equals(Object obj) {
if (!(obj instanceof ChunkCoordinate)) {
return false;
}
return this.key == ((ChunkCoordinate) obj).key;
}

@Override
public int compareTo(ChunkCoordinate other) {
return Long.compare(this.key, other.key);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
/*
* This file is part of spark.
*
* Copyright (c) lucko (Luck) <[email protected]>
* Copyright (c) contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

package me.lucko.spark.common.platform.world;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.List;
import java.util.Set;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class WorldStatisticsProviderTest {

@Test
public void testGroupIntoRegionsEmpty() {
List<WorldStatisticsProvider.Region> regions = WorldStatisticsProvider.groupIntoRegions(ImmutableList.of());
assertEquals(0, regions.size());
}

@Test
public void testGroupIntoRegionsSingle() {
TestChunkInfo chunk1 = new TestChunkInfo(0, 0);
List<WorldStatisticsProvider.Region> regions = WorldStatisticsProvider.groupIntoRegions(ImmutableList.of(chunk1));

assertEquals(1, regions.size());
WorldStatisticsProvider.Region region = regions.get(0);

Set<ChunkInfo<?>> chunks = region.getChunks();
assertEquals(1, chunks.size());
assertEquals(ImmutableSet.of(chunk1), chunks);
}

@Test
public void testGroupIntoRegionsMultiple() {
TestChunkInfo chunk1 = new TestChunkInfo(0, 0);
TestChunkInfo chunk2 = new TestChunkInfo(0, 1);
TestChunkInfo chunk3 = new TestChunkInfo(1, 0);
TestChunkInfo chunk4 = new TestChunkInfo(0, 2);

List<WorldStatisticsProvider.Region> regions = WorldStatisticsProvider.groupIntoRegions(ImmutableList.of(chunk1, chunk2, chunk3, chunk4));

assertEquals(1, regions.size());

WorldStatisticsProvider.Region region = regions.get(0);
Set<ChunkInfo<?>> chunks = region.getChunks();
assertEquals(4, chunks.size());
assertEquals(ImmutableSet.of(chunk1, chunk2, chunk3, chunk4), chunks);
}

@Test
public void testGroupIntoRegionsMultipleRegions() {
TestChunkInfo chunk1 = new TestChunkInfo(0, 0);
TestChunkInfo chunk2 = new TestChunkInfo(0, 1);
TestChunkInfo chunk3 = new TestChunkInfo(1, 0);
TestChunkInfo chunk4 = new TestChunkInfo(2, 2);

List<WorldStatisticsProvider.Region> regions = WorldStatisticsProvider.groupIntoRegions(ImmutableList.of(chunk1, chunk2, chunk3, chunk4));

assertEquals(2, regions.size());

WorldStatisticsProvider.Region region1 = regions.get(0);
Set<ChunkInfo<?>> chunks1 = region1.getChunks();
assertEquals(3, chunks1.size());
assertEquals(ImmutableSet.of(chunk1, chunk2, chunk3), chunks1);

WorldStatisticsProvider.Region region2 = regions.get(1);
Set<ChunkInfo<?>> chunks2 = region2.getChunks();
assertEquals(1, chunks2.size());
assertEquals(ImmutableSet.of(chunk4), chunks2);
}

private static final class TestChunkInfo implements ChunkInfo<String> {
private final int x;
private final int z;
private final CountMap<String> entityCounts;

public TestChunkInfo(int x, int z) {
this.x = x;
this.z = z;
this.entityCounts = new CountMap.Simple<>(new HashMap<>());
this.entityCounts.increment("test");
}

@Override
public int getX() {
return this.x;
}

@Override
public int getZ() {
return this.z;
}

@Override
public CountMap<String> getEntityCounts() {
return this.entityCounts;
}

@Override
public String entityTypeName(String type) {
return type;
}
}

}