mirror of
https://github.com/PolyhedralDev/Terra.git
synced 2026-11-28 00:45:03 +00:00
perf: replace biome tag checks with bitset columns
This commit is contained in:
1 parent
6ddf039e49
commit
8a940f7e1f
45 files changed
+938
-314
No files matched your search
@@ -26,6 +26,7 @@ import com.dfsek.terra.api.tectonic.LoaderRegistrar;
|
||||
import com.dfsek.terra.api.tectonic.ShortcutLoader;
|
||||
import com.dfsek.terra.api.util.reflection.TypeKey;
|
||||
import com.dfsek.terra.api.world.biome.generation.BiomeProvider;
|
||||
import com.dfsek.terra.api.world.biome.tag.BiomeTagIndex;
|
||||
import com.dfsek.terra.api.world.chunk.generation.stage.GenerationStage;
|
||||
import com.dfsek.terra.api.world.chunk.generation.util.provider.ChunkGeneratorProvider;
|
||||
|
||||
@@ -43,6 +44,11 @@ public interface ConfigPack extends LoaderRegistrar,
|
||||
|
||||
BiomeProvider getBiomeProvider();
|
||||
|
||||
/**
|
||||
* @return this pack's biome tag index; sealed once the pack has finished loading
|
||||
*/
|
||||
BiomeTagIndex getBiomeTagIndex();
|
||||
|
||||
List<GenerationStage> getStages();
|
||||
|
||||
Path getRootPath();
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
package com.dfsek.terra.api.util.collection;
|
||||
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.lang.invoke.VarHandle;
|
||||
|
||||
import com.dfsek.seismic.util.UnsafeUtils;
|
||||
|
||||
|
||||
public class TriStateIntCache {
|
||||
public static final long STATE_UNSET = 0L;
|
||||
public static final long STATE_FALSE = 1L;
|
||||
public static final long STATE_TRUE = 2L;
|
||||
|
||||
private static final long BIT_MASK = 3L;
|
||||
private final long[] data;
|
||||
|
||||
private static final VarHandle ARRAY_HANDLE = MethodHandles.arrayElementVarHandle(long[].class);
|
||||
|
||||
private static int getOptimalMaxKeys(int requestedKeys) {
|
||||
// 192 keys fill the first cache line exactly (along with the 16-byte header)
|
||||
if (requestedKeys <= 192) {
|
||||
return 192;
|
||||
}
|
||||
|
||||
// For every additional line, we fit 256 keys (64 bytes * 4 keys/byte)
|
||||
// We calculate the overflow beyond 192, round up to the nearest 256, and add it back.
|
||||
int overflow = requestedKeys - 192;
|
||||
int chunks = (overflow + 255) >>> 8; // Fast ceil division by 256
|
||||
|
||||
return 192 + (chunks << 8); // chunks * 256
|
||||
}
|
||||
|
||||
public TriStateIntCache(int maxKeySize) {
|
||||
this.data = new long[(getOptimalMaxKeys(maxKeySize) + 31) >>> 5];
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks the cache state without any allocation.
|
||||
*
|
||||
* @return STATE_UNSET (0), STATE_FALSE (1), or STATE_TRUE (2)
|
||||
*/
|
||||
public long get(int key) {
|
||||
long offset = UnsafeUtils.LONG_ARRAY_BASE + ((long)(key >>> 5) << UnsafeUtils.LONG_ARRAY_SHIFT);
|
||||
long currentWord = UnsafeUtils.UNSAFE.getLong(data, offset);
|
||||
return (currentWord >>> ((key << 1) & 63)) & BIT_MASK;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value safely. Handles race conditions internally.
|
||||
*/
|
||||
public void set(int key, boolean value) {
|
||||
int index = key >>> 5;
|
||||
int shift = (key << 1) & 63;
|
||||
|
||||
long targetWord = (value ? STATE_TRUE : STATE_FALSE) << shift;
|
||||
|
||||
long current;
|
||||
do {
|
||||
current = (long) ARRAY_HANDLE.getVolatile(data, index);
|
||||
|
||||
if (((current >>> shift) & BIT_MASK) != STATE_UNSET) {
|
||||
return;
|
||||
}
|
||||
|
||||
} while (!ARRAY_HANDLE.compareAndSet(data, index, current, current | targetWord));
|
||||
}
|
||||
}
|
||||
@@ -8,10 +8,12 @@
|
||||
package com.dfsek.terra.api.world.biome;
|
||||
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import com.dfsek.terra.api.properties.PropertyHolder;
|
||||
import com.dfsek.terra.api.registry.key.RegistryKey;
|
||||
import com.dfsek.terra.api.registry.key.StringIdentifiable;
|
||||
|
||||
|
||||
@@ -19,8 +21,6 @@ import com.dfsek.terra.api.registry.key.StringIdentifiable;
|
||||
* Represents a Terra biome
|
||||
*/
|
||||
public interface Biome extends PropertyHolder, StringIdentifiable {
|
||||
AtomicInteger INT_ID_COUNTER = new AtomicInteger(0);
|
||||
|
||||
/**
|
||||
* Gets the platform biome this custom biome delegates to.
|
||||
*
|
||||
@@ -42,9 +42,17 @@ public interface Biome extends PropertyHolder, StringIdentifiable {
|
||||
*/
|
||||
Set<String> getTags();
|
||||
|
||||
/**
|
||||
* Get the namespaced entries of this biome's config {@code tags:}, as written.
|
||||
*/
|
||||
default @NotNull Set<RegistryKey> getPlatformTags() {
|
||||
return Set.of();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get the numeric ID of this biome, generated at registration time
|
||||
* Get the numeric ID of this biome: dense per pack, from 1, issued by {@code getBiomeTagIndex().register(...)} during pack
|
||||
* load.
|
||||
*
|
||||
* @return The numeric ID.
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.dfsek.terra.api.world.biome.tag;
|
||||
|
||||
import com.dfsek.seismic.util.UnsafeUtils;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
import com.dfsek.terra.api.world.biome.Biome;
|
||||
|
||||
import org.jetbrains.annotations.Contract;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
|
||||
/**
|
||||
* Biome IDs are not stable across loads; never persist one.
|
||||
*/
|
||||
public final class BiomeTag implements Predicate<Biome> {
|
||||
// Lets has() on an unsealed tag return false for IDs below 512.
|
||||
private static final long[] UNSEALED = new long[8];
|
||||
|
||||
private final String name;
|
||||
private final BiomeTagIndex index;
|
||||
|
||||
// Not volatile: published by the index's volatile sealed flag, or by the index lock for tags created after seal.
|
||||
private long[] bits = UNSEALED;
|
||||
|
||||
BiomeTag(String name, BiomeTagIndex index) {
|
||||
this.name = name;
|
||||
this.index = index;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Contract(pure = true)
|
||||
public String name() {
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* No bounds checks. Only call after the owning {@link BiomeTagIndex} is sealed, with IDs from that index.
|
||||
*/
|
||||
public boolean has(int biomeId) {
|
||||
long word = UnsafeUtils.UNSAFE.getLong(bits,
|
||||
UnsafeUtils.LONG_ARRAY_BASE + ((long) (biomeId >>> 6) << UnsafeUtils.LONG_ARRAY_SHIFT));
|
||||
return ((word >>> biomeId) & 1L) != 0L;
|
||||
}
|
||||
|
||||
/**
|
||||
* Doesn't detect a biome from another pack whose ID is in range.
|
||||
*
|
||||
* @throws IllegalArgumentException if sealed and the biome's ID is outside this tag's bitset
|
||||
*/
|
||||
@Override
|
||||
public boolean test(Biome biome) {
|
||||
if(!index.isSealed()) { // volatile read: also publishes bits built by seal
|
||||
return biome.getTags().contains(name);
|
||||
}
|
||||
int id = biome.getIntID();
|
||||
if(id < 0 || id >= (bits.length << 6)) {
|
||||
throw new IllegalArgumentException("biome id " + id + " is not from this tag's pack");
|
||||
}
|
||||
return has(id);
|
||||
}
|
||||
|
||||
long[] bits() {
|
||||
return bits;
|
||||
}
|
||||
|
||||
void build(int size, List<Set<String>> tagSets) {
|
||||
// Whole 64-byte lines: every ID below size is in bounds.
|
||||
long[] built = new long[((size + 511) >>> 9) << 3];
|
||||
for(int id = 1; id < size; id++) {
|
||||
if(tagSets.get(id).contains(name)) {
|
||||
built[id >>> 6] |= 1L << id;
|
||||
}
|
||||
}
|
||||
this.bits = built;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.dfsek.terra.api.world.biome.tag;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
import org.jetbrains.annotations.Contract;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
|
||||
/**
|
||||
* ID 0 is reserved. Biomes register during pack load; the platform seals the index once the pack is built.
|
||||
*/
|
||||
public final class BiomeTagIndex {
|
||||
private final ConcurrentHashMap<String, BiomeTag> tags = new ConcurrentHashMap<>();
|
||||
private final List<Set<String>> tagSets = new ArrayList<>(); // guarded by this
|
||||
private volatile boolean sealed = false;
|
||||
|
||||
public BiomeTagIndex() {
|
||||
tagSets.add(Set.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* @return a dense ID, at least 1
|
||||
*
|
||||
* @throws IllegalStateException if sealed
|
||||
*/
|
||||
public synchronized int register(Set<String> biomeTags) {
|
||||
if(sealed) throw new IllegalStateException("BiomeTagIndex is sealed");
|
||||
tagSets.add(Set.copyOf(biomeTags));
|
||||
return tagSets.size() - 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Never released: resolve each tag once at pack load, not per sample.
|
||||
*/
|
||||
@NotNull
|
||||
public BiomeTag tag(String name) {
|
||||
BiomeTag existing = tags.get(name);
|
||||
// The volatile read of sealed publishes the bits; before seal, the lock does.
|
||||
if(existing != null && sealed) return existing;
|
||||
synchronized(this) {
|
||||
BiomeTag tag = tags.get(name);
|
||||
if(tag == null) {
|
||||
tag = new BiomeTag(name, this);
|
||||
if(sealed) tag.build(tagSets.size(), tagSets);
|
||||
tags.put(name, tag);
|
||||
}
|
||||
return tag;
|
||||
}
|
||||
}
|
||||
|
||||
@ApiStatus.Internal
|
||||
public synchronized void seal() {
|
||||
if(sealed) return;
|
||||
int size = tagSets.size();
|
||||
for(BiomeTag tag : tags.values()) tag.build(size, tagSets);
|
||||
sealed = true;
|
||||
}
|
||||
|
||||
@Contract(pure = true)
|
||||
public boolean isSealed() {
|
||||
return sealed;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return number of IDs including the reserved 0
|
||||
*/
|
||||
public synchronized int size() {
|
||||
return tagSets.size();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package com.dfsek.terra.api.world.biome.tag;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import com.dfsek.terra.api.world.biome.Biome;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
|
||||
public class BiomeTagIndexTest {
|
||||
@Test
|
||||
public void denseIds() {
|
||||
BiomeTagIndex index = new BiomeTagIndex();
|
||||
assertEquals(1, index.register(Set.of("A")));
|
||||
assertEquals(2, index.register(Set.of("B")));
|
||||
assertEquals(3, index.register(Set.of()));
|
||||
assertEquals(4, index.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void membershipAndInterning() {
|
||||
BiomeTagIndex index = new BiomeTagIndex();
|
||||
int a = index.register(Set.of("X", "Z"));
|
||||
int b = index.register(Set.of("X"));
|
||||
int c = index.register(Set.of("Y"));
|
||||
BiomeTag x = index.tag("X");
|
||||
index.seal();
|
||||
assertSame(x, index.tag("X"));
|
||||
BiomeTag z = index.tag("Z");
|
||||
assertSame(z, index.tag("Z"));
|
||||
assertEquals("Z", z.name());
|
||||
BiomeTag y = index.tag("Y");
|
||||
BiomeTag unknown = index.tag("NOPE");
|
||||
for(int id = 0; id < index.size(); id++) {
|
||||
assertEquals(id == a || id == b, x.has(id), "X has " + id);
|
||||
assertEquals(id == c, y.has(id), "Y has " + id);
|
||||
assertEquals(id == a, z.has(id), "Z has " + id);
|
||||
assertFalse(unknown.has(id), "unknown tag has " + id);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sealing() {
|
||||
BiomeTagIndex index = new BiomeTagIndex();
|
||||
int a = index.register(Set.of("X"));
|
||||
index.seal();
|
||||
index.seal();
|
||||
assertTrue(index.isSealed());
|
||||
assertTrue(index.tag("X").has(a));
|
||||
assertThrows(IllegalStateException.class, () -> index.register(Set.of("X")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parallelRegister() {
|
||||
BiomeTagIndex index = new BiomeTagIndex();
|
||||
Set<Integer> ids = IntStream.range(0, 10_000).parallel()
|
||||
.mapToObj(i -> index.register(Set.of("T" + (i % 7))))
|
||||
.collect(Collectors.toSet());
|
||||
assertEquals(10_000, ids.size());
|
||||
assertEquals(1, ids.stream().mapToInt(Integer::intValue).min().getAsInt());
|
||||
assertEquals(10_000, ids.stream().mapToInt(Integer::intValue).max().getAsInt());
|
||||
assertEquals(10_001, index.size());
|
||||
index.seal();
|
||||
for(int id : ids) {
|
||||
int matches = 0;
|
||||
for(int t = 0; t < 7; t++) {
|
||||
if(index.tag("T" + t).has(id)) matches++;
|
||||
}
|
||||
assertEquals(1, matches);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bitsetSize() {
|
||||
BiomeTagIndex index = new BiomeTagIndex();
|
||||
for(int i = 0; i < 600; i++) index.register(Set.of("X"));
|
||||
BiomeTag x = index.tag("X");
|
||||
index.seal();
|
||||
assertEquals(0, x.bits().length % 8);
|
||||
assertTrue(x.bits().length * 64L >= index.size());
|
||||
assertTrue(x.has(600));
|
||||
BiomeTag late = index.tag("LATE");
|
||||
assertEquals(0, late.bits().length % 8);
|
||||
assertTrue(late.bits().length * 64L >= index.size());
|
||||
}
|
||||
|
||||
private static Biome biome(int id, Set<String> tags) {
|
||||
return (Biome) Proxy.newProxyInstance(Biome.class.getClassLoader(), new Class<?>[]{ Biome.class }, (proxy, method, args) ->
|
||||
switch(method.getName()) {
|
||||
case "getIntID" -> id;
|
||||
case "getTags" -> tags;
|
||||
default -> throw new UnsupportedOperationException(method.getName());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBeforeAndAfterSeal() {
|
||||
BiomeTagIndex index = new BiomeTagIndex();
|
||||
Set<String> tagsA = Set.of("X");
|
||||
Set<String> tagsB = Set.of("Y");
|
||||
Biome a = biome(index.register(tagsA), tagsA);
|
||||
Biome b = biome(index.register(tagsB), tagsB);
|
||||
BiomeTag x = index.tag("X");
|
||||
assertTrue(x.test(a));
|
||||
assertFalse(x.test(b));
|
||||
for(int i = 0; i < 512; i++) assertFalse(x.has(i));
|
||||
index.seal();
|
||||
assertTrue(x.has(a.getIntID()));
|
||||
assertTrue(x.test(a));
|
||||
assertFalse(x.test(b));
|
||||
assertThrows(IllegalArgumentException.class, () -> x.test(biome(512, Set.of())));
|
||||
assertThrows(IllegalArgumentException.class, () -> x.test(biome(100_000, Set.of())));
|
||||
assertThrows(IllegalArgumentException.class, () -> x.test(biome(-1, Set.of())));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user