add ArrayProximityCheck4D and ArrayProximityMap4D<T> (#157)

This commit is contained in:
Alexdoru authored and GitHub committed 2025-07-05 18:21:27 +02:00
1 parent 417317d8c7
commit d101b003f3
7 files changed
+646 -893

No files matched your search

@@ -3,16 +3,19 @@ package com.gtnewhorizon.gtnhlib.datastructs.space;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import javax.annotation.Nonnull;
/**
* This is a data structure that allows you to quickly check if an arbitrary point in space is contained within at least
* one of the volumes defined.
* This is a data structure that allows you to quickly check if an arbitrary point in space (dim, x, y, z) is contained
* within at least one of the volumes defined.
* <p>
* When adding a volume to an existing position, it won't add a second volume but will instead update the radius of the
* element at that position.
*/
@SuppressWarnings("unused")
public class VolumeMembershipCheck {
public class ArrayProximityCheck4D {
// optimization idea : this can be dynamically
// replaced with a map if the amount of dims gets too big
@@ -20,17 +23,16 @@ public class VolumeMembershipCheck {
private final List<DimensionData> dimList = new ArrayList<>();
private final VolumeShape shape;
public enum VolumeShape {
SPHERE,
CUBE
}
public VolumeMembershipCheck(VolumeShape shape) {
public ArrayProximityCheck4D(@Nonnull VolumeShape shape) {
Objects.requireNonNull(shape);
this.shape = shape;
}
@SuppressWarnings("ForLoopReplaceableByForEach")
private DimensionData getDataForDim(int dim) {
for (DimensionData dimData : dimList) {
final int size = dimList.size();
for (int i = 0; i < size; i++) {
final DimensionData dimData = dimList.get(i);
if (dimData.getDimId() == dim) {
return dimData;
}
@@ -38,7 +40,10 @@ public class VolumeMembershipCheck {
return null;
}
public void putVolume(int dim, int x, int y, int z, int radius) {
public void put(int dim, int x, int y, int z, int radius) {
if (radius < 0) {
throw new IllegalArgumentException("Radius must be strictly positive");
}
DimensionData dimData = getDataForDim(dim);
if (dimData == null) {
dimData = new DimensionData(dim);
@@ -47,7 +52,7 @@ public class VolumeMembershipCheck {
dimData.put(x, y, z, radius);
}
public void removeVolume(int dim, int x, int y, int z) {
public void remove(int dim, int x, int y, int z) {
final DimensionData dimData = getDataForDim(dim);
if (dimData == null) {
return;
@@ -58,22 +63,45 @@ public class VolumeMembershipCheck {
}
}
public boolean isInVolume(int dim, double x, double y, double z) {
public boolean isInRange(int dim, double x, double y, double z) {
final DimensionData dimData = getDataForDim(dim);
if (dimData == null) {
return false;
}
return dimData.isInVolume(x, y, z);
if (shape == VolumeShape.SPHERE) {
return dimData.isInSphere(x, y, z);
} else if (shape == VolumeShape.CUBE) {
return dimData.isInCube(x, y, z);
}
throw new IllegalArgumentException("Invalid shape");
}
private class DimensionData {
@SuppressWarnings("ForLoopReplaceableByForEach")
public int size() {
int size = 0;
final int listSize = dimList.size();
for (int i = 0; i < listSize; i++) {
size += dimList.get(i).size();
}
return size;
}
public boolean isEmpty() {
return dimList.isEmpty();
}
public void clear() {
dimList.clear();
}
private static class DimensionData {
// optimization idea : the data array can be
// dynamically replaced with a different
// data structure if the size gets too big
// implementation note : since we want fast
// isInVolume() checks, when removing volumes,
// isInRange() checks, when removing volumes,
// we move the last element to the removed index
// so that all the "alive data" in the array
// remains at the start
@@ -97,6 +125,10 @@ public class VolumeMembershipCheck {
return dimId;
}
public int size() {
return size;
}
public void put(int x, int y, int z, int radius) {
final int maxIndex = size * 4;
final int[] a = data;
@@ -123,6 +155,9 @@ public class VolumeMembershipCheck {
if (x == a[i] && y == a[i + 1] && z == a[i + 2]) {
int numMoved = maxIndex - i - 4;
if (numMoved > 0) {
// if it's not the last element that got removed,
// move the last element to the removed index
// to keep all data packed at the start of the array
System.arraycopy(data, maxIndex - 4, data, i, 4);
}
size--;
@@ -134,32 +169,35 @@ public class VolumeMembershipCheck {
}
}
public boolean isInVolume(double x, double y, double z) {
public boolean isInSphere(double x, double y, double z) {
final int maxIndex = size * 4;
final int[] a = data;
if (shape == VolumeShape.SPHERE) {
for (int i = 0; i < maxIndex; i += 4) {
final double dx = x - a[i] - 0.5D;
final double dy = y - a[i + 1] - 0.5D;
final double dz = z - a[i + 2] - 0.5D;
final double radius = a[i + 3];
if (dx * dx + dy * dy + dz * dz < radius * radius) {
return true;
}
for (int i = 0; i < maxIndex; i += 4) {
final double dx = x - a[i] - 0.5D;
final double dy = y - a[i + 1] - 0.5D;
final double dz = z - a[i + 2] - 0.5D;
final double radius = a[i + 3];
if (dx * dx + dy * dy + dz * dz < radius * radius) {
return true;
}
} else if (shape == VolumeShape.CUBE) {
for (int i = 0; i < maxIndex; i += 4) {
final double centerX = a[i] + 0.5D;
final double centerY = a[i + 1] + 0.5D;
final double centerZ = a[i + 2] + 0.5D;
final double radius = a[i + 3] + 0.5D;
if (centerX - radius < x && x < centerX + radius
&& centerY - radius < y
&& y < centerY + radius
&& centerZ - radius < z
&& z < centerZ + radius) {
return true;
}
}
return false;
}
public boolean isInCube(double x, double y, double z) {
final int maxIndex = size * 4;
final int[] a = data;
for (int i = 0; i < maxIndex; i += 4) {
final double centerX = a[i] + 0.5D;
final double centerY = a[i + 1] + 0.5D;
final double centerZ = a[i + 2] + 0.5D;
final double radius = a[i + 3] + 0.5D;
if (centerX - radius < x && x < centerX + radius
&& centerY - radius < y
&& y < centerY + radius
&& centerZ - radius < z
&& z < centerZ + radius) {
return true;
}
}
return false;
@@ -0,0 +1,360 @@
package com.gtnewhorizon.gtnhlib.datastructs.space;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import javax.annotation.Nonnull;
/**
* This is a data structure that allows you to quickly check if an arbitrary point in space (dim, x, y, z) is in range
* of at least one of the objects defined. You can also retrieve the closest stored object from that point if any. Or
* perform an action for each object in range.
* <p>
* When adding an object to an existing position, it won't add a second object but will instead replace the element at
* this position and update the radius.
*/
@SuppressWarnings("unused")
public class ArrayProximityMap4D<T> {
// optimization idea : this can be dynamically
// replaced with a map if the amount of dims gets too big
// (I doubt the amount of dimensions will ever be too big)
private final List<DimensionData<T>> dimList = new ArrayList<>();
private final VolumeShape shape;
public ArrayProximityMap4D(@Nonnull VolumeShape shape) {
Objects.requireNonNull(shape);
this.shape = shape;
}
@SuppressWarnings("ForLoopReplaceableByForEach")
private DimensionData<T> getDataForDim(int dim) {
final int size = dimList.size();
for (int i = 0; i < size; i++) {
final DimensionData<T> dimData = dimList.get(i);
if (dimData.getDimId() == dim) {
return dimData;
}
}
return null;
}
public void put(T obj, int dim, int x, int y, int z, int radius) {
if (radius < 0) {
throw new IllegalArgumentException("Radius must be strictly positive");
}
DimensionData<T> dimData = getDataForDim(dim);
if (dimData == null) {
dimData = new DimensionData<>(dim);
dimList.add(dimData);
}
dimData.put(obj, x, y, z, radius);
}
public T remove(int dim, int x, int y, int z) {
final DimensionData<T> dimData = getDataForDim(dim);
if (dimData == null) {
return null;
}
final T obj = dimData.remove(x, y, z);
if (dimData.isEmpty()) {
dimList.remove(dimData);
}
return obj;
}
public boolean isInRange(int dim, double x, double y, double z) {
final DimensionData<T> dimData = getDataForDim(dim);
if (dimData == null) {
return false;
}
if (shape == VolumeShape.SPHERE) {
return dimData.isInSphere(x, y, z);
} else if (shape == VolumeShape.CUBE) {
return dimData.isInCube(x, y, z);
}
throw new IllegalArgumentException("Invalid shape");
}
public T getClosest(int dim, double x, double y, double z) {
final DimensionData<T> dimData = getDataForDim(dim);
if (dimData == null) {
return null;
}
if (shape == VolumeShape.SPHERE) {
return dimData.closestSphere(x, y, z);
} else if (shape == VolumeShape.CUBE) {
return dimData.closestCube(x, y, z);
}
throw new IllegalArgumentException("Invalid shape");
}
public void forEachInRange(int dim, double x, double y, double z, Consumer<T> action) {
final DimensionData<T> dimData = getDataForDim(dim);
if (dimData == null) {
return;
}
if (shape == VolumeShape.SPHERE) {
dimData.forEachInSphere(x, y, z, action);
} else if (shape == VolumeShape.CUBE) {
dimData.forEachInCube(x, y, z, action);
} else {
throw new IllegalArgumentException("Invalid shape");
}
}
@SuppressWarnings("ForLoopReplaceableByForEach")
public int size() {
int size = 0;
final int listSize = dimList.size();
for (int i = 0; i < listSize; i++) {
size += dimList.get(i).size();
}
return size;
}
public boolean isEmpty() {
return dimList.isEmpty();
}
public void clear() {
dimList.clear();
}
private static class DimensionData<T> {
// optimization idea : the data array can be
// dynamically replaced with a different
// data structure if the size gets too big
// implementation note : since we want fast
// isInRange() checks, when removing volumes,
// we move the last element to the removed index
// so that all the "alive data" in the array
// remains at the start
// the data array contains blocks of 4 ints
// 1 = positionX, 2 = positionY, 3 = positionZ, 4 = radius
private final int dimId;
private int[] data;
private Object[] objects;
private int size;
private static final int INITIAL_CAPACITY = 8;
public DimensionData(int dimensionId) {
this.dimId = dimensionId;
this.data = new int[INITIAL_CAPACITY * 4];
this.objects = new Object[INITIAL_CAPACITY];
this.size = 0;
}
public int getDimId() {
return dimId;
}
public int size() {
return size;
}
public void put(T obj, int x, int y, int z, int radius) {
final int maxIndex = size * 4;
final int[] a = data;
for (int i = 0; i < maxIndex; i += 4) {
if (x == a[i] && y == a[i + 1] && z == a[i + 2]) {
a[i + 3] = radius;
objects[i / 4] = obj;
return;
}
}
if (maxIndex == data.length) {
data = Arrays.copyOf(data, data.length * 2);
objects = Arrays.copyOf(objects, objects.length * 2);
}
data[maxIndex] = x;
data[maxIndex + 1] = y;
data[maxIndex + 2] = z;
data[maxIndex + 3] = radius;
objects[size] = obj;
size++;
}
@SuppressWarnings("unchecked")
public T remove(int x, int y, int z) {
final int maxIndex = size * 4;
final int[] a = data;
for (int i = 0; i < maxIndex; i += 4) {
if (x == a[i] && y == a[i + 1] && z == a[i + 2]) {
Object removed = objects[i / 4];
int numMoved = maxIndex - i - 4;
if (numMoved > 0) {
// if it's not the last element that got removed,
// move the last element to the removed index
// to keep all data packed at the start of the array
System.arraycopy(data, maxIndex - 4, data, i, 4);
objects[i / 4] = objects[size];
objects[size] = null;
}
size--;
if (data.length >= INITIAL_CAPACITY * 4 * 2 && size * 4 < data.length / 4) {
data = Arrays.copyOf(data, data.length / 2);
objects = Arrays.copyOf(objects, objects.length / 2);
}
return (T) removed;
}
}
return null;
}
public boolean isInSphere(double x, double y, double z) {
final int maxIndex = size * 4;
final int[] a = data;
for (int i = 0; i < maxIndex; i += 4) {
final double dx = x - a[i] - 0.5D;
final double dy = y - a[i + 1] - 0.5D;
final double dz = z - a[i + 2] - 0.5D;
final double radius = a[i + 3];
if (dx * dx + dy * dy + dz * dz < radius * radius) {
return true;
}
}
return false;
}
public boolean isInCube(double x, double y, double z) {
final int maxIndex = size * 4;
final int[] a = data;
for (int i = 0; i < maxIndex; i += 4) {
final double centerX = a[i] + 0.5D;
final double centerY = a[i + 1] + 0.5D;
final double centerZ = a[i + 2] + 0.5D;
final double radius = a[i + 3] + 0.5D;
if (centerX - radius < x && x < centerX + radius
&& centerY - radius < y
&& y < centerY + radius
&& centerZ - radius < z
&& z < centerZ + radius) {
return true;
}
}
return false;
}
@SuppressWarnings("unchecked")
public T closestSphere(double x, double y, double z) {
final int maxIndex = size * 4;
final int[] a = data;
int closestIndex = -1;
double closestDistSq = Double.MAX_VALUE;
for (int i = 0; i < maxIndex; i += 4) {
final double dx = x - a[i] - 0.5D;
final double dy = y - a[i + 1] - 0.5D;
final double dz = z - a[i + 2] - 0.5D;
final double radius = a[i + 3];
final double distSq = dx * dx + dy * dy + dz * dz;
if (distSq < radius * radius && distSq < closestDistSq) {
closestIndex = i;
closestDistSq = distSq;
}
}
if (closestIndex == -1) return null;
return (T) objects[closestIndex / 4];
}
@SuppressWarnings("unchecked")
public T closestCube(double x, double y, double z) {
final int maxIndex = size * 4;
final int[] a = data;
int closestIndex = -1;
double closestDistSq = Double.MAX_VALUE;
for (int i = 0; i < maxIndex; i += 4) {
final double centerX = a[i] + 0.5D;
final double centerY = a[i + 1] + 0.5D;
final double centerZ = a[i + 2] + 0.5D;
final double radius = a[i + 3] + 0.5D;
if (centerX - radius < x && x < centerX + radius
&& centerY - radius < y
&& y < centerY + radius
&& centerZ - radius < z
&& z < centerZ + radius) {
final double dx = x - centerX;
final double dy = y - centerY;
final double dz = z - centerZ;
final double distSq = dx * dx + dy * dy + dz * dz;
if (distSq < closestDistSq) {
closestIndex = i;
closestDistSq = distSq;
}
}
}
if (closestIndex == -1) return null;
return (T) objects[closestIndex / 4];
}
@SuppressWarnings("unchecked")
public void forEachInSphere(double x, double y, double z, Consumer<T> action) {
final int maxIndex = size * 4;
final int[] a = data;
for (int i = 0; i < maxIndex; i += 4) {
final double dx = x - a[i] - 0.5D;
final double dy = y - a[i + 1] - 0.5D;
final double dz = z - a[i + 2] - 0.5D;
final double radius = a[i + 3];
final double distSq = dx * dx + dy * dy + dz * dz;
if (distSq < radius * radius) {
action.accept((T) objects[i / 4]);
}
}
}
@SuppressWarnings("unchecked")
public void forEachInCube(double x, double y, double z, Consumer<T> action) {
final int maxIndex = size * 4;
final int[] a = data;
for (int i = 0; i < maxIndex; i += 4) {
final double centerX = a[i] + 0.5D;
final double centerY = a[i + 1] + 0.5D;
final double centerZ = a[i + 2] + 0.5D;
final double radius = a[i + 3] + 0.5D;
if (centerX - radius < x && x < centerX + radius
&& centerY - radius < y
&& y < centerY + radius
&& centerZ - radius < z
&& z < centerZ + radius) {
action.accept((T) objects[i / 4]);
}
}
}
public boolean isEmpty() {
return size == 0;
}
@Override
public String toString() {
// spotless:off
final int maxIndex = size * 4;
final int[] a = data;
final StringBuilder sb = new StringBuilder("DimensionData{");
sb.append("dimId=").append(dimId);
sb.append(", size=").append(size);
sb.append(", data={");
for (int i = 0; i < maxIndex; i += 4) {
if (i != 0) sb.append(", ");
sb.append("{x=").append(a[i]);
sb.append(", y=").append(a[i + 1]);
sb.append(", z=").append(a[i + 2]);
sb.append(", radius=").append(a[i + 3]);
sb.append(" , obj=").append(objects[i / 4]).append('}');
}
sb.append("}}");
return sb.toString();
// spotless:on
}
}
}
@@ -0,0 +1,6 @@
package com.gtnewhorizon.gtnhlib.datastructs.space;
public enum VolumeShape {
SPHERE,
CUBE
}
@@ -1,474 +0,0 @@
package com.gtnewhorizon.gtnhlib.datastructs.spatialhashgrid;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.function.BiConsumer;
import org.joml.Vector3i;
import com.gtnewhorizon.gtnhlib.util.CoordinatePacker;
import com.gtnewhorizon.gtnhlib.util.DistanceUtil;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
/**
* 3D Spatial Grid <br>
* Objects are hashed using their position
*
* @param <T> object type to store
*/
@SuppressWarnings("unused")
public class SpatialHashGrid<T> {
private final int cellSize;
private final BiConsumer<Vector3i, T> positionExtractor;
private final Vector3i scratch = new Vector3i();
private final Long2ObjectOpenHashMap<ObjectArrayList<T>> grid = new Long2ObjectOpenHashMap<>();
public enum DistanceFormula implements DistanceMetric {
SquaredEuclidean(new DistanceMetric() {
@Override
public double distance(double x1, double y1, double z1, double x2, double y2, double z2) {
return DistanceUtil.squaredEuclideanDistance(x1, y1, z1, x2, y2, z2);
}
@Override
public double transformCompareDistance(double radius) {
return radius * radius;
}
}),
/**
* Chessboard
*/
Chebyshev(DistanceUtil::chebyshevDistance),
/**
* Taxicab
*/
Manhattan(DistanceUtil::manhattanDistance);
private final DistanceMetric metric;
DistanceFormula(DistanceMetric metric) {
this.metric = metric;
}
@Override
public double distance(double x1, double y1, double z1, double x2, double y2, double z2) {
return this.metric.distance(x1, y1, z1, x2, y2, z2);
}
@Override
public double transformCompareDistance(double radius) {
return this.metric.transformCompareDistance(radius);
}
}
@FunctionalInterface
public interface DistanceMetric {
double distance(double x1, double y1, double z1, double x2, double y2, double z2);
default double transformCompareDistance(double radius) {
return radius;
}
}
public SpatialHashGrid(int cellSize, BiConsumer<Vector3i, T> positionExtractor) {
if (cellSize <= 0) throw new IllegalArgumentException("cellSize can not be less than or equal to 0");
this.cellSize = cellSize;
this.positionExtractor = positionExtractor;
}
private static long pack(int x, int y, int z) {
return CoordinatePacker.pack(x, y, z);
}
private static long hash(int cellSize, 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(cellSize, scratch.x, scratch.y, scratch.z);
ObjectArrayList<T> 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(cellSize, scratch.x, scratch.y, scratch.z);
ObjectArrayList<T> list = grid.get(key);
if (list == null) return;
list.remove(obj);
if (!list.isEmpty()) return;
grid.remove(key);
}
public boolean contains(T obj) {
positionExtractor.accept(scratch, obj);
long key = hash(cellSize, scratch.x, scratch.y, scratch.z);
ObjectArrayList<T> list = grid.get(key);
if (list == null) return false;
return list.contains(obj);
}
/**
* Search the grid for nearby objects using Squared Euclidean Distance Formula.
*
* @param radius distance in blocks to check (sphere)
* @return list of nearby objects
*/
public List<T> collectNearbySquaredEuclidean(int x, int y, int z, int radius) {
return collectNearbyWithMetric(x, y, z, radius, DistanceFormula.SquaredEuclidean);
}
/**
* Search the grid for nearby objects using Chebyshev (Chessboard) Distance Formula.
*
* @param radius distance in blocks to check (sphere)
* @return list of nearby objects
*/
public List<T> collectNearbyChebyshev(int x, int y, int z, int radius) {
return collectNearbyWithMetric(x, y, z, radius, DistanceFormula.Chebyshev);
}
/**
* Search the grid for nearby objects using Manhattan (Taxicab) Distance Formula.
*
* @param radius distance in blocks to check (sphere)
* @return list of nearby objects
*/
public List<T> collectNearbyManhattan(int x, int y, int z, int radius) {
return collectNearbyWithMetric(x, y, z, radius, DistanceFormula.Manhattan);
}
/**
* Find the first nearby object using Squared Euclidean Distance Formula.
*
* @param x position to check
* @param y position to check
* @param z position to check
* @param radius distance in blocks to check (sphere)
* @return the first nearby object or null if none found
*/
public T findFirstNearbySquaredEuclidean(int x, int y, int z, int radius) {
return findFirstNearbyWithMetric(x, y, z, radius, DistanceFormula.SquaredEuclidean);
}
/**
* Find the first nearby object using Chebyshev (Chessboard) Distance Formula.
*
* @param x position to check
* @param y position to check
* @param z position to check
* @param radius distance in blocks to check (sphere)
* @return the first nearby object or null if none found
*/
public T findFirstNearbyChebyshev(int x, int y, int z, int radius) {
return findFirstNearbyWithMetric(x, y, z, radius, DistanceFormula.Chebyshev);
}
/**
* Find the first nearby object using Manhattan (Taxicab) Distance Formula.
*
* @param x position to check
* @param y position to check
* @param z position to check
* @param radius distance in blocks to check (sphere)
* @return the first nearby object or null if none found
*/
public T findFirstNearbyManhattan(int x, int y, int z, int radius) {
return findFirstNearbyWithMetric(x, y, z, radius, DistanceFormula.Manhattan);
}
/**
* Find the closest nearby object using Squared Euclidean Distance Formula.
*
* @param x position to check
* @param y position to check
* @param z position to check
* @param radius distance in blocks to check (sphere)
* @return the closest nearby object or null if none found
*/
public T findClosestSquaredEuclidean(int x, int y, int z, int radius) {
return findClosestWithMetric(x, y, z, radius, DistanceFormula.SquaredEuclidean);
}
/**
* Find the closest nearby object using Chebyshev (Chessboard) Distance Formula.
*
* @param x position to check
* @param y position to check
* @param z position to check
* @param radius distance in blocks to check (sphere)
* @return the closest nearby object or null if none found
*/
public T findClosestChebyshev(int x, int y, int z, int radius) {
return findClosestWithMetric(x, y, z, radius, DistanceFormula.Chebyshev);
}
/**
* Find the closest nearby object using Manhattan (Taxicab) Distance Formula.
*
* @param x position to check
* @param y position to check
* @param z position to check
* @param radius distance in blocks to check (sphere)
* @return the closest nearby object or null if none found
*/
public T findClosestManhattan(int x, int y, int z, int radius) {
return findClosestWithMetric(x, y, z, radius, DistanceFormula.Manhattan);
}
/**
* Find the first nearby object using a specified distance metric. <br>
* <strong>Note:</strong> This method does <strong>not</strong> return the closest object
*
* @param x position to check
* @param y position to check
* @param z position to check
* @param radius distance in blocks to check (sphere)
* @param distanceMetric distance metric to use
* @return the first nearby object or null if none found
* @see #findClosestWithMetric(int, int, int, int, DistanceMetric)
*/
public T findFirstNearbyWithMetric(int x, int y, int z, int radius, DistanceMetric distanceMetric) {
Iterator<T> iterator = iterNearbyWithMetric(x, y, z, radius, distanceMetric);
return (iterator.hasNext() ? iterator.next() : null);
}
/**
* Find the closest nearby object using a specified distance metric.
*
* @param x position to check
* @param y position to check
* @param z position to check
* @param radius distance in blocks to check (sphere)
* @param distanceMetric distance metric to use
* @return the closest nearby object or null if none found
*/
public T findClosestWithMetric(int x, int y, int z, int radius, DistanceMetric distanceMetric) {
Iterator<T> iterator = iterNearbyWithMetric(x, y, z, radius, distanceMetric);
T closestObject = null;
double closestDistance = Double.MAX_VALUE;
while (iterator.hasNext()) {
T obj = iterator.next();
positionExtractor.accept(scratch, obj);
double distance = distanceMetric.distance(x, y, z, scratch.x, scratch.y, scratch.z);
if (distance < closestDistance) {
closestDistance = distance;
closestObject = obj;
}
}
return closestObject;
}
/**
* Collect all nearby objects using a specified distance metric.
*
* @param x position to check
* @param y position to check
* @param z position to check
* @param radius distance in blocks to check (sphere)
* @param distanceMetric distance metric to use
* @return list of nearby objects
*/
public List<T> collectNearbyWithMetric(int x, int y, int z, int radius, DistanceMetric distanceMetric) {
Iterator<T> iterator = iterNearbyWithMetric(x, y, z, radius, distanceMetric);
List<T> resultList = new ArrayList<>();
while (iterator.hasNext()) {
T obj = iterator.next();
resultList.add(obj);
}
return resultList;
}
/**
* Search the grid for nearby objects using a specified distance metric.
*
* @param x position to check
* @param y position to check
* @param z position to check
* @param radius distance in blocks to check (sphere)
* @param distanceMetric distance metric to use
* @return iterator of nearby objects
*/
public Iterator<T> iterNearbyWithMetric(int x, int y, int z, int radius, DistanceMetric distanceMetric) {
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);
return new GridIterator<>(grid, x, y, z, radius, cellSize, distanceMetric, positionExtractor);
}
public static class GridIterator<T> implements Iterator<T> {
private final Long2ObjectOpenHashMap<ObjectArrayList<T>> grid;
private final int x, y, z;
private final int cellSize;
private final int minCellX, minCellY, minCellZ;
private final int maxCellX, maxCellY, maxCellZ;
private final double distanceCompared;
private final DistanceMetric distanceMetric;
private final BiConsumer<Vector3i, T> positionExtractor;
private final Vector3i scratch = new Vector3i();
private int currCellX, currCellY, currCellZ;
private boolean isEdgeCell;
private ObjectArrayList<T> currentCell;
private int currCellIdx;
private T nextElement;
private boolean hasNextElement;
public GridIterator(Long2ObjectOpenHashMap<ObjectArrayList<T>> grid, int x, int y, int z, int radius,
int cellSize, DistanceMetric distanceMetric, BiConsumer<Vector3i, T> positionExtractor) {
this.grid = grid;
this.x = x;
this.y = y;
this.z = z;
this.cellSize = cellSize;
this.distanceCompared = distanceMetric.transformCompareDistance(radius);
this.distanceMetric = distanceMetric;
this.positionExtractor = positionExtractor;
this.minCellX = Math.floorDiv(x - radius, cellSize);
this.minCellY = Math.floorDiv(y - radius, cellSize);
this.minCellZ = Math.floorDiv(z - radius, cellSize);
this.maxCellX = Math.floorDiv(x + radius + cellSize - 1, cellSize);
this.maxCellY = Math.floorDiv(y + radius + cellSize - 1, cellSize);
this.maxCellZ = Math.floorDiv(z + radius + cellSize - 1, cellSize);
this.currCellX = minCellX;
this.currCellY = minCellY;
this.currCellZ = minCellZ;
computeNext();
}
@Override
public boolean hasNext() {
return hasNextElement;
}
@Override
public T next() {
if (!hasNextElement) throw new NoSuchElementException();
T result = nextElement;
computeNext();
return result;
}
public T peek() {
if (!hasNextElement) throw new NoSuchElementException();
return nextElement;
}
private void computeNext() {
hasNextElement = false;
nextElement = null;
do {
if (findNextElementInCell()) return;
} while (findNextCell());
}
private boolean isCellPotentiallyInRange(int cellX, int cellY, int cellZ) {
int nx = nearest(x, cellX, cellX + cellSize - 1);
int ny = nearest(y, cellY, cellY + cellSize - 1);
int nz = nearest(z, cellZ, cellZ + cellSize - 1);
return distanceMetric.distance(x, y, z, nx, ny, nz) <= distanceCompared;
}
private boolean isCellFullyInRange(int cellX, int cellY, int cellZ) {
int fx = farthest(x, cellX, cellX + cellSize - 1);
int fy = farthest(y, cellY, cellY + cellSize - 1);
int fz = farthest(z, cellZ, cellZ + cellSize - 1);
return distanceMetric.distance(x, y, z, fx, fy, fz) <= distanceCompared;
}
private static int farthest(int p, int min, int max) {
if (p < min) return max;
if (p > max) return min;
return ((p - min) > (max - p)) ? min : max;
}
private static int nearest(int v, int min, int max) {
if (v < min) return min;
return Math.min(v, max);
}
private boolean findNextCell() {
while (currCellX <= maxCellX) {
while (currCellY <= maxCellY) {
while (currCellZ <= maxCellZ) {
int currCellZ = this.currCellZ++;
int cx = currCellX * cellSize;
int cy = currCellY * cellSize;
int cz = currCellZ * cellSize;
boolean isCellInRange = isCellPotentiallyInRange(cx, cy, cz);
if (!isCellInRange) continue;
long key = pack(currCellX, currCellY, currCellZ);
ObjectArrayList<T> cell = grid.get(key);
if (cell != null && !cell.isEmpty()) {
currentCell = cell;
isEdgeCell = !isCellFullyInRange(cx, cy, cz);
currCellIdx = 0;
return true;
}
}
currCellZ = minCellZ;
currCellY++;
}
currCellY = minCellY;
currCellX++;
}
return false;
}
private boolean findNextElementInCell() {
if (currentCell == null) return false;
while (currCellIdx < currentCell.size()) {
T candidate = currentCell.get(currCellIdx++);
if (!isEdgeCell || isEdgeElementInRange(candidate)) {
nextElement = candidate;
hasNextElement = true;
return true;
}
}
currentCell = null;
return false;
}
private boolean isEdgeElementInRange(T candidate) {
positionExtractor.accept(scratch, candidate);
double dist = distanceMetric.distance(x, y, z, scratch.x, scratch.y, scratch.z);
return dist <= distanceCompared;
}
}
}