From fe83032a2d9ef2d79683e782fa0f625ceb88157d Mon Sep 17 00:00:00 2001 From: Caedis Date: Sun, 25 May 2025 10:49:54 -0500 Subject: [PATCH] Add Spatial Hash Grid Data Structure (#135) Co-authored-by: ah-OOG-ah <75745146+ah-OOG-ah@users.noreply.github.com> --- .../spatialhashgrid/SpatialHashGrid.java | 159 ++++++++++++++++++ .../spatialhashgrid/SpatialHashGridTest.java | 120 +++++++++++++ .../spatialhashgrid/TestObject.java | 12 ++ 3 files changed, 291 insertions(+) create mode 100644 src/main/java/com/gtnewhorizon/gtnhlib/datastructs/spatialhashgrid/SpatialHashGrid.java create mode 100644 src/test/java/com/gtnewhorizon/gtnhlib/test/datastructs/spatialhashgrid/SpatialHashGridTest.java create mode 100644 src/test/java/com/gtnewhorizon/gtnhlib/test/datastructs/spatialhashgrid/TestObject.java diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/datastructs/spatialhashgrid/SpatialHashGrid.java b/src/main/java/com/gtnewhorizon/gtnhlib/datastructs/spatialhashgrid/SpatialHashGrid.java new file mode 100644 index 00000000..6361a54f --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/datastructs/spatialhashgrid/SpatialHashGrid.java @@ -0,0 +1,159 @@ +package com.gtnewhorizon.gtnhlib.datastructs.spatialhashgrid; + +import java.util.List; +import java.util.function.BiConsumer; + +import org.joml.Vector3i; + +import com.gtnewhorizon.gtnhlib.util.CoordinatePacker; + +import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; + +/** + * 3D Spatial Grid
+ * Objects are hashed using their position + * + * @param object type to store + */ +public class SpatialHashGrid { + + private final int cellSize; + private final BiConsumer positionExtractor; + private final Vector3i scratch = new Vector3i(); + private final Long2ObjectOpenHashMap> grid = new Long2ObjectOpenHashMap<>(); + + public enum DistanceFormula { + SquaredEuclidean, + /** + * Chessboard + */ + Chebyshev, + + /** + * Taxicab + */ + Manhattan + } + + public SpatialHashGrid(int cellSize, BiConsumer positionExtractor) { + if (cellSize <= 0) throw new IllegalArgumentException("cellSize can not be less than or equal to 0"); + this.cellSize = cellSize; + this.positionExtractor = positionExtractor; + } + + private long pack(int x, int y, int z) { + return CoordinatePacker.pack(x, y, z); + } + + private long hash(int x, int y, int z) { + return pack(Math.floorDiv(x, cellSize), Math.floorDiv(y, cellSize), Math.floorDiv(z, cellSize)); + } + + /** + * Insert an object into the grid + */ + public void insert(T obj) { + positionExtractor.accept(scratch, obj); + long key = hash(scratch.x, scratch.y, scratch.z); + ObjectArrayList list = grid.computeIfAbsent(key, k -> new ObjectArrayList<>()); + list.add(obj); + } + + /** + * Remove an object for the grid + */ + public void remove(T obj) { + positionExtractor.accept(scratch, obj); + long key = hash(scratch.x, scratch.y, scratch.z); + ObjectArrayList list = grid.get(key); + if (list == null) return; + + list.remove(obj); + if (!list.isEmpty()) return; + + grid.remove(key); + } + + /** + * Search the grid for nearby objects Default Distance Formula: Squared Euclidean + * + * @param radius distance in blocks to check (sphere) + * @return list of nearby objects + */ + public List findNearby(int x, int y, int z, int radius) { + return findNearby(x, y, z, radius, DistanceFormula.SquaredEuclidean); + } + + /** + * Search the grid for nearby objects + * + * @param radius distance in blocks to check (sphere) + * @param distanceFormula Distance Formula to use + * @return list of nearby objects + */ + public List findNearby(int x, int y, int z, int radius, DistanceFormula distanceFormula) { + radius = Math.abs(radius); // just no + final int cellX = Math.floorDiv(x, cellSize); + final int cellY = Math.floorDiv(y, cellSize); + final int cellZ = Math.floorDiv(z, cellSize); + + // Make sure that cells which partially fall in the radius are still checked + final int cellRad = (radius + cellSize - 1) / cellSize; + final int radiusSquared = radius * radius; + + final ObjectArrayList result = new ObjectArrayList<>(); + + for (int dx = -cellRad; dx <= cellRad; dx++) { + for (int dy = -cellRad; dy <= cellRad; dy++) { + for (int dz = -cellRad; dz <= cellRad; dz++) { + long key = pack(cellX + dx, cellY + dy, cellZ + dz); + final ObjectArrayList list = grid.get(key); + if (list == null || list.isEmpty()) continue; + + boolean isEdge = (Math.abs(dx) == cellRad) || (Math.abs(dy) == cellRad) + || (Math.abs(dz) == cellRad); + + if (isEdge) { + for (T obj : list) { + positionExtractor.accept(scratch, obj); + if (distanceBetweenPoints(x, y, z, scratch.x, scratch.y, scratch.z, distanceFormula) + > radiusSquared) + continue; + + result.add(obj); + } + } else { + result.addAll(list); + } + } + } + } + + return result; + } + + private double distanceBetweenPoints(double x1, double y1, double z1, double x2, double y2, double z2, + DistanceFormula distanceFormula) { + return switch (distanceFormula) { + case SquaredEuclidean -> squaredEuclideanDistance(x1, y1, z1, x2, y2, z2); + case Chebyshev -> chebyshevDistance(x1, y1, z1, x2, y2, z2); + case Manhattan -> manhattanDistance(x1, y1, z1, x2, y2, z2); + }; + } + + private double squaredEuclideanDistance(double x1, double y1, double z1, double x2, double y2, double z2) { + double dx = x1 - x2; + double dy = y1 - y2; + double dz = z1 - z2; + return dx * dx + dy * dy + dz * dz; + } + + private double manhattanDistance(double x1, double y1, double z1, double x2, double y2, double z2) { + return Math.abs(x2 - x1) + Math.abs(y2 - y1) + Math.abs(z2 - z1); + } + + private double chebyshevDistance(double x1, double y1, double z1, double x2, double y2, double z2) { + return Math.max(Math.abs(x2 - x1), Math.max(Math.abs(y2 - y1), Math.abs(z2 - z1))); + } +} diff --git a/src/test/java/com/gtnewhorizon/gtnhlib/test/datastructs/spatialhashgrid/SpatialHashGridTest.java b/src/test/java/com/gtnewhorizon/gtnhlib/test/datastructs/spatialhashgrid/SpatialHashGridTest.java new file mode 100644 index 00000000..2053b738 --- /dev/null +++ b/src/test/java/com/gtnewhorizon/gtnhlib/test/datastructs/spatialhashgrid/SpatialHashGridTest.java @@ -0,0 +1,120 @@ +package com.gtnewhorizon.gtnhlib.test.datastructs.spatialhashgrid; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.Collection; + +import org.junit.jupiter.api.Test; + +import com.gtnewhorizon.gtnhlib.datastructs.spatialhashgrid.SpatialHashGrid; + +public class SpatialHashGridTest { + + @Test + void testInsertAndQuery() { + SpatialHashGrid grid = new SpatialHashGrid<>(5, (pos, obj) -> { + pos.x = obj.x; + pos.y = obj.y; + pos.z = obj.z; + }); + + TestObject obj = new TestObject(5, 5, 5); + grid.insert(obj); + + Collection results = grid.findNearby(5, 5, 5, 1); + assertNotNull(results); + assertTrue(results.contains(obj)); + assertEquals(1, results.size()); + } + + @Test + void testMultipleInserts() { + SpatialHashGrid grid = new SpatialHashGrid<>(5, (pos, obj) -> { + pos.x = obj.x; + pos.y = obj.y; + pos.z = obj.z; + }); + + TestObject obj1 = new TestObject(5, 5, 5); + TestObject obj2 = new TestObject(3, 3, 3); + grid.insert(obj1); + grid.insert(obj2); + + Collection results = grid.findNearby(5, 5, 5, 10); + assertNotNull(results); + assertTrue(results.contains(obj1)); + assertTrue(results.contains(obj2)); + assertEquals(2, results.size()); + } + + @Test + void testEmptyGrid() { + SpatialHashGrid grid = new SpatialHashGrid<>(5, (pos, obj) -> { + pos.x = obj.x; + pos.y = obj.y; + pos.z = obj.z; + }); + + Collection results = grid.findNearby(0, 0, 0, 10); + assertNotNull(results); + assertTrue(results.isEmpty()); + } + + @Test + void testNegativeCoordinates() { + SpatialHashGrid grid = new SpatialHashGrid<>(5, (pos, obj) -> { + pos.x = obj.x; + pos.y = obj.y; + pos.z = obj.z; + }); + + TestObject obj = new TestObject(-5, -5, -5); + grid.insert(obj); + + Collection results = grid.findNearby(-5, -5, -5, 1); + assertNotNull(results); + assertTrue(results.contains(obj)); + assertEquals(1, results.size()); + } + + @Test + void testObjectMove() { + SpatialHashGrid grid = new SpatialHashGrid<>(5, (pos, obj) -> { + pos.x = obj.x; + pos.y = obj.y; + pos.z = obj.z; + }); + + TestObject obj = new TestObject(5, 5, 5); + grid.insert(obj); + + grid.remove(obj); + obj.x = 15; + grid.insert(obj); + + Collection results = grid.findNearby(15, 5, 5, 1); + assertNotNull(results); + assertTrue(results.contains(obj)); + assertEquals(1, results.size()); + } + + @Test + void testLargeRadiusQuery() { + SpatialHashGrid grid = new SpatialHashGrid<>(5, (pos, obj) -> { + pos.x = obj.x; + pos.y = obj.y; + pos.z = obj.z; + }); + + TestObject obj1 = new TestObject(5, 5, 5); + TestObject obj2 = new TestObject(10, 10, 10); + grid.insert(obj1); + grid.insert(obj2); + + Collection results = grid.findNearby(5, 5, 5, 10); + assertNotNull(results); + assertTrue(results.contains(obj1)); + assertTrue(results.contains(obj2)); + assertEquals(2, results.size()); + } +} diff --git a/src/test/java/com/gtnewhorizon/gtnhlib/test/datastructs/spatialhashgrid/TestObject.java b/src/test/java/com/gtnewhorizon/gtnhlib/test/datastructs/spatialhashgrid/TestObject.java new file mode 100644 index 00000000..81a1b4f9 --- /dev/null +++ b/src/test/java/com/gtnewhorizon/gtnhlib/test/datastructs/spatialhashgrid/TestObject.java @@ -0,0 +1,12 @@ +package com.gtnewhorizon.gtnhlib.test.datastructs.spatialhashgrid; + +class TestObject { + + public int x, y, z; + + TestObject(int x, int y, int z) { + this.x = x; + this.y = y; + this.z = z; + } +}