Merge engine-owned pack runtime into the studio leak fix

- Take the pack runtime side for every conflicting cache
- Drop EngineRef and ReleasableThreadLocal, which the pack runtime replaces
- Keep closing cached world packs with their generator
This commit is contained in:
piexel committed 2026-11-27 08:12:44 +01:00
commit 45d5203489
241 files changed
+4686 -3395

No files matched your search

@@ -19,6 +19,7 @@
package art.arcane.iris.modded;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.BiomeEnvironment;
@@ -223,17 +224,18 @@ public final class ModdedEngineEffects extends EngineAssignedComponent implement
}
private void applyEffects(NativeWorld level, NativeProtocolPlayer player, Iterable<IrisEffect> effects) {
PackRuntime runtime = PackRuntime.of(getEngine());
for (IrisEffect effect : effects) {
try {
applyEffect(level, player, effect);
applyEffect(level, player, effect, runtime);
} catch (Throwable error) {
IrisLogging.reportError(error);
}
}
}
private void applyEffect(NativeWorld level, NativeProtocolPlayer player, IrisEffect effect) {
if (!effect.shouldApplyNow()) {
private void applyEffect(NativeWorld level, NativeProtocolPlayer player, IrisEffect effect, PackRuntime runtime) {
if (!effect.shouldApplyNow(runtime)) {
return;
}
@@ -18,6 +18,7 @@
package art.arcane.iris.modded;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.generation.decoration.IrisSurface;
import art.arcane.iris.generation.runtime.Engine;
@@ -127,7 +128,7 @@ public final class ModdedEntitySpawner {
entity.configureAnimal(irisEntity);
applySpawnEffect(irisEntity.getSpawnEffect(), entity, level);
applySpawnEffect(irisEntity.getSpawnEffect(), entity, level, PackRuntime.of(engine));
ModdedEntityCommandRunner.run(irisEntity.getRawCommands(), level.world(), blockX, blockY, blockZ);
if (riseEffectActive && entity.living()) {
startRiseEffect(engine, level, entity);
@@ -200,8 +201,9 @@ public final class ModdedEntitySpawner {
return level.chunksSafe(chunkX, chunkZ);
}
private static void applySpawnEffect(IrisEffect effect, NativeSpawnedEntity entity, NativeEntityRuntime level) {
if (effect == null || !effect.shouldApplyNow()) {
private static void applySpawnEffect(IrisEffect effect, NativeSpawnedEntity entity, NativeEntityRuntime level,
PackRuntime runtime) {
if (effect == null || !effect.shouldApplyNow(runtime)) {
return;
}
@@ -1,5 +1,6 @@
package art.arcane.iris.modded;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.volmlib.nativelib.terrain.structure.StructureStagePolicy;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.mantle.DeferredPlacementRecords;
@@ -151,7 +152,7 @@ final class ModdedNativeStructurePolicy implements NativeModdedStructureStage.Po
@Override
public NativeBlockState paletteBlock(StructurePalette source, RNG rng, int x, int y, int z) {
return ((IrisMaterialPalette) source).get(rng, x, y, z, generator.engine().getData());
return ((IrisMaterialPalette) source).get(rng, x, y, z, PackRuntime.of(generator.engine()));
}
@Override
@@ -1,7 +1,7 @@
package art.arcane.iris.generation.bake;
import art.arcane.iris.generation.runtime.ThreadSlots;
import art.arcane.iris.generation.cache.ConcurrentClockCache;
import art.arcane.iris.generation.cache.ReleasableThreadLocal;
import art.arcane.iris.generation.stream.ProvisionalSampling;
import java.util.Arrays;
@@ -17,7 +17,7 @@ public final class ChunkBakeCache {
private final PlaneSource source;
private final ConcurrentClockCache<ChunkPlanes> entries;
private final ReleasableThreadLocal<Recent> recent = new ReleasableThreadLocal<>(Recent::new);
private final ThreadSlots<Recent> recent = new ThreadSlots<>(Recent::new);
private volatile int generation;
public ChunkBakeCache(PlaneSource source, int capacityChunks) {
@@ -38,7 +38,6 @@ public final class ChunkBakeCache {
generation++;
entries.forEach(ChunkPlanes::release);
entries.clear();
recent.releaseAll();
}
public long[] census() {
@@ -3,6 +3,7 @@ package art.arcane.iris.generation.bake;
import art.arcane.iris.generation.noise.GeneratorProgram;
import art.arcane.iris.generation.noise.IrisGenerator;
import art.arcane.iris.generation.noise.TerrainBatchScratch;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.volmlib.util.math.M;
import java.util.Arrays;
@@ -12,26 +13,28 @@ public final class TerrainProgram {
private static final int CONSTANT = 1;
private static final int ACTIVE = 2;
private final PackRuntime runtime;
private final IrisGenerator[][] generators;
private final GeneratorProgram[][] programs;
private final long heightSeed;
private TerrainProgram(IrisGenerator[][] generators, GeneratorProgram[][] programs, long heightSeed) {
private TerrainProgram(PackRuntime runtime, IrisGenerator[][] generators, GeneratorProgram[][] programs, long heightSeed) {
this.runtime = runtime;
this.generators = generators;
this.programs = programs;
this.heightSeed = heightSeed;
}
public static TerrainProgram compile(IrisGenerator[][] generators, long heightSeed) {
public static TerrainProgram compile(PackRuntime runtime, IrisGenerator[][] generators, long heightSeed) {
GeneratorProgram[][] programs = new GeneratorProgram[generators.length][];
for (int group = 0; group < generators.length; group++) {
programs[group] = new GeneratorProgram[generators[group].length];
for (int index = 0; index < generators[group].length; index++) {
IrisGenerator generator = generators[group][index];
programs[group][index] = generator.supportsBatch() ? generator.compileProgram(heightSeed) : null;
programs[group][index] = generator.supportsBatch() ? generator.compileProgram(runtime, heightSeed) : null;
}
}
return new TerrainProgram(generators, programs, heightSeed);
return new TerrainProgram(runtime, generators, programs, heightSeed);
}
public long heightSeed() {
@@ -58,7 +61,7 @@ public final class TerrainProgram {
GeneratorProgram[] compiled = programs[group];
for (int member = 0; member < members.length; member++) {
GeneratorProgram program = compiled[member];
double noise = program != null ? program.height(scratch, x, z) : members[member].getHeight(x, z, heightSeed);
double noise = program != null ? program.height(scratch, x, z) : members[member].getHeight(runtime, x, z, heightSeed);
if (!Double.isFinite(noise)) {
throw new IllegalStateException("Terrain generator noise was not finite at " + x + "," + z
+ " (generator=" + members[member].getLoadKey() + ", noise=" + noise
@@ -148,7 +151,7 @@ public final class TerrainProgram {
program.heights(scratch, activeX, activeZ, activeCount, noise);
} else {
for (int index = 0; index < activeCount; index++) {
noise[index] = members[member].getHeight(activeX[index], activeZ[index], heightSeed);
noise[index] = members[member].getHeight(runtime, activeX[index], activeZ[index], heightSeed);
}
}
for (int index = 0; index < activeCount; index++) {
@@ -0,0 +1,155 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* 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 <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.generation.biome;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.SeedTable;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.noise.CNG;
import art.arcane.iris.generation.decoration.DecoratorRuntime;
import art.arcane.iris.generation.decoration.IrisDecorationPart;
import art.arcane.iris.generation.decoration.IrisDecorator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.function.Supplier;
/**
* What one engine derives from an {@link IrisBiome}: its scatter generators, the children generators per shrink
* scale, the height generators of its layer palettes and the runtimes of those palettes, linked by layer index so
* painting a column reads them without looking each layer up.
*/
public final class BiomeRuntime {
private static final int BIOME_SEED_CAPACITY = 8;
private static final int CHILD_SEED_CAPACITY = 8;
private static final int LAYER_HEIGHT_SEED_CAPACITY = 32;
private static final int SURFACE_LAYER_SEED_OFFSET = 7235;
private static final int SEA_LAYER_SEED_OFFSET = 7735;
private static final int CEILING_LAYER_SEED_OFFSET = 7235;
private final IrisBiome biome;
private final PackRuntime runtime;
private final SeedTable<CNG> biomeGenerators;
private final ConcurrentHashMap<Long, SeedTable<CNG>> childGeneratorsByScale = new ConcurrentHashMap<>();
private final SeedTable<KList<CNG>> layerHeights;
private final SeedTable<KList<CNG>> seaLayerHeights;
private final SeedTable<KList<CNG>> ceilingLayerHeights;
private final LinkedLayers surfaceLayers;
private final LinkedLayers seaLayers;
private final LinkedLayers ceilingLayers;
private final AtomicReferenceArray<LinkedDecorators> decoratorBuckets =
new AtomicReferenceArray<>(IrisDecorationPart.values().length);
public BiomeRuntime(IrisBiome biome, PackRuntime runtime) {
this.biome = biome;
this.runtime = runtime;
this.biomeGenerators = new SeedTable<>(BIOME_SEED_CAPACITY, seed -> biome.createBiomeGenerator(seed, runtime));
this.layerHeights = new SeedTable<>(LAYER_HEIGHT_SEED_CAPACITY, seed ->
IrisBiomeLayerGenerator.createHeightGenerators(biome.getLayers(), SURFACE_LAYER_SEED_OFFSET, seed, runtime));
this.seaLayerHeights = new SeedTable<>(LAYER_HEIGHT_SEED_CAPACITY, seed ->
IrisBiomeLayerGenerator.createHeightGenerators(biome.getSeaLayers(), SEA_LAYER_SEED_OFFSET, seed, runtime));
this.ceilingLayerHeights = new SeedTable<>(LAYER_HEIGHT_SEED_CAPACITY, seed ->
IrisBiomeLayerGenerator.createHeightGenerators(biome.getCaveCeilingLayers(), CEILING_LAYER_SEED_OFFSET, seed, runtime));
this.surfaceLayers = new LinkedLayers(biome::getLayers);
this.seaLayers = new LinkedLayers(biome::getSeaLayers);
this.ceilingLayers = new LinkedLayers(biome::getCaveCeilingLayers);
}
public CNG biomeGenerator(long seed) {
return biomeGenerators.get(seed);
}
public CNG childrenGenerator(long seed, double scale) {
return childGeneratorsByScale.computeIfAbsent(Double.doubleToLongBits(scale), ignored ->
new SeedTable<>(CHILD_SEED_CAPACITY, childSeed -> biome.createChildrenGenerator(childSeed, scale, runtime)))
.get(seed);
}
public KList<CNG> layerHeights(long seed) {
return layerHeights.get(seed);
}
public KList<CNG> seaLayerHeights(long seed) {
return seaLayerHeights.get(seed);
}
public KList<CNG> ceilingLayerHeights(long seed) {
return ceilingLayerHeights.get(seed);
}
/** The runtime of the surface layer at this index of {@link IrisBiome#getLayers()}. */
public PaletteLayerRuntime surfaceLayer(int index) {
return surfaceLayers.get(index);
}
/** The runtime of the sea layer at this index of {@link IrisBiome#getSeaLayers()}. */
public PaletteLayerRuntime seaLayer(int index) {
return seaLayers.get(index);
}
/** The runtime of the cave ceiling layer at this index of {@link IrisBiome#getCaveCeilingLayers()}. */
public PaletteLayerRuntime ceilingLayer(int index) {
return ceilingLayers.get(index);
}
/** The runtimes of this part's {@link IrisBiome#getDecoratorBucket} decorators, in bucket order. */
public DecoratorRuntime[] decorators(IrisDecorationPart part) {
IrisDecorator[] bucket = biome.getDecoratorBucket(part);
LinkedDecorators linked = decoratorBuckets.getAcquire(part.ordinal());
if (linked != null && linked.bucket() == bucket) {
return linked.runtimes();
}
DecoratorRuntime[] runtimes = new DecoratorRuntime[bucket.length];
for (int index = 0; index < bucket.length; index++) {
runtimes[index] = runtime.decorator(bucket[index]);
}
decoratorBuckets.setRelease(part.ordinal(), new LinkedDecorators(bucket, runtimes));
return runtimes;
}
private record LinkedDecorators(IrisDecorator[] bucket, DecoratorRuntime[] runtimes) {
}
private final class LinkedLayers {
private final Supplier<KList<IrisBiomePaletteLayer>> layers;
private volatile PaletteLayerRuntime[] linked;
private LinkedLayers(Supplier<KList<IrisBiomePaletteLayer>> layers) {
this.layers = layers;
}
private PaletteLayerRuntime get(int index) {
PaletteLayerRuntime[] current = linked;
if (current == null) {
current = link(layers.get());
linked = current;
}
return current[index];
}
private PaletteLayerRuntime[] link(KList<IrisBiomePaletteLayer> source) {
PaletteLayerRuntime[] result = new PaletteLayerRuntime[source.size()];
for (int index = 0; index < result.length; index++) {
result[index] = runtime.paletteLayer(source.get(index));
}
return result;
}
}
}
@@ -0,0 +1,57 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* 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 <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.generation.biome;
import art.arcane.iris.generation.cave.IrisCaveProfileSampler;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.SeedTable;
import java.util.Optional;
/**
* What one engine derives from an {@link IrisFloatingChildBiomes} entry: its edge taper profile per base seed and the
* cave profile sampler of the biome it carves with.
*/
public final class FloatingChildRuntime {
private static final int EDGE_PROFILE_SEED_CAPACITY = 8;
private final IrisFloatingChildBiomes entry;
private final PackRuntime runtime;
private final SeedTable<FloatingIslandEdgeProfile> edgeProfiles;
private volatile Optional<IrisCaveProfileSampler> carvingProfileSampler;
public FloatingChildRuntime(IrisFloatingChildBiomes entry, PackRuntime runtime) {
this.entry = entry;
this.runtime = runtime;
this.edgeProfiles = new SeedTable<>(EDGE_PROFILE_SEED_CAPACITY, seed -> entry.createEdgeTaperProfile(seed, runtime));
}
public FloatingIslandEdgeProfile edgeTaperProfile(long baseSeed) {
return edgeProfiles.get(baseSeed);
}
public IrisCaveProfileSampler carvingProfileSampler() {
Optional<IrisCaveProfileSampler> resolved = carvingProfileSampler;
if (resolved == null) {
resolved = Optional.ofNullable(entry.createCarvingProfileSampler(runtime));
carvingProfileSampler = resolved;
}
return resolved.orElse(null);
}
}
@@ -0,0 +1,67 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* 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 <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.generation.biome;
import java.util.HashMap;
/**
* One worker's floating island samples for the chunk it is generating. A runtime scope keeps one per worker thread,
* so the memo never outlives the engine that produced its samples.
*/
public final class FloatingIslandMemo {
private static final int CHUNK_COLUMN_COUNT = 256;
private final HashMap<Long, MemoizedSample> samples = new HashMap<>(CHUNK_COLUMN_COUNT);
private MemoContext context;
public void clear() {
samples.clear();
context = null;
}
/** The memoized sample for this column and parent, which may itself be null; null when not sampled yet. */
MemoizedSample find(IrisBiome parent, long column) {
MemoizedSample cached = samples.get(column);
return cached != null && cached.parent == parent ? cached : null;
}
void remember(IrisBiome parent, long column, FloatingIslandSample sample) {
samples.put(column, new MemoizedSample(parent, sample));
}
void enterChunk(int chunkX, int chunkZ, int height, long seed, FloatingIslandBoundarySampler boundarySampler) {
if (context != null && context.matches(chunkX, chunkZ, height, seed, boundarySampler)) {
return;
}
samples.clear();
context = new MemoContext(chunkX, chunkZ, height, seed, boundarySampler);
}
private record MemoContext(int chunkX, int chunkZ, int height, long seed,
FloatingIslandBoundarySampler boundarySampler) {
private boolean matches(int chunkX, int chunkZ, int height, long seed,
FloatingIslandBoundarySampler boundarySampler) {
return this.chunkX == chunkX && this.chunkZ == chunkZ && this.height == height && this.seed == seed
&& this.boundarySampler == boundarySampler;
}
}
record MemoizedSample(IrisBiome parent, FloatingIslandSample sample) {
}
}
@@ -20,16 +20,12 @@ package art.arcane.iris.generation.biome;
import art.arcane.iris.generation.cave.IrisCaveProfileSampler;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.volmlib.util.noise.CNG;
import art.arcane.volmlib.util.collection.KList;
import it.unimi.dsi.fastutil.longs.Long2DoubleOpenHashMap;
import java.util.Arrays;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
public final class FloatingIslandSample {
@@ -51,8 +47,6 @@ public final class FloatingIslandSample {
private static final double CARVE_MAX_VERTICAL_RUN_FRACTION = 0.18D;
private static final ThreadLocal<int[]> LAST_REJECT = ThreadLocal.withInitial(() -> new int[1]);
private static final ThreadLocal<double[]> LAST_DENSITY = ThreadLocal.withInitial(() -> new double[2]);
private static final ThreadLocal<ChunkMemo> CHUNK_MEMO = ThreadLocal.withInitial(ChunkMemo::new);
private static final ThreadLocal<IdentityHashMap<CNG, Long2DoubleOpenHashMap>> FOOTPRINT_MEMO = ThreadLocal.withInitial(IdentityHashMap::new);
private static final AtomicBoolean NULL_CNG_WARNED = new AtomicBoolean(false);
public static int getLastReject() {
@@ -67,33 +61,20 @@ public final class FloatingIslandSample {
return LAST_DENSITY.get()[1];
}
public static void clearThreadCaches() {
CHUNK_MEMO.remove();
FOOTPRINT_MEMO.remove();
LAST_REJECT.remove();
LAST_DENSITY.remove();
public static void clearChunkMemo(PackRuntime runtime) {
runtime.floatingIslandMemo().clear();
}
public static void clearChunkMemo() {
CHUNK_MEMO.get().samples.clear();
FOOTPRINT_MEMO.get().clear();
}
public static FloatingIslandSample sampleMemoized(IrisBiome parent, int wx, int wz, int chunkHeight, long baseSeed, IrisData data, Engine engine, FloatingIslandBoundarySampler boundarySampler) {
long key = (((long) wx) << 32) ^ (wz & 0xFFFFFFFFL);
ChunkMemo memo = CHUNK_MEMO.get();
if (memo.context == null || !memo.context.matches(wx >> 4, wz >> 4, chunkHeight, baseSeed,
data, engine, boundarySampler)) {
memo.samples.clear();
FOOTPRINT_MEMO.get().clear();
memo.context = new MemoContext(wx >> 4, wz >> 4, chunkHeight, baseSeed, data, engine, boundarySampler);
public static FloatingIslandSample sampleMemoized(IrisBiome parent, int wx, int wz, int chunkHeight, long baseSeed, PackRuntime runtime, FloatingIslandBoundarySampler boundarySampler) {
long column = (((long) wx) << 32) ^ (wz & 0xFFFFFFFFL);
FloatingIslandMemo memo = runtime.floatingIslandMemo();
memo.enterChunk(wx >> 4, wz >> 4, chunkHeight, baseSeed, boundarySampler);
FloatingIslandMemo.MemoizedSample cached = memo.find(parent, column);
if (cached != null) {
return cached.sample();
}
MemoizedSample cached = memo.samples.get(key);
if (cached != null && cached.parent == parent) {
return cached.sample;
}
FloatingIslandSample result = sample(parent, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler);
memo.samples.put(key, new MemoizedSample(parent, result));
FloatingIslandSample result = sample(parent, wx, wz, chunkHeight, baseSeed, runtime, boundarySampler);
memo.remember(parent, column, result);
return result;
}
@@ -184,18 +165,18 @@ public final class FloatingIslandSample {
}
private static int maximumEdgeFieldWidth(KList<IrisFloatingChildBiomes> entries, long baseSeed,
IrisData data, IrisBiome parent) {
PackRuntime runtime, IrisBiome parent) {
int maximumWidth = FloatingIslandEdgeProfile.MIN_WIDTH;
for (IrisFloatingChildBiomes entry : entries) {
FloatingIslandEdgeProfile profile = resolveEdgeProfile(entry, baseSeed, data, parent);
FloatingIslandEdgeProfile profile = resolveEdgeProfile(entry, baseSeed, runtime, parent);
maximumWidth = Math.max(maximumWidth, profile.fieldWidth());
}
return maximumWidth;
}
private static FloatingIslandEdgeProfile resolveEdgeProfile(IrisFloatingChildBiomes entry, long baseSeed,
IrisData data, IrisBiome parent) {
FloatingIslandEdgeProfile profile = entry.getEdgeTaperProfile(baseSeed, data);
PackRuntime runtime, IrisBiome parent) {
FloatingIslandEdgeProfile profile = entry.getEdgeTaperProfile(baseSeed, runtime);
if (profile != null) {
return profile;
}
@@ -203,17 +184,17 @@ public final class FloatingIslandSample {
return FloatingIslandEdgeProfile.DEFAULT;
}
public static FloatingIslandSample sample(IrisBiome parent, int wx, int wz, int chunkHeight, long baseSeed, IrisData data, Engine engine, FloatingIslandBoundarySampler boundarySampler) {
public static FloatingIslandSample sample(IrisBiome parent, int wx, int wz, int chunkHeight, long baseSeed, PackRuntime runtime, FloatingIslandBoundarySampler boundarySampler) {
KList<IrisFloatingChildBiomes> entries = parent.getFloatingChildBiomes();
if (entries == null || entries.isEmpty()) {
return reject(REJECT_NO_ENTRIES);
}
int boundaryFieldWidth = maximumEdgeFieldWidth(entries, baseSeed, data, parent);
int boundaryFieldWidth = maximumEdgeFieldWidth(entries, baseSeed, runtime, parent);
int parentBoundaryDistance = boundarySampler.edgeDistance(parent, wx, wz, boundaryFieldWidth);
if (parent.isMergeFloatingChildBiomes()) {
return sampleMerged(parent, entries, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler,
return sampleMerged(parent, entries, wx, wz, chunkHeight, baseSeed, runtime, boundarySampler,
parentBoundaryDistance, boundaryFieldWidth);
}
@@ -223,7 +204,7 @@ public final class FloatingIslandSample {
entry = entries.getFirst();
} else {
IrisFloatingChildBiomes reference = entries.getFirst();
CNG picker = reference.getPickerCng(baseSeed, data);
CNG picker = reference.getPickerCng(baseSeed, runtime);
if (picker == null) {
warnNullCng("pickerStyle", parent);
return reject(REJECT_NO_PICK);
@@ -237,20 +218,20 @@ public final class FloatingIslandSample {
ownershipBoundaryDistance = ownership.boundaryDistance();
}
return sampleEntry(parent, entry, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler,
return sampleEntry(parent, entry, wx, wz, chunkHeight, baseSeed, runtime, boundarySampler,
parentBoundaryDistance, ownershipBoundaryDistance);
}
private static FloatingIslandSample sampleMerged(IrisBiome parent, KList<IrisFloatingChildBiomes> entries,
int wx, int wz, int chunkHeight, long baseSeed, IrisData data,
Engine engine, FloatingIslandBoundarySampler boundarySampler,
int wx, int wz, int chunkHeight, long baseSeed, PackRuntime runtime,
FloatingIslandBoundarySampler boundarySampler,
int parentBoundaryDistance, int boundaryFieldWidth) {
KList<FloatingIslandSample> samples = new KList<>();
int minY = Integer.MAX_VALUE;
int maxY = Integer.MIN_VALUE;
for (IrisFloatingChildBiomes entry : entries) {
FloatingIslandSample sample = sampleEntry(parent, entry, wx, wz, chunkHeight, baseSeed, data, engine,
FloatingIslandSample sample = sampleEntry(parent, entry, wx, wz, chunkHeight, baseSeed, runtime,
boundarySampler, parentBoundaryDistance, boundaryFieldWidth + 1);
if (sample == null) {
continue;
@@ -313,11 +294,11 @@ public final class FloatingIslandSample {
}
private static FloatingIslandSample sampleEntry(IrisBiome parent, IrisFloatingChildBiomes entry, int wx, int wz,
int chunkHeight, long baseSeed, IrisData data, Engine engine,
int chunkHeight, long baseSeed, PackRuntime runtime,
FloatingIslandBoundarySampler boundarySampler,
int parentBoundaryDistance, int ownershipBoundaryDistance) {
FloatingIslandEdgeProfile edgeProfile = resolveEdgeProfile(entry, baseSeed, data, parent);
CNG footprintCng = entry.getFootprintCng(baseSeed, data);
FloatingIslandEdgeProfile edgeProfile = resolveEdgeProfile(entry, baseSeed, runtime, parent);
CNG footprintCng = entry.getFootprintCng(baseSeed, runtime);
if (footprintCng == null) {
warnNullCng("footprintStyle", parent);
return reject(REJECT_NO_SEED);
@@ -343,23 +324,23 @@ public final class FloatingIslandSample {
return reject(REJECT_NO_THICKNESS);
}
CNG altitudeCng = entry.getAltitudeCng(baseSeed, data);
CNG altitudeCng = entry.getAltitudeCng(baseSeed, runtime);
if (altitudeCng == null) {
warnNullCng("altitudeStyle", parent);
return reject(REJECT_NO_SEED);
}
double altNoise = altitudeCng.noise(wx, wz);
double altClamped = Math.max(0, Math.min(1, altNoise));
int worldMin = engine.getWorld().minHeight();
int worldMin = runtime.engine().getWorld().minHeight();
int minAlt = Math.max(0, entry.getMinHeightAboveSurface() - worldMin);
int maxAlt = Math.max(minAlt, entry.getMaxHeightAboveSurface() - worldMin);
int baseY = minAlt + (int) Math.round(altClamped * (maxAlt - minAlt));
IrisBiome target = entry.getRealBiome(parent, data);
int fullTopHeight = computeTopHeight(entry, target, engine, baseSeed, wx, wz, data);
IrisBiome target = entry.getRealBiome(parent, runtime.data());
int fullTopHeight = computeTopHeight(entry, target, runtime, baseSeed, wx, wz);
int topH = roundedEdgeHeight(fullTopHeight, edgeFade);
CNG bottomCng = entry.getBottomCng(baseSeed, data);
CNG bottomCng = entry.getBottomCng(baseSeed, runtime);
if (bottomCng == null) {
warnNullCng("bottomStyle", parent);
return reject(REJECT_NO_SEED);
@@ -416,11 +397,11 @@ public final class FloatingIslandSample {
}
boolean[] solidMask = new boolean[thickness];
CNG wallWarp = entry.getWallWarpCng(baseSeed, data);
CNG wallWarp = entry.getWallWarpCng(baseSeed, runtime);
double warpAmp = Math.max(0, entry.getWallWarpAmplitude());
double effectiveWarpAmp = effectiveWallWarpAmplitude(warpAmp, edgeFade);
IrisCaveProfileSampler carvingProfileSampler = entry.getCarvingProfileSampler(engine, data);
CNG carve = carvingProfileSampler == null && !entry.hasCarvingReference() ? entry.getCarveCng(baseSeed, data) : null;
IrisCaveProfileSampler carvingProfileSampler = entry.getCarvingProfileSampler(runtime);
CNG carve = carvingProfileSampler == null && !entry.hasCarvingReference() ? entry.getCarveCng(baseSeed, runtime) : null;
double carveThreshold = entry.getCarveThreshold();
boolean useWarp = wallWarp != null && effectiveWarpAmp > 0;
boolean useProfileCarve = carvingProfileSampler != null;
@@ -683,27 +664,7 @@ public final class FloatingIslandSample {
}
private static double footprintSigned(CNG footprintCng, int wx, int wz) {
IdentityHashMap<CNG, Long2DoubleOpenHashMap> memoByCng = FOOTPRINT_MEMO.get();
Long2DoubleOpenHashMap memo = memoByCng.get(footprintCng);
if (memo == null) {
memo = new Long2DoubleOpenHashMap(512);
memo.defaultReturnValue(Double.NaN);
memoByCng.put(footprintCng, memo);
}
long key = columnKey(wx, wz);
double cached = memo.get(key);
if (!Double.isNaN(cached)) {
return cached;
}
double signed = signedFromUnit(footprintCng.noise(wx, wz));
memo.put(key, signed);
return signed;
}
private static long columnKey(int wx, int wz) {
return ((long) wx << 32) ^ (wz & 0xFFFFFFFFL);
return signedFromUnit(footprintCng.noise(wx, wz));
}
private static double signedFromUnit(double value) {
@@ -779,7 +740,7 @@ public final class FloatingIslandSample {
}
}
private static int computeTopHeight(IrisFloatingChildBiomes entry, IrisBiome target, Engine engine, long baseSeed, int wx, int wz, IrisData data) {
private static int computeTopHeight(IrisFloatingChildBiomes entry, IrisBiome target, PackRuntime runtime, long baseSeed, int wx, int wz) {
int maxTopHeight = Math.max(0, entry.getMaxTopHeight());
if (maxTopHeight == 0) {
return 0;
@@ -787,7 +748,7 @@ public final class FloatingIslandSample {
return switch (entry.getTopShapeMode()) {
case FLAT -> maxTopHeight;
case NOISE -> {
CNG topCng = entry.getTopShapeCng(baseSeed, data);
CNG topCng = entry.getTopShapeCng(baseSeed, runtime);
if (topCng == null) {
warnNullCng("topShapeStyle", null);
yield maxTopHeight / 2;
@@ -801,7 +762,7 @@ public final class FloatingIslandSample {
if (target == null) {
yield maxTopHeight / 2;
}
double h = target.getHeight(engine, wx, wz, baseSeed);
double h = target.getHeight(runtime, wx, wz, baseSeed);
int rounded = (int) Math.round(h);
if (rounded < 0) {
yield 0;
@@ -810,21 +771,4 @@ public final class FloatingIslandSample {
}
};
}
private static final class ChunkMemo {
private final HashMap<Long, MemoizedSample> samples = new HashMap<>(256);
private MemoContext context;
}
private record MemoContext(int chunkX, int chunkZ, int height, long seed, IrisData data, Engine engine,
FloatingIslandBoundarySampler boundarySampler) {
private boolean matches(int chunkX, int chunkZ, int height, long seed, IrisData data, Engine engine,
FloatingIslandBoundarySampler boundarySampler) {
return this.chunkX == chunkX && this.chunkZ == chunkZ && this.height == height && this.seed == seed
&& this.data == data && this.engine == engine && this.boundarySampler == boundarySampler;
}
}
private record MemoizedSample(IrisBiome parent, FloatingIslandSample sample) {
}
}
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.biome;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.cave.IrisCaveProfile;
import art.arcane.iris.generation.decoration.IrisDecorationPart;
import art.arcane.iris.generation.decoration.IrisDecorator;
@@ -29,7 +30,6 @@ import art.arcane.iris.generation.decoration.IrisProceduralObjects;
import art.arcane.iris.generation.hydrology.config.IrisHydrologyPolicy;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.NoiseStyle;
import art.arcane.iris.generation.runtime.EngineRef;
import art.arcane.iris.generation.terrain.InferredType;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.terrain.IrisTerrain3D;
@@ -48,7 +48,6 @@ import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.pack.loading.IrisRegistrant;
import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.volmlib.util.cache.AtomicCache;
import art.arcane.iris.generation.cache.LazyBoundedCache;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.pack.schema.annotation.ArrayType;
import art.arcane.iris.pack.schema.annotation.DependsOn;
@@ -64,7 +63,6 @@ import art.arcane.volmlib.util.collection.KSet;
import art.arcane.iris.generation.block.DataProvider;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG;
import art.arcane.iris.generation.context.IrisContext;
import art.arcane.volmlib.util.stream.ProceduralStream;
import lombok.AccessLevel;
import lombok.Data;
@@ -94,7 +92,6 @@ import java.util.Objects;
@EqualsAndHashCode(callSuper = false)
public class IrisBiome extends IrisRegistrant implements Rarity {
public static final int CHILD_HOPS = 4;
private static final int BIOME_GENERATOR_CACHE_SIZE = 8;
private static final int CHILDREN_SEED_SALT = 2137;
private final transient AtomicCache<KMap<String, IrisBiomeGeneratorLink>> genCache = new AtomicCache<>();
@@ -105,25 +102,10 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
private final transient AtomicCache<Color> cacheColorDecoratorLoad = new AtomicCache<>();
private final transient AtomicCache<Color> cacheColorLayerLoad = new AtomicCache<>();
private final transient AtomicCache<Color> cacheColorDepositLoad = new AtomicCache<>();
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient LazyBoundedCache<ChildGeneratorKey, CNG> childrenGenerators = new LazyBoundedCache<>(8);
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private transient volatile CachedChildGenerator recentChildGenerator;
@Getter(AccessLevel.NONE)
private final transient LazyBoundedCache<Long, CNG> biomeGenerators =
new LazyBoundedCache<>(BIOME_GENERATOR_CACHE_SIZE);
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private transient volatile SeededBiomeGenerator recentBiomeGenerator;
private final transient AtomicCache<Integer> maxHeight = new AtomicCache<>();
private final transient AtomicCache<Integer> maxWithObjectHeight = new AtomicCache<>();
private final transient AtomicCache<IrisBiome> realCarveBiome = new AtomicCache<>();
private final transient AtomicCache<KList<IrisBiome>> realChildren = new AtomicCache<>();
private final transient IrisBiomeLayerHeightCache layerHeightGenerators = new IrisBiomeLayerHeightCache();
private final transient IrisBiomeLayerHeightCache layerCeilingHeightGenerators = new IrisBiomeLayerHeightCache();
private final transient IrisBiomeLayerHeightCache layerSeaHeightGenerators = new IrisBiomeLayerHeightCache();
private final transient AtomicCache<KList<IrisOreGenerator>> surfaceOreCache = new AtomicCache<>();
private final transient AtomicCache<KList<IrisOreGenerator>> undergroundOreCache = new AtomicCache<>();
private final transient AtomicCache<IrisOreBands> surfaceOreBandsCache = new AtomicCache<>();
@@ -275,16 +257,16 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
return IrisBiomeOres.canReplaceSurfaceOre(this, state);
}
public NativeBlockState generateOres(int x, int y, int z, RNG rng, IrisData data, boolean surface) {
return IrisBiomeOres.generateOres(this, x, y, z, rng, data, surface);
public NativeBlockState generateOres(int x, int y, int z, RNG rng, PackRuntime runtime, boolean surface) {
return IrisBiomeOres.generateOres(this, x, y, z, rng, runtime, surface);
}
public NativeBlockState generateSurfaceOres(int x, int y, int z, RNG rng, IrisData data) {
return IrisBiomeOres.generateSurfaceOres(this, x, y, z, rng, data);
public NativeBlockState generateSurfaceOres(int x, int y, int z, RNG rng, PackRuntime runtime) {
return IrisBiomeOres.generateSurfaceOres(this, x, y, z, rng, runtime);
}
public NativeBlockState generateUndergroundOres(int x, int y, int z, RNG rng, IrisData data) {
return IrisBiomeOres.generateUndergroundOres(this, x, y, z, rng, data);
public NativeBlockState generateUndergroundOres(int x, int y, int z, RNG rng, PackRuntime runtime) {
return IrisBiomeOres.generateUndergroundOres(this, x, y, z, rng, runtime);
}
public boolean hasSurfaceOres() {
@@ -470,68 +452,37 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
});
}
public double getHeight(Engine xg, double x, double z, long seed) {
public double getHeight(PackRuntime runtime, double x, double z, long seed) {
double height = 0;
for (IrisBiomeGeneratorLink i : generators) {
height += i.getHeight(xg, x, z, seed);
height += i.getHeight(runtime, x, z, seed);
}
return Math.max(0, Math.min(height, xg.getHeight()));
}
public CNG getBiomeGenerator(RNG random) {
IrisData loader = getLoader();
Engine engine = resolveBiomeGeneratorEngine(loader);
return getBiomeGenerator(random, engine);
return Math.max(0, Math.min(height, runtime.engine().getHeight()));
}
/** Engines seed the scatter generator from their own biome seed; engine-less tools use the caller's seed. */
public CNG getBiomeGenerator(RNG random, Engine engine) {
IrisData loader = getLoader();
long seed = engine == null ? random.getSeed() : engine.getSeedManager().getBiome();
SeededBiomeGenerator recent = recentBiomeGenerator;
if (recent != null && recent.seed == seed) {
return recent.generator;
}
CNG generator = biomeGenerators.computeIfAbsent(seed, ignored -> createBiomeGenerator(seed, loader));
recentBiomeGenerator = new SeededBiomeGenerator(seed, generator);
return generator;
return PackRuntime.of(engine, getLoader()).biome(this).biomeGenerator(seed);
}
private Engine resolveBiomeGeneratorEngine(IrisData loader) {
IrisContext context = IrisContext.get();
if (context != null) {
Engine contextEngine = context.getEngine();
if (!contextEngine.isClosed() && (loader == null || contextEngine.getData() == loader)) {
return contextEngine;
}
}
return loader == null ? null : loader.getEngine();
}
private CNG createBiomeGenerator(long seed, IrisData loader) {
CNG createBiomeGenerator(long seed, PackRuntime runtime) {
int signature = 213949 + 228888 + getRarity() + getName().length();
return biomeStyle.createNoCache(new RNG(seed).nextParallelRNG(signature), loader);
return biomeStyle.createNoCache(new RNG(seed).nextParallelRNG(signature), runtime);
}
public CNG getChildrenGenerator(RNG random, int sig, double scale) {
return getChildrenGenerator(deriveChildStyleSeed(random, sig).getSeed(), scale);
public CNG getChildrenGenerator(PackRuntime runtime, RNG random, int sig, double scale) {
return getChildrenGenerator(runtime, deriveChildStyleSeed(random, sig).getSeed(), scale);
}
public CNG getChildrenGenerator(long seed, double scale) {
IrisData data = getLoader();
Engine engine = data == null ? null : data.getEngine();
CachedChildGenerator recent = recentChildGenerator;
if (recent != null && recent.key.matches(seed, scale, data, engine)) {
return recent.generator;
}
ChildGeneratorKey key = new ChildGeneratorKey(seed, scale, data, EngineRef.of(engine));
CNG generator = childrenGenerators.computeIfAbsent(key,
ignored -> getChildStyle().createScaledGenerator(new RNG(seed), data, scale));
recentChildGenerator = new CachedChildGenerator(key, generator);
return generator;
public CNG getChildrenGenerator(PackRuntime runtime, long seed, double scale) {
return runtime.biome(this).childrenGenerator(seed, scale);
}
CNG createChildrenGenerator(long seed, double scale, PackRuntime runtime) {
return getChildStyle().createScaledGenerator(new RNG(seed), runtime, scale);
}
static RNG deriveChildStyleSeed(RNG random, int signature) {
@@ -542,24 +493,24 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
return deriveChildStyleSeed(random, signature).getSeed();
}
public KList<NativeBlockState> generateLayers(IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, IrisComplex complex) {
return IrisBiomeLayerGenerator.generateLayers(this, dim, wx, wz, random, maxDepth, height, rdata, complex);
public KList<NativeBlockState> generateLayers(IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, PackRuntime runtime, IrisComplex complex) {
return IrisBiomeLayerGenerator.generateLayers(this, dim, wx, wz, random, maxDepth, height, runtime, complex);
}
public KList<NativeBlockState> generateLayersWithSlope(IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, ProceduralStream<Double> slopeStream) {
return IrisBiomeLayerGenerator.generateLayers(this, dim, wx, wz, random, maxDepth, height, rdata, slopeStream);
public KList<NativeBlockState> generateLayersWithSlope(IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, PackRuntime runtime, ProceduralStream<Double> slopeStream) {
return IrisBiomeLayerGenerator.generateLayers(this, dim, wx, wz, random, maxDepth, height, runtime, slopeStream);
}
public KList<NativeBlockState> generateCeilingLayers(IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, IrisComplex complex) {
return IrisBiomeLayerGenerator.generateCeilingLayers(this, dim, wx, wz, random, maxDepth, height, rdata, complex);
public KList<NativeBlockState> generateCeilingLayers(IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, PackRuntime runtime, IrisComplex complex) {
return IrisBiomeLayerGenerator.generateCeilingLayers(this, dim, wx, wz, random, maxDepth, height, runtime, complex);
}
public KList<NativeBlockState> generateLockedLayers(double wx, double wz, RNG random, int maxDepthf, int height, IrisData rdata, IrisComplex complex) {
return IrisBiomeLayerGenerator.generateLockedLayers(this, wx, wz, random, maxDepthf, height, rdata, complex);
public KList<NativeBlockState> generateLockedLayers(double wx, double wz, RNG random, int maxDepthf, int height, PackRuntime runtime, IrisComplex complex) {
return IrisBiomeLayerGenerator.generateLockedLayers(this, wx, wz, random, maxDepthf, height, runtime, complex);
}
public KList<NativeBlockState> generateSeaLayers(double wx, double wz, RNG random, int maxDepth, IrisData rdata) {
return IrisBiomeLayerGenerator.generateSeaLayers(this, wx, wz, random, maxDepth, rdata);
public KList<NativeBlockState> generateSeaLayers(double wx, double wz, RNG random, int maxDepth, PackRuntime runtime) {
return IrisBiomeLayerGenerator.generateSeaLayers(this, wx, wz, random, maxDepth, runtime);
}
/**
@@ -574,20 +525,20 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
return IrisBiomeLayerGenerator.getMaxWithObjectHeight(this, data, engine);
}
public KList<CNG> getLayerHeightGenerators(RNG rng, IrisData rdata) {
return IrisBiomeLayerGenerator.getLayerHeightGenerators(this, rng, rdata);
public KList<CNG> getLayerHeightGenerators(RNG rng, PackRuntime runtime) {
return runtime.biome(this).layerHeights(rng.getSeed());
}
public KList<CNG> getLayerSeaHeightGenerators(RNG rng, IrisData data) {
return IrisBiomeLayerGenerator.getLayerSeaHeightGenerators(this, rng, data);
public KList<CNG> getLayerSeaHeightGenerators(RNG rng, PackRuntime runtime) {
return runtime.biome(this).seaLayerHeights(rng.getSeed());
}
public KList<CNG> getCaveCeilingLayerHeightGenerators(RNG rng, IrisData data) {
return IrisBiomeLayerGenerator.getCaveCeilingLayerHeightGenerators(this, rng, data);
public KList<CNG> getCaveCeilingLayerHeightGenerators(RNG rng, PackRuntime runtime) {
return runtime.biome(this).ceilingLayerHeights(rng.getSeed());
}
public NativeBlockState getSurfaceBlock(int x, int z, RNG rng, IrisData idm) {
return IrisBiomeLayerGenerator.getSurfaceBlock(this, x, z, rng, idm);
public NativeBlockState getSurfaceBlock(int x, int z, RNG rng, PackRuntime runtime) {
return IrisBiomeLayerGenerator.getSurfaceBlock(this, x, z, rng, runtime);
}
public boolean isLand() {
@@ -617,18 +568,10 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
return inferredType.equals(InferredType.SHORE);
}
public Biome getSkyBiome(RNG rng, double x, double y, double z) {
return IrisBiomeDerivatives.getSkyBiome(this, rng, resolveBiomeGeneratorEngine(getLoader()), x, y, z);
}
public Biome getSkyBiome(RNG rng, Engine engine, double x, double y, double z) {
return IrisBiomeDerivatives.getSkyBiome(this, rng, engine, x, y, z);
}
public IrisBiomeCustom getCustomBiome(RNG rng, double x, double y, double z) {
return IrisBiomeDerivatives.getCustomBiome(this, rng, resolveBiomeGeneratorEngine(getLoader()), x, y, z);
}
public IrisBiomeCustom getCustomBiome(RNG rng, Engine engine, double x, double y, double z) {
return IrisBiomeDerivatives.getCustomBiome(this, rng, engine, x, y, z);
}
@@ -657,27 +600,14 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
return new KList<>(m);
}
//TODO: Test
public Biome getGroundBiome(RNG rng, double x, double y, double z) {
return IrisBiomeDerivatives.getGroundBiome(this, rng, resolveBiomeGeneratorEngine(getLoader()), x, y, z);
}
public Biome getGroundBiome(RNG rng, Engine engine, double x, double y, double z) {
return IrisBiomeDerivatives.getGroundBiome(this, rng, engine, x, y, z);
}
public String getSkyBiomeKey(RNG rng, double x, double y, double z) {
return IrisBiomeDerivatives.getSkyBiomeKey(this, rng, resolveBiomeGeneratorEngine(getLoader()), x, y, z);
}
public String getSkyBiomeKey(RNG rng, Engine engine, double x, double y, double z) {
return IrisBiomeDerivatives.getSkyBiomeKey(this, rng, engine, x, y, z);
}
public String getGroundBiomeKey(RNG rng, double x, double y, double z) {
return IrisBiomeDerivatives.getGroundBiomeKey(this, rng, resolveBiomeGeneratorEngine(getLoader()), x, y, z);
}
public String getGroundBiomeKey(RNG rng, Engine engine, double x, double y, double z) {
return IrisBiomeDerivatives.getGroundBiomeKey(this, rng, engine, x, y, z);
}
@@ -715,41 +645,4 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
public String getTypeName() {
return "Biome";
}
private static final class SeededBiomeGenerator {
private final long seed;
private final CNG generator;
private SeededBiomeGenerator(long seed, CNG generator) {
this.seed = seed;
this.generator = generator;
}
}
private record ChildGeneratorKey(long seed, double scale, IrisData data, EngineRef engine) {
private boolean matches(long seed, double scale, IrisData data, Engine engine) {
return this.seed == seed && Double.doubleToLongBits(this.scale) == Double.doubleToLongBits(scale)
&& this.data == data && this.engine.refersTo(engine);
}
@Override
public boolean equals(Object object) {
return object instanceof ChildGeneratorKey other
&& seed == other.seed
&& Double.doubleToLongBits(scale) == Double.doubleToLongBits(other.scale)
&& data == other.data
&& engine.equals(other.engine);
}
@Override
public int hashCode() {
int hash = Long.hashCode(seed);
hash = 31 * hash + Double.hashCode(scale);
hash = 31 * hash + System.identityHashCode(data);
return 31 * hash + engine.hashCode();
}
}
private record CachedChildGenerator(ChildGeneratorKey key, CNG generator) {
}
}
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.biome;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.noise.IrisGenerator;
import art.arcane.volmlib.util.cache.AtomicCache;
@@ -81,8 +82,8 @@ public class IrisBiomeGeneratorLink {
});
}
public double getHeight(DataProvider xg, double x, double z, long seed) {
double g = getCachedGenerator(xg).getHeight(x, z, seed);
public double getHeight(PackRuntime runtime, double x, double z, long seed) {
double g = getCachedGenerator(runtime::data).getHeight(runtime, x, z, seed);
g = g < 0 ? 0 : g;
g = g > 1 ? 1 : g;
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.biome;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.terrain.IrisSlopeClip;
import art.arcane.iris.structure.object.IrisObject;
@@ -45,18 +46,18 @@ final class IrisBiomeLayerGenerator {
private IrisBiomeLayerGenerator() {
}
static KList<NativeBlockState> generateLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, IrisComplex complex) {
return generateLayers(biome, dim, wx, wz, random, maxDepth, height, rdata, complex, null);
static KList<NativeBlockState> generateLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, PackRuntime runtime, IrisComplex complex) {
return generateLayers(biome, dim, wx, wz, random, maxDepth, height, runtime, complex, null);
}
static KList<NativeBlockState> generateLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, ProceduralStream<Double> slopeStream) {
return generateLayers(biome, dim, wx, wz, random, maxDepth, height, rdata, null, slopeStream);
static KList<NativeBlockState> generateLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, PackRuntime runtime, ProceduralStream<Double> slopeStream) {
return generateLayers(biome, dim, wx, wz, random, maxDepth, height, runtime, null, slopeStream);
}
private static KList<NativeBlockState> generateLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, IrisComplex complex, ProceduralStream<Double> slopeStream) {
private static KList<NativeBlockState> generateLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, PackRuntime runtime, IrisComplex complex, ProceduralStream<Double> slopeStream) {
if (biome.isLockLayers()) {
KList<NativeBlockState> data = generateLockedLayers(biome, wx, wz, random, maxDepth, height, rdata, complex, slopeStream);
appendSurfaceFallback(data, biome, dim, wx, wz, random, Math.min(maxDepth, biome.getLockLayersMax()), rdata);
KList<NativeBlockState> data = generateLockedLayers(biome, wx, wz, random, maxDepth, height, runtime, complex, slopeStream);
appendSurfaceFallback(data, biome, dim, wx, wz, random, Math.min(maxDepth, biome.getLockLayersMax()), runtime);
return data;
}
@@ -73,7 +74,8 @@ final class IrisBiomeLayerGenerator {
return data;
}
KList<CNG> heightGenerators = getLayerHeightGenerators(biome, random, rdata);
BiomeRuntime biomeRuntime = runtime.biome(biome);
KList<CNG> heightGenerators = biomeRuntime.layerHeights(random.getSeed());
double surfaceSlope = 0D;
boolean sampledSlope = false;
@@ -98,7 +100,7 @@ final class IrisBiomeLayerGenerator {
continue;
}
appendLayer(data, layer, i, d, wx, wz, random, maxDepth, rdata);
appendLayer(data, layer, biomeRuntime.surfaceLayer(i), i, d, wx, wz, random, maxDepth);
if (data.size() >= maxDepth) {
break;
@@ -115,12 +117,12 @@ final class IrisBiomeLayerGenerator {
}
}
appendSurfaceFallback(data, biome, dim, wx, wz, random, maxDepth, rdata);
appendSurfaceFallback(data, biome, dim, wx, wz, random, maxDepth, runtime);
return data;
}
private static void appendSurfaceFallback(KList<NativeBlockState> data, IrisBiome biome, IrisDimension dim,
double wx, double wz, RNG random, int maxDepth, IrisData rdata) {
double wx, double wz, RNG random, int maxDepth, PackRuntime runtime) {
if (!data.isEmpty() || maxDepth <= 0 || biome.getLayers().isEmpty()) {
return;
}
@@ -129,11 +131,11 @@ final class IrisBiomeLayerGenerator {
fallback = dim.getSurfaceLayerFallback();
}
if (fallback == IrisSurfaceLayerFallback.TOP_LAYER) {
appendLayer(data, biome.getLayers().get(0), 0, 1, wx, wz, random, maxDepth, rdata);
appendLayer(data, biome.getLayers().get(0), runtime.biome(biome).surfaceLayer(0), 0, 1, wx, wz, random, maxDepth);
}
}
static KList<NativeBlockState> generateCeilingLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, IrisComplex complex) {
static KList<NativeBlockState> generateCeilingLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, PackRuntime runtime, IrisComplex complex) {
KList<NativeBlockState> data = new KList<>();
if (maxDepth <= 0) {
@@ -147,7 +149,8 @@ final class IrisBiomeLayerGenerator {
return data;
}
KList<CNG> heightGenerators = getCaveCeilingLayerHeightGenerators(biome, random, rdata);
BiomeRuntime biomeRuntime = runtime.biome(biome);
KList<CNG> heightGenerators = biomeRuntime.ceilingLayerHeights(random.getSeed());
for (int i = 0; i < layerCount; i++) {
IrisBiomePaletteLayer layer = ceilingLayers.get(i);
@@ -159,7 +162,7 @@ final class IrisBiomeLayerGenerator {
continue;
}
appendLayer(data, layer, i, d, wx, wz, random, maxDepth, rdata);
appendLayer(data, layer, biomeRuntime.ceilingLayer(i), i, d, wx, wz, random, maxDepth);
if (data.size() >= maxDepth) {
break;
@@ -179,11 +182,11 @@ final class IrisBiomeLayerGenerator {
return data;
}
static KList<NativeBlockState> generateLockedLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepthf, int height, IrisData rdata, IrisComplex complex) {
return generateLockedLayers(biome, wx, wz, random, maxDepthf, height, rdata, complex, null);
static KList<NativeBlockState> generateLockedLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepthf, int height, PackRuntime runtime, IrisComplex complex) {
return generateLockedLayers(biome, wx, wz, random, maxDepthf, height, runtime, complex, null);
}
private static KList<NativeBlockState> generateLockedLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepthf, int height, IrisData rdata, IrisComplex complex, ProceduralStream<Double> slopeStream) {
private static KList<NativeBlockState> generateLockedLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepthf, int height, PackRuntime runtime, IrisComplex complex, ProceduralStream<Double> slopeStream) {
KList<NativeBlockState> data = new KList<>();
int maxDepth = Math.min(maxDepthf, biome.getLockLayersMax());
KList<IrisBiomePaletteLayer> layers = biome.getLayers();
@@ -192,7 +195,8 @@ final class IrisBiomeLayerGenerator {
return data;
}
KList<CNG> heightGenerators = getLayerHeightGenerators(biome, random, rdata);
BiomeRuntime biomeRuntime = runtime.biome(biome);
KList<CNG> heightGenerators = biomeRuntime.layerHeights(random.getSeed());
int[] boundaries = new int[layerCount + 1];
double surfaceSlope = 0D;
boolean sampledSlope = false;
@@ -230,7 +234,7 @@ final class IrisBiomeLayerGenerator {
double zoom = layer.getZoom();
try {
data.add(layer.get(random, layerIndex + offset,
(wx + offset) / zoom, offset, (wz - offset) / zoom, rdata));
(wx + offset) / zoom, offset, (wz - offset) / zoom, biomeRuntime.surfaceLayer(layerIndex)));
} catch (Throwable error) {
GenerationFailures.skipPlacement(error, "surface layer", "block", (int) wx, height - depth, (int) wz, biome.getLoadKey());
}
@@ -274,7 +278,7 @@ final class IrisBiomeLayerGenerator {
: complex.getSlopeStream().getDouble(x, z);
}
static KList<NativeBlockState> generateSeaLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepth, IrisData rdata) {
static KList<NativeBlockState> generateSeaLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepth, PackRuntime runtime) {
KList<NativeBlockState> data = new KList<>();
KList<IrisBiomePaletteLayer> seaLayers = biome.getSeaLayers();
@@ -284,7 +288,8 @@ final class IrisBiomeLayerGenerator {
return data;
}
KList<CNG> heightGenerators = getLayerSeaHeightGenerators(biome, random, rdata);
BiomeRuntime biomeRuntime = runtime.biome(biome);
KList<CNG> heightGenerators = biomeRuntime.seaLayerHeights(random.getSeed());
for (int i = 0; i < layerCount; i++) {
IrisBiomePaletteLayer layer = seaLayers.get(i);
@@ -296,7 +301,7 @@ final class IrisBiomeLayerGenerator {
continue;
}
appendLayer(data, layer, i, d, wx, wz, random, maxDepth, rdata);
appendLayer(data, layer, biomeRuntime.seaLayer(i), i, d, wx, wz, random, maxDepth);
if (data.size() >= maxDepth) {
break;
@@ -306,46 +311,51 @@ final class IrisBiomeLayerGenerator {
return data;
}
static KList<CNG> getLayerHeightGenerators(IrisBiome biome, RNG rng, IrisData rdata) {
return getHeightGenerators(biome.getLayerHeightGenerators(), biome.getLayers(), 7235, rng, rdata);
static KList<CNG> getLayerHeightGenerators(IrisBiome biome, RNG rng, PackRuntime runtime) {
return runtime.biome(biome).layerHeights(rng.getSeed());
}
static KList<CNG> getLayerSeaHeightGenerators(IrisBiome biome, RNG rng, IrisData data) {
return getHeightGenerators(biome.getLayerSeaHeightGenerators(), biome.getSeaLayers(), 7735, rng, data);
static KList<CNG> getLayerSeaHeightGenerators(IrisBiome biome, RNG rng, PackRuntime runtime) {
return runtime.biome(biome).seaLayerHeights(rng.getSeed());
}
static KList<CNG> getCaveCeilingLayerHeightGenerators(IrisBiome biome, RNG rng, IrisData data) {
return getHeightGenerators(biome.getLayerCeilingHeightGenerators(), biome.getCaveCeilingLayers(), 7235, rng, data);
static KList<CNG> getCaveCeilingLayerHeightGenerators(IrisBiome biome, RNG rng, PackRuntime runtime) {
return runtime.biome(biome).ceilingLayerHeights(rng.getSeed());
}
private static KList<CNG> getHeightGenerators(IrisBiomeLayerHeightCache cache,
KList<IrisBiomePaletteLayer> layers,
int seedOffset, RNG rng, IrisData data) {
return cache.get(layers, seedOffset, rng, data);
static KList<CNG> createHeightGenerators(KList<IrisBiomePaletteLayer> layers, int seedOffset, long seed,
PackRuntime runtime) {
RNG rng = new RNG(seed);
KList<CNG> result = new KList<>();
int offset = seedOffset;
for (IrisBiomePaletteLayer layer : layers) {
result.add(layer.getHeightGenerator(rng.nextParallelRNG((offset++) * offset * offset * offset), runtime));
}
return result;
}
private static void appendLayer(KList<NativeBlockState> blocks, IrisBiomePaletteLayer layer,
int layerIndex, int thickness, double x, double z,
RNG random, int maxDepth, IrisData data) {
PaletteLayerRuntime layerRuntime, int layerIndex, int thickness, double x, double z,
RNG random, int maxDepth) {
double zoom = layer.getZoom();
for (int offset = 0; offset < thickness && blocks.size() < maxDepth; offset++) {
try {
blocks.add(layer.get(random, layerIndex + offset,
(x + offset) / zoom, offset, (z - offset) / zoom, data));
(x + offset) / zoom, offset, (z - offset) / zoom, layerRuntime));
} catch (Throwable error) {
GenerationFailures.skipPlacement(error, "surface layer", "block", (int) x, -1, (int) z, "none");
}
}
}
static NativeBlockState getSurfaceBlock(IrisBiome biome, int x, int z, RNG rng, IrisData idm) {
static NativeBlockState getSurfaceBlock(IrisBiome biome, int x, int z, RNG rng, PackRuntime runtime) {
KList<IrisBiomePaletteLayer> layers = biome.getLayers();
if (layers.isEmpty()) {
return B.getState("AIR");
}
return layers.get(0).get(rng, x, 0, z, idm);
return layers.get(0).get(rng, x, 0, z, runtime);
}
static int getMaxHeight(IrisBiome biome, Engine engine) {
@@ -1,69 +0,0 @@
package art.arcane.iris.generation.biome;
import art.arcane.iris.generation.cache.LazyBoundedCache;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.EngineRef;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG;
final class IrisBiomeLayerHeightCache {
private final LazyBoundedCache<GeneratorKey, KList<CNG>> generators = new LazyBoundedCache<>(32);
private volatile CachedGenerators recent;
KList<CNG> get(KList<IrisBiomePaletteLayer> layers, int seedOffset, RNG rng, IrisData data) {
Engine engine = data == null ? null : data.getEngine();
long seed = rng.getSeed();
CachedGenerators cached = recent;
if (cached != null && cached.key.matches(data, engine, seed)) {
return cached.generators;
}
GeneratorKey key = new GeneratorKey(data, engine, seed);
KList<CNG> result = generators.computeIfAbsent(key, ignored -> create(layers, seedOffset, rng, data));
recent = new CachedGenerators(key, result);
return result;
}
private static KList<CNG> create(KList<IrisBiomePaletteLayer> layers, int seedOffset, RNG rng, IrisData data) {
KList<CNG> result = new KList<>();
int offset = seedOffset;
for (IrisBiomePaletteLayer layer : layers) {
result.add(layer.getHeightGenerator(rng.nextParallelRNG((offset++) * offset * offset * offset), data));
}
return result;
}
private record CachedGenerators(GeneratorKey key, KList<CNG> generators) {
}
private static final class GeneratorKey {
private final IrisData data;
private final EngineRef engine;
private final long seed;
private GeneratorKey(IrisData data, Engine engine, long seed) {
this.data = data;
this.engine = EngineRef.of(engine);
this.seed = seed;
}
private boolean matches(IrisData data, Engine engine, long seed) {
return this.data == data && this.engine.refersTo(engine) && this.seed == seed;
}
@Override
public boolean equals(Object object) {
return this == object || object instanceof GeneratorKey other
&& data == other.data && engine.equals(other.engine) && seed == other.seed;
}
@Override
public int hashCode() {
int result = System.identityHashCode(data);
result = 31 * result + engine.hashCode();
return 31 * result + Long.hashCode(seed);
}
}
}
@@ -22,7 +22,7 @@ import art.arcane.iris.generation.decoration.IrisOreGenerator;
import art.arcane.iris.generation.decoration.IrisOreBands;
import art.arcane.iris.generation.decoration.IrisProceduralBlocks;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.volmlib.util.cache.AtomicCache;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import art.arcane.iris.generation.block.B;
@@ -39,17 +39,17 @@ final class IrisBiomeOres {
private IrisBiomeOres() {
}
static NativeBlockState generateOres(IrisBiome biome, int x, int y, int z, RNG rng, IrisData data, boolean surface) {
static NativeBlockState generateOres(IrisBiome biome, int x, int y, int z, RNG rng, PackRuntime runtime, boolean surface) {
KList<IrisOreGenerator> localOres = surface ? getSurfaceOres(biome) : getUndergroundOres(biome);
return generateOres(localOres, x, y, z, rng, data);
return generateOres(localOres, x, y, z, rng, runtime);
}
static NativeBlockState generateSurfaceOres(IrisBiome biome, int x, int y, int z, RNG rng, IrisData data) {
return generateOres(getSurfaceOres(biome), x, y, z, rng, data);
static NativeBlockState generateSurfaceOres(IrisBiome biome, int x, int y, int z, RNG rng, PackRuntime runtime) {
return generateOres(getSurfaceOres(biome), x, y, z, rng, runtime);
}
static NativeBlockState generateUndergroundOres(IrisBiome biome, int x, int y, int z, RNG rng, IrisData data) {
return generateOres(getUndergroundOres(biome), x, y, z, rng, data);
static NativeBlockState generateUndergroundOres(IrisBiome biome, int x, int y, int z, RNG rng, PackRuntime runtime) {
return generateOres(getUndergroundOres(biome), x, y, z, rng, runtime);
}
static boolean hasSurfaceOres(IrisBiome biome) {
@@ -122,7 +122,7 @@ final class IrisBiomeOres {
});
}
private static NativeBlockState generateOres(KList<IrisOreGenerator> localOres, int x, int y, int z, RNG rng, IrisData data) {
private static NativeBlockState generateOres(KList<IrisOreGenerator> localOres, int x, int y, int z, RNG rng, PackRuntime runtime) {
if (localOres.isEmpty()) {
return null;
}
@@ -130,7 +130,7 @@ final class IrisBiomeOres {
int oreCount = localOres.size();
for (int oreIndex = 0; oreIndex < oreCount; oreIndex++) {
IrisOreGenerator oreGenerator = localOres.get(oreIndex);
NativeBlockState ore = oreGenerator.generate(x, y, z, rng, data);
NativeBlockState ore = oreGenerator.generate(x, y, z, rng, runtime);
if (ore != null) {
return ore;
}
@@ -18,16 +18,14 @@
package art.arcane.iris.generation.biome;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.block.IrisBlockData;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.NoiseStyle;
import art.arcane.iris.generation.runtime.EngineRef;
import art.arcane.iris.generation.terrain.IrisSlopeClip;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.volmlib.util.cache.AtomicCache;
import art.arcane.iris.generation.cache.LazyBoundedCache;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.pack.schema.annotation.ArrayType;
import art.arcane.iris.pack.schema.annotation.DependsOn;
import art.arcane.volmlib.util.documentation.Description;
@@ -38,17 +36,12 @@ import art.arcane.iris.pack.schema.annotation.Snippet;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import lombok.Setter;
import lombok.experimental.Accessors;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicReferenceArray;
@Snippet("biome-palette")
@Accessors(chain = true)
@@ -57,24 +50,7 @@ import java.util.concurrent.atomic.AtomicReferenceArray;
@Description("A layer of surface / subsurface material in biomes")
@Data
public class IrisBiomePaletteLayer {
private static final int LAYER_GENERATOR_CACHE_SIZE = 32;
private final transient AtomicCache<KList<NativeBlockState>> blockData = new AtomicCache<>();
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient LazyBoundedCache<LayerGeneratorKey, CNG> layerGenerators =
new LazyBoundedCache<>(LAYER_GENERATOR_CACHE_SIZE);
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient AtomicReferenceArray<CachedLayerGenerator> recentLayerGenerators =
new AtomicReferenceArray<>(LAYER_GENERATOR_CACHE_SIZE);
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient LazyBoundedCache<LayerGeneratorKey, CNG> heightGenerators =
new LazyBoundedCache<>(LAYER_GENERATOR_CACHE_SIZE);
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient AtomicReference<CachedLayerGenerator> recentHeightGenerator = new AtomicReference<>();
@Description("The style of noise")
private IrisGeneratorStyle style = NoiseStyle.STATIC.style();
@DependsOn({"minHeight", "maxHeight"})
@@ -99,23 +75,17 @@ public class IrisBiomePaletteLayer {
@Description("The palette of blocks to be used in this layer")
private KList<IrisBlockData> palette = new KList<IrisBlockData>().qadd(new IrisBlockData("GRASS_BLOCK"));
public CNG getHeightGenerator(RNG rng, IrisData data) {
Engine engine = data == null ? null : data.getEngine();
long generatorSeed = rng.getSeed() + minHeight * maxHeight + getBlockData(data).size();
CachedLayerGenerator recent = recentHeightGenerator.get();
if (recent != null && recent.key.matches(data, engine, generatorSeed)) {
return recent.generator;
}
LayerGeneratorKey key = new LayerGeneratorKey(data, engine, generatorSeed);
CNG generator = heightGenerators.computeIfAbsent(key,
ignored -> CNG.signature(new RNG(generatorSeed)));
recentHeightGenerator.set(new CachedLayerGenerator(key, generator));
return generator;
public CNG getHeightGenerator(RNG rng, PackRuntime runtime) {
long generatorSeed = rng.getSeed() + minHeight * maxHeight + getBlockData(runtime.data()).size();
return runtime.paletteLayer(this).heightGenerator(generatorSeed);
}
public NativeBlockState get(RNG rng, double x, double y, double z, IrisData data) {
return get(rng, 0, x, y, z, data);
static CNG createHeightGenerator(long generatorSeed) {
return CNG.signature(new RNG(generatorSeed));
}
public NativeBlockState get(RNG rng, double x, double y, double z, PackRuntime runtime) {
return get(rng, 0, x, y, z, runtime);
}
/**
@@ -123,44 +93,45 @@ public class IrisBiomePaletteLayer {
* only built inside the lazy layer generator initializer, using the exact same seed derivation
* as {@code parent.nextParallelRNG(signature)} followed by the generator signature.
*/
public NativeBlockState get(RNG parent, int signature, double x, double y, double z, IrisData data) {
KList<NativeBlockState> localBlockData = getBlockData(data);
if (localBlockData.isEmpty()) {
return null;
public NativeBlockState get(RNG parent, int signature, double x, double y, double z, PackRuntime runtime) {
KList<NativeBlockState> localBlockData = getBlockData(runtime.data());
if (localBlockData.size() <= 1) {
return localBlockData.isEmpty() ? null : localBlockData.get(0);
}
return fit(localBlockData, runtime.paletteLayer(this), parent, signature, x, y, z);
}
if (localBlockData.size() == 1) {
return localBlockData.get(0);
/** {@link #get(RNG, int, double, double, double, PackRuntime)} for a caller that already holds this layer's runtime. */
public NativeBlockState get(RNG parent, int signature, double x, double y, double z, PaletteLayerRuntime layerRuntime) {
KList<NativeBlockState> localBlockData = getBlockData(layerRuntime.packRuntime().data());
if (localBlockData.size() <= 1) {
return localBlockData.isEmpty() ? null : localBlockData.get(0);
}
return fit(localBlockData, layerRuntime, parent, signature, x, y, z);
}
private NativeBlockState fit(KList<NativeBlockState> localBlockData, PaletteLayerRuntime layerRuntime,
RNG parent, int signature, double x, double y, double z) {
double localZoom = zoom;
double scaledX = x / localZoom;
double scaledY = y / localZoom;
double scaledZ = z / localZoom;
return getLayerGenerator(parent, signature, data).fit(localBlockData, scaledX, scaledY, scaledZ);
CNG generator = layerRuntime.layerGenerator(layerGeneratorSeed(parent, signature, localBlockData.size()));
return generator.fit(localBlockData, x / localZoom, y / localZoom, z / localZoom);
}
public CNG getLayerGenerator(RNG rng, IrisData data) {
return getLayerGenerator(rng, 0, data);
public CNG getLayerGenerator(RNG rng, PackRuntime runtime) {
return getLayerGenerator(rng, 0, runtime);
}
public CNG getLayerGenerator(RNG parent, int signature, IrisData data) {
Engine engine = data == null ? null : data.getEngine();
long generatorSeed = parent.getSeed() + signature + minHeight + maxHeight + getBlockData(data).size();
int slot = (int) generatorSeed & (LAYER_GENERATOR_CACHE_SIZE - 1);
CachedLayerGenerator recent = recentLayerGenerators.getAcquire(slot);
if (recent != null && recent.key.matches(data, engine, generatorSeed)) {
return recent.generator;
}
public CNG getLayerGenerator(RNG parent, int signature, PackRuntime runtime) {
long generatorSeed = layerGeneratorSeed(parent, signature, getBlockData(runtime.data()).size());
return runtime.paletteLayer(this).layerGenerator(generatorSeed);
}
LayerGeneratorKey key = new LayerGeneratorKey(data, engine, generatorSeed);
CNG generator = layerGenerators.computeIfAbsent(key,
ignored -> style.create(new RNG(generatorSeed), data, engine));
if (generator != null) {
recentLayerGenerators.setRelease(slot, new CachedLayerGenerator(key, generator));
}
return generator;
private long layerGeneratorSeed(RNG parent, int signature, int blockCount) {
return parent.getSeed() + signature + minHeight + maxHeight + blockCount;
}
CNG createLayerGenerator(long generatorSeed, PackRuntime runtime) {
return style.createNoCache(new RNG(generatorSeed), runtime);
}
public KList<IrisBlockData> add(String b) {
@@ -196,49 +167,4 @@ public class IrisBiomePaletteLayer {
palette.clear();
return this;
}
private static final class LayerGeneratorKey {
private final IrisData data;
private final EngineRef engine;
private final long seed;
private LayerGeneratorKey(IrisData data, Engine engine, long seed) {
this.data = data;
this.engine = EngineRef.of(engine);
this.seed = seed;
}
private boolean matches(IrisData data, Engine engine, long seed) {
return this.data == data && this.engine.refersTo(engine) && this.seed == seed;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (!(object instanceof LayerGeneratorKey other)) {
return false;
}
return data == other.data && engine.equals(other.engine) && seed == other.seed;
}
@Override
public int hashCode() {
int result = System.identityHashCode(data);
result = 31 * result + engine.hashCode();
result = 31 * result + Long.hashCode(seed);
return result;
}
}
private static final class CachedLayerGenerator {
private final LayerGeneratorKey key;
private final CNG generator;
private CachedLayerGenerator(LayerGeneratorKey key, CNG generator) {
this.key = key;
this.generator = generator;
}
}
}
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.biome;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.cave.IrisCaveProfileSampler;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.NoiseStyle;
@@ -33,10 +34,6 @@ import art.arcane.volmlib.util.math.Rarity;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.volmlib.util.cache.AtomicCache;
import art.arcane.iris.generation.cache.LazyBoundedCache;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.pack.schema.annotation.ArrayType;
import art.arcane.volmlib.util.documentation.Description;
@@ -62,97 +59,72 @@ import lombok.experimental.Accessors;
@Data
public class IrisFloatingChildBiomes implements Rarity {
private final transient AtomicCache<IrisBiome> resolvedBiome = new AtomicCache<>();
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient LazyBoundedCache<RuntimeKey, FloatingIslandEdgeProfile> edgeTaperProfiles = new LazyBoundedCache<>(8);
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private transient volatile CachedEdgeProfile recentEdgeProfile;
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient LazyBoundedCache<RuntimeKey, IrisCaveProfileSampler> carvingProfileSamplers = new LazyBoundedCache<>(8);
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private transient volatile CachedCarvingProfile recentCarvingProfile;
private final transient AtomicCache<IrisObjectScale> shrinkScaleCache = new AtomicCache<>();
public CNG getFootprintCng(long baseSeed, IrisData data) {
return getFootprintStyle().create(baseSeed ^ 0xF007B17DL, data);
public CNG getFootprintCng(long baseSeed, PackRuntime runtime) {
return getFootprintStyle().create(baseSeed ^ 0xF007B17DL, runtime);
}
public FloatingIslandEdgeProfile getEdgeTaperProfile(long baseSeed, IrisData data) {
Engine engine = data == null ? null : data.getEngine();
CachedEdgeProfile recent = recentEdgeProfile;
if (recent != null && recent.key.matches(baseSeed, data, engine)) {
return recent.profile;
}
RuntimeKey key = new RuntimeKey(baseSeed, data, engine);
FloatingIslandEdgeProfile profile = edgeTaperProfiles.computeIfAbsent(key, ignored -> {
int width = FloatingIslandEdgeProfile.clampWidth(getEdgeTaperWidth());
double amplitude = FloatingIslandEdgeProfile.clampVariationAmplitude(
getEdgeTaperVariationAmplitude(), width);
IrisGeneratorStyle style = getEdgeTaperVariationStyle();
CNG variation = amplitude > 0.0D && style != null
? style.create(baseSeed ^ 0xED6E7A9E5L, data)
: null;
return new FloatingIslandEdgeProfile(width, getEdgeTaperExponent(), amplitude, variation);
});
recentEdgeProfile = new CachedEdgeProfile(key, profile);
return profile;
public FloatingIslandEdgeProfile getEdgeTaperProfile(long baseSeed, PackRuntime runtime) {
return runtime.floatingChild(this).edgeTaperProfile(baseSeed);
}
public CNG getPickerCng(long baseSeed, IrisData data) {
return getPickerStyle().create(baseSeed ^ 0x91C4E72DL, data);
FloatingIslandEdgeProfile createEdgeTaperProfile(long baseSeed, PackRuntime runtime) {
int width = FloatingIslandEdgeProfile.clampWidth(getEdgeTaperWidth());
double amplitude = FloatingIslandEdgeProfile.clampVariationAmplitude(getEdgeTaperVariationAmplitude(), width);
IrisGeneratorStyle style = getEdgeTaperVariationStyle();
CNG variation = amplitude > 0.0D && style != null
? style.create(baseSeed ^ 0xED6E7A9E5L, runtime)
: null;
return new FloatingIslandEdgeProfile(width, getEdgeTaperExponent(), amplitude, variation);
}
public CNG getAltitudeCng(long baseSeed, IrisData data) {
return getAltitudeStyle().create(baseSeed ^ 0xA17DEBBL, data);
public CNG getPickerCng(long baseSeed, PackRuntime runtime) {
return getPickerStyle().create(baseSeed ^ 0x91C4E72DL, runtime);
}
public CNG getTopShapeCng(long baseSeed, IrisData data) {
return getTopShapeStyle().create(baseSeed ^ 0x70970601DEFL, data);
public CNG getAltitudeCng(long baseSeed, PackRuntime runtime) {
return getAltitudeStyle().create(baseSeed ^ 0xA17DEBBL, runtime);
}
public CNG getBottomCng(long baseSeed, IrisData data) {
return getBottomStyle().create(baseSeed ^ 0xB0770075CAFEL, data);
public CNG getTopShapeCng(long baseSeed, PackRuntime runtime) {
return getTopShapeStyle().create(baseSeed ^ 0x70970601DEFL, runtime);
}
public CNG getWallWarpCng(long baseSeed, IrisData data) {
public CNG getBottomCng(long baseSeed, PackRuntime runtime) {
return getBottomStyle().create(baseSeed ^ 0xB0770075CAFEL, runtime);
}
public CNG getWallWarpCng(long baseSeed, PackRuntime runtime) {
IrisGeneratorStyle style = getWallWarpStyle();
if (style == null) {
return null;
}
return style.create(baseSeed ^ 0xA117BA17E0FL, data);
return style.create(baseSeed ^ 0xA117BA17E0FL, runtime);
}
public CNG getCarveCng(long baseSeed, IrisData data) {
public CNG getCarveCng(long baseSeed, PackRuntime runtime) {
IrisGeneratorStyle style = getCarveStyle();
if (style == null) {
return null;
}
return style.create(baseSeed ^ 0xCA5EC1EE5EL, data);
return style.create(baseSeed ^ 0xCA5EC1EE5EL, runtime);
}
public IrisCaveProfileSampler getCarvingProfileSampler(Engine engine, IrisData data) {
public IrisCaveProfileSampler getCarvingProfileSampler(PackRuntime runtime) {
if (!hasCarvingReference()) {
return null;
}
return runtime.floatingChild(this).carvingProfileSampler();
}
CachedCarvingProfile recent = recentCarvingProfile;
if (recent != null && recent.key.matches(0L, data, engine)) {
return recent.sampler;
IrisCaveProfileSampler createCarvingProfileSampler(PackRuntime runtime) {
Engine engine = runtime.engine();
IrisBiome resolved = resolveCarvingBiome(carving, engine, runtime.data());
if (resolved == null || resolved.getCaveProfile() == null || !resolved.getCaveProfile().isEnabled()) {
return null;
}
RuntimeKey key = new RuntimeKey(0L, data, engine);
IrisCaveProfileSampler sampler = carvingProfileSamplers.computeIfAbsent(key, ignored -> {
IrisBiome resolved = resolveCarvingBiome(carving, engine, data);
if (resolved == null || resolved.getCaveProfile() == null || !resolved.getCaveProfile().isEnabled()) {
return null;
}
return new IrisCaveProfileSampler(engine, resolved.getCaveProfile());
});
recentCarvingProfile = new CachedCarvingProfile(key, sampler);
return sampler;
return new IrisCaveProfileSampler(engine, resolved.getCaveProfile());
}
public boolean hasCarvingReference() {
@@ -400,28 +372,4 @@ public class IrisFloatingChildBiomes implements Rarity {
return loaded;
});
}
private record RuntimeKey(long seed, IrisData data, Engine engine) {
private boolean matches(long seed, IrisData data, Engine engine) {
return this.seed == seed && this.data == data && this.engine == engine;
}
@Override
public boolean equals(Object object) {
return object instanceof RuntimeKey other && matches(other.seed, other.data, other.engine);
}
@Override
public int hashCode() {
int hash = Long.hashCode(seed);
hash = 31 * hash + System.identityHashCode(data);
return 31 * hash + System.identityHashCode(engine);
}
}
private record CachedEdgeProfile(RuntimeKey key, FloatingIslandEdgeProfile profile) {
}
private record CachedCarvingProfile(RuntimeKey key, IrisCaveProfileSampler sampler) {
}
}
@@ -0,0 +1,57 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* 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 <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.generation.biome;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.SeedTable;
import art.arcane.volmlib.util.noise.CNG;
/**
* What one engine derives from an {@link IrisBiomePaletteLayer}: the block selection and depth generators of the
* seeds that sample it.
*/
public final class PaletteLayerRuntime {
private static final int LAYER_SEED_CAPACITY = 32;
private static final int LAYER_RECENT_SLOTS = 32;
private static final int HEIGHT_SEED_CAPACITY = 32;
private final PackRuntime runtime;
private final SeedTable<CNG> layerGenerators;
private final SeedTable<CNG> heightGenerators;
public PaletteLayerRuntime(IrisBiomePaletteLayer layer, PackRuntime runtime) {
this.runtime = runtime;
this.layerGenerators = new SeedTable<>(LAYER_SEED_CAPACITY, LAYER_RECENT_SLOTS,
seed -> layer.createLayerGenerator(seed, runtime));
this.heightGenerators = new SeedTable<>(HEIGHT_SEED_CAPACITY, IrisBiomePaletteLayer::createHeightGenerator);
}
/** The scope this runtime was built in, whose pack data resolves the layer's palette. */
public PackRuntime packRuntime() {
return runtime;
}
public CNG layerGenerator(long seed) {
return layerGenerators.get(seed);
}
public CNG heightGenerator(long seed) {
return heightGenerators.get(seed);
}
}
@@ -1,49 +0,0 @@
package art.arcane.iris.generation.cache;
import java.util.LinkedHashMap;
import java.util.Objects;
import java.util.function.Function;
public final class LazyBoundedCache<K, V> {
private final int maximumSize;
private transient LinkedHashMap<K, V> entries;
public LazyBoundedCache(int maximumSize) {
if (maximumSize <= 0) {
throw new IllegalArgumentException("Maximum cache size must be positive");
}
this.maximumSize = maximumSize;
}
public synchronized V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
K requiredKey = Objects.requireNonNull(key, "Cache key");
Function<? super K, ? extends V> requiredMapping = Objects.requireNonNull(mappingFunction, "Cache mapping function");
if (entries != null) {
V cached = entries.get(requiredKey);
if (cached != null) {
return cached;
}
}
V computed = requiredMapping.apply(requiredKey);
if (computed == null) {
return null;
}
if (entries == null) {
entries = new LinkedHashMap<>(maximumSize, 1F, true);
}
entries.put(requiredKey, computed);
if (entries.size() > maximumSize) {
entries.sequencedKeySet().removeFirst();
}
return computed;
}
synchronized boolean isInitialized() {
return entries != null;
}
synchronized int size() {
return entries == null ? 0 : entries.size();
}
}
@@ -1,47 +0,0 @@
package art.arcane.iris.generation.cache;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
/**
* A per-instance thread local whose owner can drop every thread's value when it closes.
* A plain ThreadLocal leaves its values in pooled threads that outlive the owner, and with them
* whatever they reference, until each thread happens to clean the stale entry.
*/
public final class ReleasableThreadLocal<T> {
private final Supplier<? extends T> factory;
private final Set<Slot<T>> slots = ConcurrentHashMap.newKeySet();
private final ThreadLocal<Slot<T>> local = ThreadLocal.withInitial(this::registerSlot);
public ReleasableThreadLocal(Supplier<? extends T> factory) {
this.factory = Objects.requireNonNull(factory, "factory");
}
public T get() {
Slot<T> slot = local.get();
T value = slot.value;
if (value == null) {
value = factory.get();
slot.value = value;
}
return value;
}
public void releaseAll() {
for (Slot<T> slot : slots) {
slot.value = null;
}
}
private Slot<T> registerSlot() {
Slot<T> slot = new Slot<>();
slots.add(slot);
return slot;
}
private static final class Slot<T> {
private T value;
}
}
@@ -22,7 +22,7 @@ import art.arcane.iris.pack.value.IrisRange;
import art.arcane.iris.generation.noise.IrisStyledRange;
import art.arcane.volmlib.util.math.M;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.volmlib.util.noise.CNG;
import art.arcane.volmlib.util.math.RNG;
@@ -52,18 +52,18 @@ public final class IrisCaveProfileSampler {
private final boolean hasModules;
public IrisCaveProfileSampler(Engine engine, IrisCaveProfile profile) {
IrisData data = engine.getData();
PackRuntime runtime = PackRuntime.of(engine, engine.getData());
this.profile = profile;
List<ModuleState> moduleStates = new ArrayList<>();
RNG baseRng = new RNG(engine.getSeedManager().getCarve());
this.baseDensity = profile.getBaseDensityStyle().create(baseRng.nextParallelRNG(934_447), data);
this.detailDensity = profile.getDetailDensityStyle().create(baseRng.nextParallelRNG(612_991), data);
this.warpDensity = profile.getWarpStyle().create(baseRng.nextParallelRNG(770_713), data);
this.baseDensity = profile.getBaseDensityStyle().create(baseRng.nextParallelRNG(934_447), runtime);
this.detailDensity = profile.getDetailDensityStyle().create(baseRng.nextParallelRNG(612_991), runtime);
this.warpDensity = profile.getWarpStyle().create(baseRng.nextParallelRNG(770_713), runtime);
IrisStyledRange threshold = profile.getDensityThreshold();
thresholdMin = threshold.getMin();
thresholdMax = threshold.getMax();
thresholdHasNoise = thresholdMin != thresholdMax && !threshold.getStyle().isFlat();
thresholdDensity = thresholdHasNoise ? threshold.getStyle().create(baseRng.nextParallelRNG(489_112), data) : null;
thresholdDensity = thresholdHasNoise ? threshold.getStyle().create(baseRng.nextParallelRNG(489_112), runtime) : null;
constantThreshold = thresholdMin == thresholdMax ? thresholdMin : M.lerp(thresholdMin, thresholdMax, 0.5D);
this.baseWeight = profile.getBaseWeight();
this.detailWeight = profile.getDetailWeight();
@@ -73,7 +73,7 @@ public final class IrisCaveProfileSampler {
double weight = Math.abs(baseWeight) + Math.abs(detailWeight);
int index = 0;
for (IrisCaveFieldModule module : profile.getModules()) {
CNG moduleDensity = module.getStyle().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), data);
CNG moduleDensity = module.getStyle().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), runtime);
ModuleState state = new ModuleState(module, moduleDensity);
moduleStates.add(state);
weight += Math.abs(state.weight);
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.GenerationFailures;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.mantle.EngineMantle;
@@ -46,6 +47,7 @@ final class DecoratorCore {
private static volatile NativeBlockState twistingVines;
private static volatile NativeBlockState twistingVinesPlant;
/** Per-thread placement options; callers clear the mantle reference once a placement returns. */
static final ThreadLocal<PlaceOpts> SCRATCH_OPTS = ThreadLocal.withInitial(PlaceOpts::new);
@@ -73,11 +75,13 @@ final class DecoratorCore {
boolean caveSkipFluid;
boolean underwater;
int fluidHeight;
EngineMantle mantle;
void reset() {
caveSkipFluid = false;
underwater = false;
fluidHeight = 0;
mantle = null;
}
}
@@ -90,25 +94,27 @@ final class DecoratorCore {
}
static IrisDecorator pickDecorator(IrisBiome biome, IrisDecorationPart part, RNG gRNG,
RNG colRng, IrisData data, double realX, double realZ) {
RNG colRng, PackRuntime runtime, double realX, double realZ) {
IrisDecorator[] bucket = biome.getDecoratorBucket(part);
if (bucket.length == 0) {
return null;
}
DecoratorRuntime[] decoratorRuntimes = runtime.biome(biome).decorators(part);
IrisDecorator picked = null;
int count = 0;
for (IrisDecorator d : bucket) {
for (int index = 0; index < bucket.length; index++) {
IrisDecorator d = bucket[index];
try {
if (d.passesChanceGate(gRNG, realX, realZ, data)) {
if (d.passesChanceGate(gRNG, realX, realZ, decoratorRuntimes[index])) {
count++;
if (count == 1 || colRng.nextInt(count) == 0) {
picked = d;
}
}
} catch (Throwable e) {
skip(e, d, data, (int) realX, -1, (int) realZ, biome);
skip(e, d, runtime.data(), (int) realX, -1, (int) realZ, biome);
}
}
@@ -117,14 +123,14 @@ final class DecoratorCore {
static void placeSurfaceSingle(IrisDecorator decorator,
int x, int z, int realX, int height, int realZ,
Hunk<NativeBlockState> data, RNG rng, IrisData irisData,
Hunk<NativeBlockState> data, RNG rng, PackRuntime runtime,
boolean underwater, boolean caveSkipFluid, EngineMantle mantle) {
if (height < 0 || height >= data.getHeight()) {
return;
}
NativeBlockState bdx = data.get(x, height, z);
NativeBlockState bd = decorator.pickBlockData(rng, irisData, realX, realZ);
NativeBlockState bd = decorator.pickBlockData(rng, runtime, realX, realZ);
if (!IrisSpeleothems.isSpike(bd) && !underwater && !canGoOn(bd, bdx)
&& !decorator.isForcePlace() && decorator.getForceBlock() == null) {
@@ -136,14 +142,14 @@ final class DecoratorCore {
return;
}
data.set(x, height, z, fixFacesForHunk(
decorator.getForceBlock().getBlockData(irisData), data, x, z, realX, height, realZ, mantle));
decorator.getForceBlock().getBlockData(runtime.data()), data, x, z, realX, height, realZ, mantle));
}
if (!decorator.isForcePlace()) {
if (decorator.getWhitelist() != null && !matchesPalette(decorator.getWhitelistArray(irisData), bdx)) {
if (decorator.getWhitelist() != null && !matchesPalette(decorator.getWhitelistArray(runtime.data()), bdx)) {
return;
}
if (decorator.getBlacklist() != null && matchesPalette(decorator.getBlacklistArray(irisData), bdx)) {
if (decorator.getBlacklist() != null && matchesPalette(decorator.getBlacklistArray(runtime.data()), bdx)) {
return;
}
}
@@ -174,7 +180,7 @@ final class DecoratorCore {
data.set(x, lowerY, z, lower);
data.set(x, upperY, z, IrisProceduralBlocks.normalizeWaterlogging(upper, data.get(x, upperY, z), true));
} catch (Throwable e) {
skip(e, decorator, irisData, realX, lowerY, realZ, null);
skip(e, decorator, runtime.data(), realX, lowerY, realZ, null);
}
return;
}
@@ -200,8 +206,8 @@ final class DecoratorCore {
static void placeSingleAt(IrisDecorator decorator, int x, int z,
int realX, int height, int realZ, Hunk<NativeBlockState> data,
RNG rng, IrisData irisData, boolean applyFixFaces, EngineMantle mantle) {
NativeBlockState bd = decorator.pickBlockData(rng, irisData, realX, realZ);
RNG rng, PackRuntime runtime, boolean applyFixFaces, EngineMantle mantle) {
NativeBlockState bd = decorator.pickBlockData(rng, runtime, realX, realZ);
if (bd == null) {
return;
}
@@ -210,7 +216,7 @@ final class DecoratorCore {
return;
}
if (IrisSpeleothems.isSpike(bd)) {
if (height + 1 < data.getHeight() && allowsSurface(decorator, data.get(x, height + 1, z), irisData)) {
if (height + 1 < data.getHeight() && allowsSurface(decorator, data.get(x, height + 1, z), runtime.data())) {
placeSingleSpike(bd, data, x, z, height, false, false);
}
return;
@@ -223,17 +229,17 @@ final class DecoratorCore {
static void placeStackUp(IrisDecorator decorator, int x, int z, int realX, int realZ,
int height, int max, Hunk<NativeBlockState> data,
RNG rng, IrisData irisData, PlaceOpts opts, EngineMantle mantle) {
RNG rng, PackRuntime runtime, PlaceOpts opts) {
if (height < 0 || height >= data.getHeight()) {
return;
}
NativeBlockState support = data.get(x, height, z);
if (!allowsSurface(decorator, support, irisData)) {
if (!allowsSurface(decorator, support, runtime.data())) {
return;
}
int effectiveMax = opts.underwater ? Math.min(max, opts.fluidHeight - height) : max;
int stack = computeStack(decorator, rng, realX, realZ, irisData, effectiveMax);
int stack = computeStack(decorator, rng, realX, realZ, runtime, effectiveMax);
int placed = 0;
boolean hasSpikes = false;
NativeBlockState sampledBlock = null;
@@ -252,8 +258,8 @@ final class DecoratorCore {
boolean top = threshold >= decorator.getTopThreshold();
if (sampledBlock == null || top != sampledTop) {
sampledBlock = top
? decorator.pickBlockDataTop(rng, irisData, realX, realZ)
: decorator.pickBlockData(rng, irisData, realX, realZ);
? decorator.pickBlockDataTop(rng, runtime, realX, realZ)
: decorator.pickBlockData(rng, runtime, realX, realZ);
sampledTop = top;
}
NativeBlockState block = sampledBlock;
@@ -261,7 +267,7 @@ final class DecoratorCore {
break;
}
if (!IrisSugarCane.canPlace(block, data, x, y, z, realX, realZ,
mantle == null ? null : mantle.getEngine())) {
opts.mantle == null ? null : opts.mantle.getEngine())) {
break;
}
if (IrisSpeleothems.isSpike(block)) {
@@ -286,15 +292,15 @@ final class DecoratorCore {
static void placeStackDown(IrisDecorator decorator, int x, int z, int realX, int realZ,
int height, int minHeight, Hunk<NativeBlockState> data,
RNG rng, IrisData irisData, int max, PlaceOpts opts, EngineMantle mantle) {
RNG rng, PackRuntime runtime, int max, PlaceOpts opts, EngineMantle mantle) {
if (height < 0 || height >= data.getHeight()) {
return;
}
NativeBlockState support = height + 1 < data.getHeight() ? data.get(x, height + 1, z) : null;
if (!allowsSurface(decorator, support, irisData)) {
if (!allowsSurface(decorator, support, runtime.data())) {
return;
}
int stack = computeStack(decorator, rng, realX, realZ, irisData, max);
int stack = computeStack(decorator, rng, realX, realZ, runtime, max);
int placed = 0;
boolean hasSpikes = false;
NativeBlockState sampledBlock = null;
@@ -313,8 +319,8 @@ final class DecoratorCore {
boolean top = threshold >= decorator.getTopThreshold();
if (sampledBlock == null || top != sampledTop) {
sampledBlock = top
? decorator.pickBlockDataTop(rng, irisData, realX, realZ)
: decorator.pickBlockData(rng, irisData, realX, realZ);
? decorator.pickBlockDataTop(rng, runtime, realX, realZ)
: decorator.pickBlockData(rng, runtime, realX, realZ);
sampledTop = top;
}
NativeBlockState block = sampledBlock;
@@ -347,11 +353,11 @@ final class DecoratorCore {
static void placeFloatingSimple(IrisDecorator decorator,
int xf, int zf, int realX, int realZ,
int height, int max, Hunk<NativeBlockState> data,
RNG rng, IrisData irisData, EngineMantle mantle) {
RNG rng, PackRuntime runtime, EngineMantle mantle) {
if (!hasFloatingSurface(data, xf, height, zf)) {
return;
}
NativeBlockState bd = decorator.pickBlockData(rng, irisData, realX, realZ);
NativeBlockState bd = decorator.pickBlockData(rng, runtime, realX, realZ);
if (bd == null) {
return;
}
@@ -361,7 +367,7 @@ final class DecoratorCore {
}
if (IrisSpeleothems.isSpike(bd)) {
if (max > 1 && allowsSurface(decorator, data.get(xf, height, zf), irisData)) {
if (max > 1 && allowsSurface(decorator, data.get(xf, height, zf), runtime.data())) {
placeSingleSpike(bd, data, xf, zf, height + 1, true, false);
}
return;
@@ -381,7 +387,7 @@ final class DecoratorCore {
data.set(xf, lowerY, zf, IrisProceduralBlocks.normalizeWaterlogging(lower, data.get(xf, lowerY, zf), true));
data.set(xf, upperY, zf, IrisProceduralBlocks.normalizeWaterlogging(upper, data.get(xf, upperY, zf), true));
} catch (Throwable e) {
skip(e, decorator, irisData, realX, lowerY, realZ, null);
skip(e, decorator, runtime.data(), realX, lowerY, realZ, null);
}
return;
}
@@ -394,11 +400,11 @@ final class DecoratorCore {
static int placeFloatingStacked(IrisDecorator decorator,
int xf, int zf, int realX, int realZ,
int height, int max, Hunk<NativeBlockState> data,
RNG rng, IrisData irisData, EngineMantle mantle) {
RNG rng, PackRuntime runtime, EngineMantle mantle) {
if (!hasFloatingSurface(data, xf, height, zf)) {
return 0;
}
int stack = decorator.getHeight(rng, realX, realZ, irisData);
int stack = decorator.getHeight(rng, realX, realZ, runtime);
if (decorator.isScaleStack()) {
stack = Math.min((int) Math.ceil((double) max * ((double) stack / 100)), decorator.getAbsoluteMaxStack());
} else {
@@ -418,8 +424,8 @@ final class DecoratorCore {
boolean top = threshold >= decorator.getTopThreshold();
if (sampledBlock == null || top != sampledTop) {
sampledBlock = top
? decorator.pickBlockDataTop(rng, irisData, realX, realZ)
: decorator.pickBlockData(rng, irisData, realX, realZ);
? decorator.pickBlockDataTop(rng, runtime, realX, realZ)
: decorator.pickBlockData(rng, runtime, realX, realZ);
sampledTop = top;
}
NativeBlockState bd = sampledBlock;
@@ -431,7 +437,7 @@ final class DecoratorCore {
break;
}
if (IrisSpeleothems.isSpike(bd)) {
if (!allowsSurface(decorator, data.get(xf, height, zf), irisData)
if (!allowsSurface(decorator, data.get(xf, height, zf), runtime.data())
|| !IrisSpeleothems.canPlace(bd, data, xf, zf, h, true, false)) {
break;
}
@@ -579,8 +585,8 @@ final class DecoratorCore {
}
static int computeStack(IrisDecorator decorator, RNG rng, double realX, double realZ,
IrisData irisData, int max) {
int stack = decorator.getHeight(rng, realX, realZ, irisData);
PackRuntime runtime, int max) {
int stack = decorator.getHeight(rng, realX, realZ, runtime);
if (decorator.isScaleStack()) {
stack = Math.min((int) Math.ceil((double) max * ((double) stack / 100)), decorator.getAbsoluteMaxStack());
} else {
@@ -0,0 +1,57 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* 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 <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.SeedTable;
import art.arcane.volmlib.util.noise.CNG;
/** What one engine derives from an {@link IrisDecorator}: the stack, placement and variance generators of each seed. */
public final class DecoratorRuntime {
private static final int SEED_CAPACITY = 32;
private final PackRuntime runtime;
private final SeedTable<CNG> heightGenerators;
private final SeedTable<CNG> layerGenerators;
private final SeedTable<CNG> varianceGenerators;
public DecoratorRuntime(IrisDecorator decorator, PackRuntime runtime) {
this.runtime = runtime;
this.heightGenerators = new SeedTable<>(SEED_CAPACITY, seed -> decorator.createHeightGenerator(seed, runtime));
this.layerGenerators = new SeedTable<>(SEED_CAPACITY, seed -> decorator.createLayerGenerator(seed, runtime));
this.varianceGenerators = new SeedTable<>(SEED_CAPACITY, seed -> decorator.createVarianceGenerator(seed, runtime));
}
/** The scope this runtime was built in, whose pack data resolves the decorator's palettes. */
public PackRuntime packRuntime() {
return runtime;
}
public CNG heightGenerator(long seed) {
return heightGenerators.get(seed);
}
public CNG layerGenerator(long seed) {
return layerGenerators.get(seed);
}
public CNG varianceGenerator(long seed) {
return varianceGenerators.get(seed);
}
}
@@ -0,0 +1,75 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* 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 <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.SeedTable;
import art.arcane.iris.structure.object.IrisObject;
import art.arcane.volmlib.util.collection.KList;
/**
* What one engine derives from an {@link IrisDepositGenerator}: the clump variants of the engine's deposit seed, at
* the configured size and at each scaled size the deposit modifier asks for.
*/
public final class DepositRuntime {
private static final int SCALED_SIZE_CAPACITY = 64;
private final IrisDepositGenerator deposit;
private final PackRuntime runtime;
private final long depositSeed;
private final SeedTable<KList<IrisObject>> scaledClumps;
private volatile KList<IrisObject> clumps;
public DepositRuntime(IrisDepositGenerator deposit, PackRuntime runtime) {
this.deposit = deposit;
this.runtime = runtime;
this.depositSeed = runtime.engine().getSeedManager().getDeposit();
this.scaledClumps = new SeedTable<>(SCALED_SIZE_CAPACITY, sizes -> deposit.createScaledClumps(
depositSeed, minSize(sizes), maxSize(sizes), runtime.data()));
}
public KList<IrisObject> clumps() {
KList<IrisObject> built = clumps;
if (built != null) {
return built;
}
synchronized (this) {
if (clumps == null) {
clumps = deposit.createClumps(depositSeed, runtime.data());
}
return clumps;
}
}
public KList<IrisObject> scaledClumps(int minSize, int maxSize) {
return scaledClumps.get(sizeKey(minSize, maxSize));
}
private static long sizeKey(int minSize, int maxSize) {
return ((long) minSize << 32) | (maxSize & 0xffffffffL);
}
private static int minSize(long sizeKey) {
return (int) (sizeKey >>> 32);
}
private static int maxSize(long sizeKey) {
return (int) sizeKey;
}
}
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.volmlib.util.hunk.Hunk;
@@ -36,7 +37,8 @@ public class FloatingDecorator {
int height, int max, Hunk<NativeBlockState> data, RNG rng,
Runnable candidatesNullCallback) {
RNG gRNG = new RNG(DecoratorCore.partSeed(engine.getSeedManager().getComponent(), part));
IrisDecorator decorator = DecoratorCore.pickDecorator(target, part, gRNG, rng, engine.getData(), realX, realZ);
PackRuntime runtime = PackRuntime.of(engine);
IrisDecorator decorator = DecoratorCore.pickDecorator(target, part, gRNG, rng, runtime, realX, realZ);
if (decorator == null) {
candidatesNullCallback.run();
@@ -45,11 +47,11 @@ public class FloatingDecorator {
if (!decorator.isStacking()) {
DecoratorCore.placeFloatingSimple(decorator, xf, zf, realX, realZ, height, max, data,
gRNG, engine.getData(), engine.getMantle());
gRNG, runtime, engine.getMantle());
return max > 1 ? 1 : 0;
}
return DecoratorCore.placeFloatingStacked(decorator, xf, zf, realX, realZ, height, max, data,
gRNG, engine.getData(), engine.getMantle());
gRNG, runtime, engine.getMantle());
}
}
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.block.B;
import art.arcane.iris.generation.block.IrisBlockData;
import art.arcane.iris.generation.hydrology.plan.HydrologySettings;
@@ -32,7 +33,7 @@ public final class HydrologyVegetation {
this.shoreRng = new RNG(DecoratorCore.partSeed(this.seed, IrisDecorationPart.SHORE_LINE));
}
public void decorate(Hunk<NativeBlockState> output, int localX, int localZ, int x, int z, WaterRole role, Water water, IrisData data) {
public void decorate(Hunk<NativeBlockState> output, int localX, int localZ, int x, int z, WaterRole role, Water water, PackRuntime runtime) {
Placement placement = placement(role);
if (placement == Placement.NONE) {
return;
@@ -45,7 +46,7 @@ public final class HydrologyVegetation {
if (ground < 0 || ground + 1 >= output.getHeight()) {
return;
}
Column column = new Column(output, localX, localZ, x, z, ground, water, data);
Column column = new Column(output, localX, localZ, x, z, ground, water, runtime);
if (placement == Placement.SHORE) {
decorateShore(column, decorators.shore);
return;
@@ -112,7 +113,7 @@ public final class HydrologyVegetation {
int count = 0;
for (IrisDecorator decorator : bucket) {
try {
if (!decorator.passesChanceGate(partRng, column.x, column.z, column.data)) {
if (!decorator.passesChanceGate(partRng, column.x, column.z, column.runtime)) {
continue;
}
} catch (Throwable e) {
@@ -213,9 +214,10 @@ public final class HydrologyVegetation {
private final int z;
private final int ground;
private final Water water;
private final PackRuntime runtime;
private final IrisData data;
private Column(Hunk<NativeBlockState> output, int localX, int localZ, int x, int z, int ground, Water water, IrisData data) {
private Column(Hunk<NativeBlockState> output, int localX, int localZ, int x, int z, int ground, Water water, PackRuntime runtime) {
this.output = output;
this.localX = localX;
this.localZ = localZ;
@@ -223,7 +225,8 @@ public final class HydrologyVegetation {
this.z = z;
this.ground = ground;
this.water = water;
this.data = data;
this.runtime = runtime;
this.data = runtime.data();
}
private boolean accepts(IrisDecorator decorator, NativeBlockState support) {
@@ -231,7 +234,7 @@ public final class HydrologyVegetation {
}
private int stack(IrisDecorator decorator, RNG rng, int room) {
return decorator.isStacking() ? Math.min(room, DecoratorCore.computeStack(decorator, rng, x, z, data, room)) : 1;
return decorator.isStacking() ? Math.min(room, DecoratorCore.computeStack(decorator, rng, x, z, runtime, room)) : 1;
}
private void place(IrisDecorator decorator, RNG rng, int baseY, int room, Slot slot, NativeBlockState support) {
@@ -243,7 +246,7 @@ public final class HydrologyVegetation {
}
private void placePicked(IrisDecorator decorator, RNG rng, int baseY, int room, Slot slot, NativeBlockState support) {
NativeBlockState first = decorator.pickBlockData(rng, data, x, z);
NativeBlockState first = decorator.pickBlockData(rng, runtime, x, z);
if (first == null) {
return;
}
@@ -260,7 +263,7 @@ public final class HydrologyVegetation {
int y = baseY + index;
boolean top = (stack == 1 ? 1D : (double) index / (stack - 1)) >= decorator.getTopThreshold();
if (top != sampledTop) {
sampled = top ? decorator.pickBlockDataTop(rng, data, x, z) : decorator.pickBlockData(rng, data, x, z);
sampled = top ? decorator.pickBlockDataTop(rng, runtime, x, z) : decorator.pickBlockData(rng, runtime, x, z);
sampledTop = top;
}
NativeBlockState block = sampled == null ? null : fit(sampled, y, slot, decorator, index == 0 ? support : null);
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.terrain.InferredType;
import art.arcane.iris.generation.biome.IrisBiome;
@@ -47,21 +48,22 @@ public class IrisCeilingDecorator extends IrisEngineDecorator {
Hunk<NativeBlockState> data, IrisBiome biome, InferredType inferredType, int height, int max) {
boolean caveSkipFluid = IrisSurfaceDecorator.skipsFluid(inferredType);
RNG rng = getRNG(realX, realZ);
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ);
PackRuntime runtime = PackRuntime.of(getEngine(), getData());
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, runtime, realX, realZ);
if (decorator == null) {
return;
}
try {
place(decorator, x, z, realX, realZ, data, height, max, caveSkipFluid);
place(decorator, x, z, realX, realZ, data, height, max, caveSkipFluid, runtime);
} catch (Throwable e) {
DecoratorCore.skip(e, decorator, getData(), realX, height, realZ, biome);
}
}
private void place(IrisDecorator decorator, int x, int z, int realX, int realZ, Hunk<NativeBlockState> data,
int height, int max, boolean caveSkipFluid) {
int height, int max, boolean caveSkipFluid, PackRuntime runtime) {
if (!decorator.isStacking()) {
if (caveSkipFluid) {
NativeBlockState state = data.get(x, height, z);
@@ -69,13 +71,13 @@ public class IrisCeilingDecorator extends IrisEngineDecorator {
return;
}
}
DecoratorCore.placeSingleAt(decorator, x, z, realX, height, realZ, data, partRNG, getData(), true, getEngine().getMantle());
DecoratorCore.placeSingleAt(decorator, x, z, realX, height, realZ, data, partRNG, runtime, true, getEngine().getMantle());
return;
}
DecoratorCore.PlaceOpts opts = DecoratorCore.SCRATCH_OPTS.get();
opts.reset();
opts.caveSkipFluid = caveSkipFluid;
DecoratorCore.placeStackDown(decorator, x, z, realX, realZ, height, 0, data, partRNG, getData(), max, opts, getEngine().getMantle());
DecoratorCore.placeStackDown(decorator, x, z, realX, realZ, height, 0, data, partRNG, runtime, max, opts, getEngine().getMantle());
}
}
@@ -18,13 +18,12 @@
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.cache.LazyBoundedCache;
import art.arcane.iris.generation.block.IrisBlockData;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.NoiseStyle;
import art.arcane.iris.generation.runtime.EngineRef;
import art.arcane.iris.generation.terrain.IrisSlopeClip;
import art.arcane.iris.pack.loading.IrisData;
@@ -53,8 +52,6 @@ import lombok.experimental.Accessors;
@Description("A biome decorator is used for placing flowers, grass, cacti and so on")
@Data
public class IrisDecorator {
private final transient LazyBoundedCache<GeneratorKey, Generators> generators = new LazyBoundedCache<>(32);
private transient volatile Generators recentGenerators;
private final transient AtomicCache<KList<NativeBlockState>> blockData = new AtomicCache<>();
private final transient AtomicCache<KList<NativeBlockState>> blockDataTops = new AtomicCache<>();
private final transient AtomicCache<NativeBlockState[]> blockDataArray = new AtomicCache<>();
@@ -119,50 +116,39 @@ public class IrisDecorator {
@Description("When the stack passes the top threshold, the top palette will start being used instead of the normal palette.")
private double topThreshold = 1.0;
public int getHeight(RNG rng, double x, double z, IrisData data) {
public int getHeight(RNG rng, double x, double z, PackRuntime runtime) {
if (stackMin == stackMax) {
return stackMin;
}
return getHeightGenerator(rng, data)
return getHeightGenerator(rng, runtime)
.fit(stackMin, stackMax,
x / heightVariance.getZoom(),
z / heightVariance.getZoom());
}
public CNG getHeightGenerator(RNG rng, IrisData data) {
AtomicCache<CNG> cache = generators(rng, data).height;
CNG cached = cache.getIfPresent();
return cached != null ? cached : cache.aquire(() ->
heightVariance.create(rng.nextParallelRNG(getBlockData(data).size() + stackMax + stackMin), data));
public CNG getHeightGenerator(RNG rng, PackRuntime runtime) {
return runtime.decorator(this).heightGenerator(rng.getSeed());
}
public CNG getGenerator(RNG rng, IrisData data) {
AtomicCache<CNG> cache = generators(rng, data).layer;
CNG cached = cache.getIfPresent();
return cached != null ? cached : cache.aquire(() -> style.create(rng.nextParallelRNG(getBlockData(data).size()), data));
public CNG getGenerator(RNG rng, PackRuntime runtime) {
return runtime.decorator(this).layerGenerator(rng.getSeed());
}
public CNG getVarianceGenerator(RNG rng, IrisData data) {
AtomicCache<CNG> cache = generators(rng, data).variance;
CNG cached = cache.getIfPresent();
return cached != null ? cached : cache.aquire(() -> createVarianceGenerator(rng, data));
public CNG getVarianceGenerator(RNG rng, PackRuntime runtime) {
return runtime.decorator(this).varianceGenerator(rng.getSeed());
}
private Generators generators(RNG rng, IrisData data) {
long seed = rng.getSeed();
Engine engine = data == null ? null : data.getEngine();
Generators recent = recentGenerators;
if (recent != null && recent.key.seed == seed && recent.key.data == data && recent.key.engine.refersTo(engine)) {
return recent;
}
Generators selected = generators.computeIfAbsent(new GeneratorKey(seed, data, EngineRef.of(engine)), Generators::new);
recentGenerators = selected;
return selected;
public CNG createHeightGenerator(long seed, PackRuntime runtime) {
return heightVariance.create(new RNG(seed).nextParallelRNG(getBlockData(runtime.data()).size() + stackMax + stackMin), runtime);
}
private CNG createVarianceGenerator(RNG rng, IrisData data) {
return variance.createNoCache(deriveVarianceSeed(rng, data), data).scale(1D / variance.getZoom());
public CNG createLayerGenerator(long seed, PackRuntime runtime) {
return style.create(new RNG(seed).nextParallelRNG(getBlockData(runtime.data()).size()), runtime);
}
public CNG createVarianceGenerator(long seed, PackRuntime runtime) {
return variance.createNoCache(deriveVarianceSeed(new RNG(seed), runtime.data()), runtime).scale(1D / variance.getZoom());
}
RNG deriveVarianceSeed(RNG rng, IrisData data) {
@@ -174,27 +160,32 @@ public class IrisDecorator {
return palette;
}
public boolean passesChanceGate(RNG rng, double x, double z, IrisData data) {
if (getBlockData(data).isEmpty()) {
public boolean passesChanceGate(RNG rng, double x, double z, PackRuntime runtime) {
return passesChanceGate(rng, x, z, runtime.decorator(this));
}
/** {@link #passesChanceGate(RNG, double, double, PackRuntime)} for a caller that already holds this decorator's runtime. */
public boolean passesChanceGate(RNG rng, double x, double z, DecoratorRuntime decoratorRuntime) {
if (getBlockData(decoratorRuntime.packRuntime().data()).isEmpty()) {
return false;
}
double xx = x / style.getZoom();
double zz = z / style.getZoom();
return getGenerator(rng, data).fitDouble(0D, 1D, xx, zz) <= chance;
return decoratorRuntime.layerGenerator(rng.getSeed()).fitDouble(0D, 1D, xx, zz) <= chance;
}
public NativeBlockState getBlockData(IrisBiome b, RNG rng, double x, double z, IrisData data) {
if (!passesChanceGate(rng, x, z, data)) {
public NativeBlockState getBlockData(IrisBiome b, RNG rng, double x, double z, PackRuntime runtime) {
if (!passesChanceGate(rng, x, z, runtime)) {
return null;
}
if (getBlockData(data).size() == 1) {
return getBlockData(data).get(0);
if (getBlockData(runtime.data()).size() == 1) {
return getBlockData(runtime.data()).get(0);
}
return getVarianceGenerator(rng, data).fit(getBlockData(data), z, x);
return getVarianceGenerator(rng, runtime).fit(getBlockData(runtime.data()), z, x);
}
public NativeBlockState getBlockData100(IrisBiome b, RNG rng, double x, double y, double z, IrisData data) {
KList<NativeBlockState> palette = getBlockData(data);
public NativeBlockState getBlockData100(IrisBiome b, RNG rng, double x, double y, double z, PackRuntime runtime) {
KList<NativeBlockState> palette = getBlockData(runtime.data());
if (palette.isEmpty()) {
IrisLogging.warnOnce("decorator-empty:" + b.getName(), "Empty Block Data for " + b.getName());
return null;
@@ -204,24 +195,24 @@ public class IrisDecorator {
return palette.get(0);
}
return getVarianceGenerator(rng, data).fit(palette, z, y, x); //X and Z must be switched
return getVarianceGenerator(rng, runtime).fit(palette, z, y, x); //X and Z must be switched
}
public NativeBlockState getBlockDataForTop(IrisBiome b, RNG rng, double x, double y, double z, IrisData data) {
KList<NativeBlockState> topPalette = getBlockDataTops(data);
public NativeBlockState getBlockDataForTop(IrisBiome b, RNG rng, double x, double y, double z, PackRuntime runtime) {
KList<NativeBlockState> topPalette = getBlockDataTops(runtime.data());
if (topPalette.isEmpty()) {
return getBlockData100(b, rng, x, y, z, data);
return getBlockData100(b, rng, x, y, z, runtime);
}
double xx = x / style.getZoom();
double zz = z / style.getZoom();
if (getGenerator(rng, data).fitDouble(0D, 1D, xx, zz) <= chance) { //Exclude y from here
if (getGenerator(rng, runtime).fitDouble(0D, 1D, xx, zz) <= chance) { //Exclude y from here
if (topPalette.size() == 1) {
return topPalette.get(0);
}
return getVarianceGenerator(rng, data).fit(topPalette, z, y, x); //X and Z must be switched
return getVarianceGenerator(rng, runtime).fit(topPalette, z, y, x); //X and Z must be switched
}
return null;
@@ -337,55 +328,30 @@ public class IrisDecorator {
return resolved;
}
public NativeBlockState pickBlockData(RNG rng, IrisData data, double x, double z) {
NativeBlockState[] arr = getBlockDataArray(data);
public NativeBlockState pickBlockData(RNG rng, PackRuntime runtime, double x, double z) {
NativeBlockState[] arr = getBlockDataArray(runtime.data());
if (arr.length == 0) {
return null;
}
if (arr.length == 1) {
return arr[0];
}
return arr[Math.abs((int) getVarianceGenerator(rng, data).fit(0, arr.length - 1, z, x))];
return arr[Math.abs((int) getVarianceGenerator(rng, runtime).fit(0, arr.length - 1, z, x))];
}
public NativeBlockState pickBlockDataTop(RNG rng, IrisData data, double x, double z) {
NativeBlockState[] arr = getBlockDataTopsArray(data);
public NativeBlockState pickBlockDataTop(RNG rng, PackRuntime runtime, double x, double z) {
NativeBlockState[] arr = getBlockDataTopsArray(runtime.data());
if (arr.length == 0) {
return pickBlockData(rng, data, x, z);
return pickBlockData(rng, runtime, x, z);
}
if (arr.length == 1) {
return arr[0];
}
return arr[Math.abs((int) getVarianceGenerator(rng, data).fit(0, arr.length - 1, z, x))];
return arr[Math.abs((int) getVarianceGenerator(rng, runtime).fit(0, arr.length - 1, z, x))];
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean isStacking() {
return getStackMax() > 1;
}
private static final class Generators {
private final GeneratorKey key;
private final AtomicCache<CNG> layer = new AtomicCache<>();
private final AtomicCache<CNG> variance = new AtomicCache<>();
private final AtomicCache<CNG> height = new AtomicCache<>();
private Generators(GeneratorKey key) {
this.key = key;
}
}
private record GeneratorKey(long seed, IrisData data, EngineRef engine) {
@Override
public boolean equals(Object other) {
return other instanceof GeneratorKey key
&& seed == key.seed && data == key.data && engine.equals(key.engine);
}
@Override
public int hashCode() {
return 31 * (31 * Long.hashCode(seed) + System.identityHashCode(data))
+ engine.hashCode();
}
}
}
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.block.IrisBlockData;
import art.arcane.iris.structure.object.IrisObject;
@@ -62,12 +63,10 @@ public class IrisDepositGenerator {
private static final long FNV_OFFSET_BASIS = 0xcbf29ce484222325L;
private static final long FNV_PRIME = 0x100000001b3L;
private final transient ConcurrentMap<ClumpCacheKey, KList<IrisObject>> objects = new ConcurrentHashMap<>();
private final transient AtomicCache<KList<NativeBlockState>> blockData = new AtomicCache<>();
private final transient AtomicCache<Boolean> ore = new AtomicCache<>();
private final transient AtomicCache<KSet<String>> replaceableBlockData = new AtomicCache<>();
private final transient AtomicCache<KSet<String>> surfaceReplaceableBlockData = new AtomicCache<>();
private final transient ConcurrentMap<ClumpCacheKey, KList<IrisObject>> scaledObjects = new ConcurrentHashMap<>();
@Required
@MinNumber(-8192)
@MaxNumber(8192)
@@ -145,54 +144,47 @@ public class IrisDepositGenerator {
@Description("If set to true, this deposit will replace bedrock")
private boolean replaceBedrock = false;
public IrisObject getClump(Engine engine, RNG rng, IrisData rdata) {
public IrisObject getClump(PackRuntime runtime, RNG rng) {
if (shape != IrisDepositShape.IRIS) {
return generateConfiguredClumpObject(rng, rdata, minSize, maxSize);
return generateConfiguredClumpObject(rng, runtime.data(), minSize, maxSize);
}
ClumpCacheKey cacheKey = new ClumpCacheKey(engine.getSeedManager().getDeposit(), minSize, maxSize);
KList<IrisObject> objects = this.objects.computeIfAbsent(cacheKey, key -> {
RNG rngv = new RNG(key.depositSeed() + stableClumpSalt(rdata));
KList<IrisObject> objectsf = new KList<>();
for (int i = 0; i < varience; i++) {
objectsf.add(generateClumpObject(
rngv.nextParallelRNG(2349 * i + 3598), rdata, key.minSize(), key.maxSize()));
}
return objectsf;
});
KList<IrisObject> objects = runtime.deposit(this).clumps();
return objects.get(rng.i(0, objects.size()));
}
public IrisObject getClump(Engine engine, RNG rng, IrisData rdata, double sizeMultiplier) {
public IrisObject getClump(PackRuntime runtime, RNG rng, double sizeMultiplier) {
if (sizeMultiplier == 1D) {
return getClump(engine, rng, rdata);
return getClump(runtime, rng);
}
int scaledMinSize = scaledDepositSize(minSize, sizeMultiplier);
int scaledMaxSize = scaledDepositSize(maxSize, sizeMultiplier);
if (shape != IrisDepositShape.IRIS) {
return generateConfiguredClumpObject(rng, rdata, scaledMinSize, scaledMaxSize);
return generateConfiguredClumpObject(rng, runtime.data(), scaledMinSize, scaledMaxSize);
}
ClumpCacheKey cacheKey = new ClumpCacheKey(
engine.getSeedManager().getDeposit(), scaledMinSize, scaledMaxSize);
KList<IrisObject> objects = scaledObjects.computeIfAbsent(cacheKey, key -> {
long sizeSeed = ((long) key.minSize() << 32) ^ (key.maxSize() & 0xffffffffL);
RNG rngv = new RNG(key.depositSeed() + stableClumpSalt(rdata) + sizeSeed);
KList<IrisObject> generated = new KList<>();
for (int i = 0; i < varience; i++) {
generated.add(generateClumpObject(
rngv.nextParallelRNG(2349 * i + 3598), rdata, key.minSize(), key.maxSize()));
}
return generated;
});
KList<IrisObject> objects = runtime.deposit(this).scaledClumps(scaledMinSize, scaledMaxSize);
return objects.get(rng.i(0, objects.size()));
}
public KList<IrisObject> createClumps(long depositSeed, IrisData rdata) {
return createClumpVariants(new RNG(depositSeed + stableClumpSalt(rdata)), rdata, minSize, maxSize);
}
public KList<IrisObject> createScaledClumps(long depositSeed, int scaledMinSize, int scaledMaxSize, IrisData rdata) {
long sizeSeed = ((long) scaledMinSize << 32) ^ (scaledMaxSize & 0xffffffffL);
return createClumpVariants(new RNG(depositSeed + stableClumpSalt(rdata) + sizeSeed), rdata, scaledMinSize, scaledMaxSize);
}
private KList<IrisObject> createClumpVariants(RNG rngv, IrisData rdata, int clumpMinSize, int clumpMaxSize) {
KList<IrisObject> variants = new KList<>();
for (int i = 0; i < varience; i++) {
variants.add(generateClumpObject(rngv.nextParallelRNG(2349 * i + 3598), rdata, clumpMinSize, clumpMaxSize));
}
return variants;
}
public int getMaxDimension() {
return Math.min(11, (int) Math.ceil(Math.cbrt(maxSize)));
}
@@ -279,7 +271,7 @@ public class IrisDepositGenerator {
}
/**
* Advances {@code rng} exactly as {@link #getClump(Engine, RNG, IrisData)} would and reports the clump's width
* Advances {@code rng} exactly as {@link #getClump(PackRuntime, RNG)} would and reports the clump's width
* and lowest block offset without building it, so a caller can reject the clump first and replay the build
* only for clumps it keeps. Returns null without drawing when the shape has no footprint path.
*/
@@ -682,9 +674,6 @@ public class IrisDepositGenerator {
return false;
}
record ClumpCacheKey(long depositSeed, int minSize, int maxSize) {
}
@FunctionalInterface
interface CellSink {
void add(int x, int y, int z);
@@ -1,7 +1,6 @@
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.value.IrisRange;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import art.arcane.volmlib.util.collection.KList;
@@ -11,20 +10,24 @@ import java.util.Arrays;
/**
* One ore list (a biome's, region's or dimension's surface or underground ores) indexed by Y. Each Y
* holds the generators whose range contains it, in list order, so resolving a block tries exactly
* the generators that could place there and still returns the first one that does.
* holds the indices of the generators whose range contains it, in list order, so resolving a block tries exactly
* the generators that could place there and still returns the first one that does. The seeded chance fields live in
* an {@link OreBandsRuntime}, aligned with {@link #generators()}.
*/
public final class IrisOreBands {
public static final IrisOreBands EMPTY = new IrisOreBands(new IrisOreGenerator[0], 0, -1, null);
private static final int MAXIMUM_INDEXED_HEIGHT = 8192;
private final IrisOreGenerator[] generators;
private final int[] everyGenerator;
private final int minY;
private final int maxY;
private final IrisOreGenerator[][] byY;
private final int[][] byY;
private IrisOreBands(IrisOreGenerator[] generators, int minY, int maxY, IrisOreGenerator[][] byY) {
private IrisOreBands(IrisOreGenerator[] generators, int minY, int maxY, int[][] byY) {
this.generators = generators;
this.everyGenerator = new int[generators.length];
Arrays.setAll(everyGenerator, index -> index);
this.minY = minY;
this.maxY = maxY;
this.byY = byY;
@@ -57,19 +60,19 @@ public final class IrisOreBands {
height > MAXIMUM_INDEXED_HEIGHT ? null : index(generators, minY, (int) height));
}
private static IrisOreGenerator[][] index(IrisOreGenerator[] generators, int minY, int height) {
IrisOreGenerator[][] byY = new IrisOreGenerator[height][];
IrisOreGenerator[] scratch = new IrisOreGenerator[generators.length];
IrisOreGenerator[] previous = null;
private static int[][] index(IrisOreGenerator[] generators, int minY, int height) {
int[][] byY = new int[height][];
int[] scratch = new int[generators.length];
int[] previous = null;
for (int offset = 0; offset < height; offset++) {
int y = minY + offset;
int count = 0;
for (IrisOreGenerator generator : generators) {
if (generator.getRange().contains(y)) {
scratch[count++] = generator;
for (int index = 0; index < generators.length; index++) {
if (generators[index].getRange().contains(y)) {
scratch[count++] = index;
}
}
IrisOreGenerator[] candidates = Arrays.copyOf(scratch, count);
int[] candidates = Arrays.copyOf(scratch, count);
byY[offset] = previous != null && Arrays.equals(previous, candidates) ? previous : candidates;
previous = byY[offset];
}
@@ -92,13 +95,18 @@ public final class IrisOreBands {
return y >= minY && y <= maxY;
}
/** The banded generators in list order; chance fields built for them must keep this order. */
public IrisOreGenerator[] generators() {
return generators.clone();
}
/**
* The ore placed at a Y inside {@link #contains(int)}, or null when no generator places one.
*/
public NativeBlockState generate(int x, int y, int z, RNG rng, IrisData data, Engine engine) {
IrisOreGenerator[] candidates = byY == null ? generators : byY[y - minY];
for (IrisOreGenerator candidate : candidates) {
NativeBlockState ore = candidate.generate(x, y, z, rng, data, engine);
NativeBlockState generate(int x, int y, int z, RNG rng, IrisOreGenerator.OreChance[] chances, PackRuntime runtime) {
int[] candidates = byY == null ? everyGenerator : byY[y - minY];
for (int index : candidates) {
NativeBlockState ore = generators[index].generate(x, y, z, rng, chances[index], runtime);
if (ore != null) {
return ore;
}
@@ -18,14 +18,13 @@
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.NoiseStyle;
import art.arcane.iris.generation.runtime.EngineRef;
import art.arcane.iris.generation.terrain.IrisMaterialPalette;
import art.arcane.iris.pack.value.IrisRange;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.cache.LazyBoundedCache;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.volmlib.util.documentation.Description;
import art.arcane.iris.pack.schema.annotation.MaxNumber;
@@ -57,72 +56,46 @@ public class IrisOreGenerator {
@Description("Vertical band (min, max) this ore can generate in, in engine-local Y where 0 is the bottom of the dimension, not world Y.")
private IrisRange range = new IrisRange(30, 80);
private final transient LazyBoundedCache<ChanceKey, OreChance> chanceCache = new LazyBoundedCache<>(32);
private transient volatile CachedChance recentChance;
public void warm(RNG rng, IrisData data) {
chance(rng, data);
palette.getLayerGenerator(rng, data);
public void warm(RNG rng, PackRuntime runtime) {
runtime.oreChance(this, rng.getSeed());
palette.getLayerGenerator(rng, runtime);
}
public NativeBlockState generate(int x, int y, int z, RNG rng, IrisData data) {
return generate(x, y, z, rng, data, data == null ? null : data.getEngine());
}
public NativeBlockState generate(int x, int y, int z, RNG rng, IrisData data, Engine engine) {
if (threshold <= 0 || !range.contains(y)) {
public NativeBlockState generate(int x, int y, int z, RNG rng, PackRuntime runtime) {
if (!canPlaceAt(y)) {
return null;
}
return placeByChance(x, y, z, rng, runtime.oreChance(this, rng.getSeed()), runtime);
}
if (palette.getPalette().isEmpty()) {
/** Places with a chance field already resolved for {@code rng}'s seed, as {@link OreBandsRuntime} holds them. */
public NativeBlockState generate(int x, int y, int z, RNG rng, OreChance chance, PackRuntime runtime) {
if (!canPlaceAt(y)) {
return null;
}
return placeByChance(x, y, z, rng, chance, runtime);
}
if (chance(rng, data, engine).sample(x, y, z) > threshold) {
private boolean canPlaceAt(int y) {
return threshold > 0 && range.contains(y) && !palette.getPalette().isEmpty();
}
private NativeBlockState placeByChance(int x, int y, int z, RNG rng, OreChance chance, PackRuntime runtime) {
if (chance.sample(x, y, z) > threshold) {
return null;
}
return palette.get(rng, x, y, z, data);
return palette.get(rng, x, y, z, runtime);
}
private OreChance chance(RNG rng, IrisData data) {
return chance(rng, data, data == null ? null : data.getEngine());
}
private OreChance chance(RNG rng, IrisData data, Engine engine) {
long seed = rng.getSeed();
CachedChance recent = recentChance;
if (recent != null && recent.key.seed == seed && recent.key.data == data && recent.key.engine.refersTo(engine)) {
return recent.chance;
}
ChanceKey key = new ChanceKey(seed, data, EngineRef.of(engine));
OreChance selected = chanceCache.computeIfAbsent(key, ignored -> OreChance.of(chanceStyle.create(rng, data)));
recentChance = new CachedChance(key, selected);
return selected;
}
private record ChanceKey(long seed, IrisData data, EngineRef engine) {
@Override
public boolean equals(Object other) {
return other instanceof ChanceKey key
&& seed == key.seed && data == key.data && engine.equals(key.engine);
}
@Override
public int hashCode() {
return 31 * (31 * Long.hashCode(seed) + System.identityHashCode(data))
+ engine.hashCode();
}
}
private record CachedChance(ChanceKey key, OreChance chance) {
public OreChance createChance(long seed, PackRuntime runtime) {
return OreChance.of(chanceStyle.create(new RNG(seed), runtime));
}
/**
* The chance field, with its single value resolved once when it is constant (a FLAT style),
* which bands such as a full deepslate layer sample at every block.
*/
private record OreChance(CNG noise, boolean constant, double value) {
public record OreChance(CNG noise, boolean constant, double value) {
private static OreChance of(CNG noise) {
boolean constant = noise.isConstant();
return new OreChance(noise, constant, constant ? noise.noise(0D, 0D, 0D) : 0D);
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.terrain.IrisMaterialPalette;
import art.arcane.iris.structure.object.IrisObject;
@@ -59,7 +60,7 @@ public final class IrisProceduralBlocks {
public static NativeBlockState resolve(String block, IrisMaterialPalette palette, IrisData data, int x, int y, int z, RNG paletteRng) {
if (paletteSet(palette)) {
return palette.get(paletteRng, x, y, z, data);
return palette.get(paletteRng, x, y, z, PackRuntime.forPack(data));
}
if (block != null && !block.isEmpty()) {
return B.getStateOrNull(block, false);
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.volmlib.util.hunk.Hunk;
@@ -42,27 +43,28 @@ public class IrisSeaFloorDecorator extends IrisEngineDecorator {
return;
}
RNG rng = getRNG(realX, realZ);
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ);
PackRuntime runtime = PackRuntime.of(getEngine(), getData());
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, runtime, realX, realZ);
if (decorator == null) {
return;
}
try {
place(decorator, x, z, realX, realZ, data, biome, height, max, limit);
place(decorator, x, z, realX, realZ, data, biome, height, max, limit, runtime);
} catch (Throwable e) {
DecoratorCore.skip(e, decorator, getData(), realX, height, realZ, biome);
}
}
private void place(IrisDecorator decorator, int x, int z, int realX, int realZ, Hunk<NativeBlockState> data,
IrisBiome biome, int height, int max, int limit) {
IrisBiome biome, int height, int max, int limit, PackRuntime runtime) {
if (!decorator.isStacking()) {
if (!decorator.isForcePlace() && !decorator.getSlopeCondition().isDefault()
&& !decorator.getSlopeCondition().isValid(getComplex().getSlopeStream().get(realX, realZ))) {
return;
}
NativeBlockState block = decorator.getBlockData100(biome, partRNG, realX, height, realZ, getData());
NativeBlockState block = decorator.getBlockData100(biome, partRNG, realX, height, realZ, runtime);
if (block != null) {
data.set(x, height, z, block);
}
@@ -70,13 +72,13 @@ public class IrisSeaFloorDecorator extends IrisEngineDecorator {
}
int stack = Math.min(limit - height,
DecoratorCore.computeStack(decorator, partRNG, realX, realZ, getData(), max - height));
DecoratorCore.computeStack(decorator, partRNG, realX, realZ, runtime, max - height));
for (int i = 0; i < stack; i++) {
int h = height + i;
double threshold = stack == 1 ? 1.0 : ((double) i) / (stack - 1);
NativeBlockState block = threshold >= decorator.getTopThreshold()
? decorator.getBlockDataForTop(biome, partRNG, realX, h, realZ, getData())
: decorator.getBlockData100(biome, partRNG, realX, h, realZ, getData());
? decorator.getBlockDataForTop(biome, partRNG, realX, h, realZ, runtime)
: decorator.getBlockData100(biome, partRNG, realX, h, realZ, runtime);
if (block == null) {
break;
}
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.volmlib.util.hunk.Hunk;
@@ -42,25 +43,26 @@ public class IrisSeaSurfaceDecorator extends IrisEngineDecorator {
return;
}
RNG rng = getRNG(realX, realZ);
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ);
PackRuntime runtime = PackRuntime.of(getEngine(), getData());
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, runtime, realX, realZ);
if (decorator == null) {
return;
}
try {
place(decorator, x, z, realX, realZ, data, biome, height, max, maxBaseY);
place(decorator, x, z, realX, realZ, data, biome, height, max, maxBaseY, runtime);
} catch (Throwable e) {
DecoratorCore.skip(e, decorator, getData(), realX, height, realZ, biome);
}
}
private void place(IrisDecorator decorator, int x, int z, int realX, int realZ, Hunk<NativeBlockState> data,
IrisBiome biome, int height, int max, int maxBaseY) {
IrisBiome biome, int height, int max, int maxBaseY, PackRuntime runtime) {
if (!decorator.isStacking()) {
int targetY = height + 1;
if (DecoratorCore.canReplaceStackTarget(data.get(x, targetY, z), false)) {
NativeBlockState block = decorator.getBlockData100(biome, partRNG, realX, height, realZ, getData());
NativeBlockState block = decorator.getBlockData100(biome, partRNG, realX, height, realZ, runtime);
if (block != null) {
data.set(x, targetY, z, block);
}
@@ -69,7 +71,7 @@ public class IrisSeaSurfaceDecorator extends IrisEngineDecorator {
}
int stack = Math.min(maxBaseY - height,
DecoratorCore.computeStack(decorator, partRNG, realX, realZ, getData(), max - height));
DecoratorCore.computeStack(decorator, partRNG, realX, realZ, runtime, max - height));
for (int i = 0; i < stack; i++) {
int h = height + i;
int targetY = h + 1;
@@ -78,8 +80,8 @@ public class IrisSeaSurfaceDecorator extends IrisEngineDecorator {
}
double threshold = stack == 1 ? 1.0 : ((double) i) / (stack - 1);
NativeBlockState block = threshold >= decorator.getTopThreshold()
? decorator.getBlockDataForTop(biome, partRNG, realX, h, realZ, getData())
: decorator.getBlockData100(biome, partRNG, realX, h, realZ, getData());
? decorator.getBlockDataForTop(biome, partRNG, realX, h, realZ, runtime)
: decorator.getBlockData100(biome, partRNG, realX, h, realZ, runtime);
if (block == null) {
break;
}
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.volmlib.util.hunk.Hunk;
@@ -78,7 +79,8 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator {
int max
) {
RNG rng = getRNG(realX, realZ);
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ);
PackRuntime runtime = PackRuntime.of(getEngine(), getData());
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, runtime, realX, realZ);
if (decorator == null) {
return;
@@ -90,14 +92,14 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator {
}
try {
placePicked(decorator, x, z, realX, realZ, data, biome, height, max);
placePicked(decorator, x, z, realX, realZ, data, biome, height, max, runtime);
} catch (Throwable e) {
DecoratorCore.skip(e, decorator, getData(), realX, height, realZ, biome);
}
}
private void placePicked(IrisDecorator decorator, int x, int z, int realX, int realZ, Hunk<NativeBlockState> data,
IrisBiome biome, int height, int max) {
IrisBiome biome, int height, int max, PackRuntime runtime) {
NativeBlockState support = data.get(x, height, z);
if (support == null || !support.isSolid()) {
return;
@@ -111,7 +113,7 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator {
|| !DecoratorCore.canReplaceStackTarget(data.get(x, targetY, z), false)) {
return;
}
NativeBlockState block = decorator.getBlockData100(biome, partRNG, realX, height, realZ, getData());
NativeBlockState block = decorator.getBlockData100(biome, partRNG, realX, height, realZ, runtime);
if (block != null && DecoratorCore.isValidShorelineSupport(decorator, block, support)
&& IrisSugarCane.canPlace(block, data, x, targetY, z, realX, realZ, getEngine())) {
data.set(x, targetY, z, block);
@@ -120,7 +122,7 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator {
return;
}
int stack = DecoratorCore.computeStack(decorator, partRNG, realX, realZ, getData(), max - height);
int stack = DecoratorCore.computeStack(decorator, partRNG, realX, realZ, runtime, max - height);
if (stack == 1) {
int targetY = height + 1;
@@ -128,7 +130,7 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator {
return;
}
NativeBlockState block = decorator.getBlockDataForTop(biome, partRNG, realX, height, realZ, getData());
NativeBlockState block = decorator.getBlockDataForTop(biome, partRNG, realX, height, realZ, runtime);
if (block != null && DecoratorCore.isValidShorelineSupport(decorator, block, support)
&& IrisSugarCane.canPlace(block, data, x, targetY, z, realX, realZ, getEngine())) {
data.set(x, targetY, z, block);
@@ -146,8 +148,8 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator {
}
double threshold = ((double) i) / (stack - 1);
NativeBlockState block = threshold >= decorator.getTopThreshold()
? decorator.getBlockDataForTop(biome, partRNG, realX, h, realZ, getData())
: decorator.getBlockData100(biome, partRNG, realX, h, realZ, getData());
? decorator.getBlockDataForTop(biome, partRNG, realX, h, realZ, runtime)
: decorator.getBlockData100(biome, partRNG, realX, h, realZ, runtime);
if (block == null) {
break;
}
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.biome.IrisBiome;
@@ -79,7 +80,7 @@ final class IrisSugarCane {
}
IrisBiome biome = complex.getTrueBiomeStream().get(x, z);
KList<NativeBlockState> layers = biome.generateSeaLayers(x, z,
new RNG(engine.getSeedManager().getTerrain()), fluidHeight - terrainHeight, engine.getData());
new RNG(engine.getSeedManager().getTerrain()), fluidHeight - terrainHeight, PackRuntime.of(engine));
int depth = fluidHeight - y;
return supportsAdjacent(layers.hasIndex(depth) ? layers.get(depth) : complex.resolveSeaFluid(x, z));
}
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.context.ChunkContext;
@@ -73,21 +74,22 @@ public class IrisSurfaceDecorator extends IrisEngineDecorator {
}
boolean caveSkipFluid = skipsFluid(inferredType);
RNG rng = getRNG(realX, realZ);
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ);
PackRuntime runtime = PackRuntime.of(getEngine(), getData());
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, runtime, realX, realZ);
if (decorator == null || !isSlopeValid(decorator, realX, height, realZ)) {
return;
}
try {
place(decorator, x, z, realX, realZ, data, height, max, underwater, fluidHeight, caveSkipFluid);
place(decorator, x, z, realX, realZ, data, height, max, underwater, fluidHeight, caveSkipFluid, runtime);
} catch (Throwable e) {
DecoratorCore.skip(e, decorator, getData(), realX, height, realZ, biome);
}
}
private void place(IrisDecorator decorator, int x, int z, int realX, int realZ, Hunk<NativeBlockState> data,
int height, int max, boolean underwater, int fluidHeight, boolean caveSkipFluid) {
int height, int max, boolean underwater, int fluidHeight, boolean caveSkipFluid, PackRuntime runtime) {
AquaticPlacementSnapshot aquaticSnapshot = captureAquaticPlacement(
decorator, getData(), data, x, z, height, max);
if (decorator.isStacking()) {
@@ -96,14 +98,18 @@ public class IrisSurfaceDecorator extends IrisEngineDecorator {
opts.underwater = underwater;
opts.fluidHeight = fluidHeight;
opts.caveSkipFluid = caveSkipFluid;
DecoratorCore.placeStackUp(decorator, x, z, realX, realZ, height, max, data, partRNG, getData(), opts,
getEngine().getMantle());
opts.mantle = getEngine().getMantle();
try {
DecoratorCore.placeStackUp(decorator, x, z, realX, realZ, height, max, data, partRNG, runtime, opts);
} finally {
opts.mantle = null;
}
aquaticSnapshot.restoreIfUnsupported(data, x, z);
return;
}
DecoratorCore.placeSurfaceSingle(decorator, x, z, realX, height, realZ,
data, partRNG, getData(), underwater, caveSkipFluid, getEngine().getMantle());
data, partRNG, runtime, underwater, caveSkipFluid, getEngine().getMantle());
aquaticSnapshot.restoreIfUnsupported(data, x, z);
}
@@ -0,0 +1,68 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* 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 <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import art.arcane.volmlib.util.math.RNG;
/**
* What one engine derives from an {@link IrisOreBands} for one seed: the chance field of every banded generator,
* resolved once so placing ores block by block reads plain fields instead of looking each generator up.
*/
public final class OreBandsRuntime {
private final IrisOreBands bands;
private final PackRuntime runtime;
private final IrisOreGenerator.OreChance[] chances;
public OreBandsRuntime(IrisOreBands bands, long seed, PackRuntime runtime) {
this.bands = bands;
this.runtime = runtime;
IrisOreGenerator[] generators = bands.generators();
this.chances = new IrisOreGenerator.OreChance[generators.length];
for (int index = 0; index < generators.length; index++) {
chances[index] = runtime.oreChance(generators[index], seed);
}
}
public IrisOreBands bands() {
return bands;
}
public boolean hasOres() {
return bands.hasOres();
}
public int lowestY() {
return bands.lowestY();
}
public int highestY() {
return bands.highestY();
}
public boolean contains(int y) {
return bands.contains(y);
}
/** The ore placed at a Y inside {@link #contains(int)}, or null when no generator places one. */
public NativeBlockState generate(int x, int y, int z, RNG rng) {
return bands.generate(x, y, z, rng, chances, runtime);
}
}
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.decoration.formation;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.terrain.IrisMaterialPalette;
import art.arcane.iris.generation.decoration.IrisProceduralBlocks;
@@ -59,7 +60,7 @@ public final class FormationBlockResolver {
strataRng = new RNG(formation.getSeed() + band * 31L);
strataRngs.put(band, strataRng);
}
NativeBlockState strataState = strata.get(strataRng, x, band, z, data);
NativeBlockState strataState = strata.get(strataRng, x, band, z, PackRuntime.forPack(data));
if (strataState != null) {
return strataState;
}
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.decoration.tree;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.terrain.IrisMaterialPalette;
import art.arcane.iris.generation.decoration.IrisProceduralBlocks;
@@ -84,7 +85,7 @@ public final class TreeBlockResolver {
private static NativeBlockState resolveSecondaryLeaf(IrisProceduralTree tree, IrisData data, TreeBlockCanvas.Vec pos, RNG paletteRng) {
if (IrisProceduralBlocks.paletteSet(tree.getSecondaryLeavesPalette())) {
return tree.getSecondaryLeavesPalette().get(paletteRng, pos.x(), pos.y(), pos.z(), data);
return tree.getSecondaryLeavesPalette().get(paletteRng, pos.x(), pos.y(), pos.z(), PackRuntime.forPack(data));
}
if (tree.getWeightedSecondaryLeaves() != null && !tree.getWeightedSecondaryLeaves().isEmpty()) {
String picked = pickWeighted(tree, new RNG(tree.getSeed() ^ positionHash(pos)));
@@ -117,7 +118,7 @@ public final class TreeBlockResolver {
private static NativeBlockState resolveBlock(String block, IrisMaterialPalette palette, IrisData data, TreeBlockCanvas.Vec pos, RNG paletteRng) {
if (IrisProceduralBlocks.paletteSet(palette)) {
return palette.get(paletteRng, pos.x(), pos.y(), pos.z(), data);
return palette.get(paletteRng, pos.x(), pos.y(), pos.z(), PackRuntime.forPack(data));
}
if (block != null && !block.isEmpty()) {
return B.getStateOrNull(block, false);
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.hydrology.engine;
import art.arcane.iris.generation.runtime.ThreadSlots;
import art.arcane.iris.generation.runtime.HydrologyPlanException;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.concurrent.MultiBurst;
@@ -78,7 +79,7 @@ public final class HydrologyRuntime {
private final NaturalHeights naturalHeight;
private final BooleanSupplier mainThread;
private final RasterLru rasters;
private final ThreadLocal<LastRaster> last;
private final ThreadSlots<LastRaster> last;
private final Set<Long> queued;
private final ConcurrentHashMap<Long, CompletableFuture<ChunkWaterRaster>> building;
private final RasterFailures failures;
@@ -132,7 +133,7 @@ public final class HydrologyRuntime {
this.naturalHeight = Objects.requireNonNull(naturalHeight, "naturalHeight");
this.mainThread = Objects.requireNonNull(mainThread, "mainThread");
this.rasters = new RasterLru();
this.last = ThreadLocal.withInitial(LastRaster::new);
this.last = new ThreadSlots<>(LastRaster::new);
this.queued = ConcurrentHashMap.newKeySet();
this.building = new ConcurrentHashMap<>();
this.failures = new RasterFailures(ticker);
@@ -60,7 +60,7 @@ public final class IrisHydrologyTerrainSource implements HydrologyTerrainSource,
this.focus = complex.getFocusBiome();
this.binding = Objects.requireNonNull(binding, "binding");
this.climate = settings.climate();
this.wetness = climate.enabled() ? climate.style().create(settings.seed() ^ SALT_CLIMATE, complex.getData()) : null;
this.wetness = climate.enabled() ? climate.style().create(settings.seed() ^ SALT_CLIMATE, complex.getPackRuntime()) : null;
}
@Override
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.mantle;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.cache.Cache;
import art.arcane.iris.generation.runtime.Engine;
@@ -32,6 +33,7 @@ import org.jetbrains.annotations.Nullable;
final class FloatingIslandSampleResolver implements IslandObjectPlacer.SampleProvider {
private final IrisData data;
private final Engine engine;
private final PackRuntime runtime;
private final int chunkHeight;
private final long baseSeed;
private final FloatingIslandBoundarySampler boundarySampler;
@@ -41,6 +43,7 @@ final class FloatingIslandSampleResolver implements IslandObjectPlacer.SamplePro
FloatingIslandSampleResolver(EngineMantle engineMantle, FloatingIslandBoundarySampler boundarySampler) {
this.data = engineMantle.getData();
this.engine = engineMantle.getEngine();
this.runtime = PackRuntime.of(engine, data);
this.chunkHeight = engine.getHeight();
this.baseSeed = engine.getSeedManager().getTerrain() ^ IrisFloatingChildBiomeModifier.FLOATING_BASE_SEED_SALT;
this.boundarySampler = boundarySampler;
@@ -48,6 +51,10 @@ final class FloatingIslandSampleResolver implements IslandObjectPlacer.SamplePro
this.resolvedSamples = new LongOpenHashSet();
}
PackRuntime runtime() {
return runtime;
}
@Override
public @Nullable FloatingIslandSample sample(int x, int z) {
long key = Cache.key(x, z);
@@ -59,7 +66,7 @@ final class FloatingIslandSampleResolver implements IslandObjectPlacer.SamplePro
resolvedSamples.add(key);
return null;
}
FloatingIslandSample sample = FloatingIslandSample.sample(parent, x, z, chunkHeight, baseSeed, data, engine, boundarySampler);
FloatingIslandSample sample = FloatingIslandSample.sample(parent, x, z, chunkHeight, baseSeed, runtime, boundarySampler);
resolvedSamples.add(key);
if (sample != null) {
sampleCache.put(key, sample);
@@ -18,6 +18,8 @@
package art.arcane.iris.generation.mantle;
import art.arcane.iris.generation.runtime.ThreadSlots;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.GenerationCounter;
@@ -78,6 +80,7 @@ public class IrisCaveCarver3D {
private final Engine engine;
private final IrisData data;
private final PackRuntime runtime;
private final IrisCaveProfile profile;
private final NoiseProgram baseDensity;
private final NoiseProgram detailDensity;
@@ -108,8 +111,8 @@ public class IrisCaveCarver3D {
private final int verticalDensityStep;
private final int worldMinimumY;
private final int densityMaximumY;
private final ThreadLocal<Boolean> carving = ThreadLocal.withInitial(() -> false);
private final ThreadLocal<CaveCarveScratch> scratchCache = ThreadLocal.withInitial(CaveCarveScratch::new);
private final ThreadSlots<Boolean> carving = new ThreadSlots<>(() -> false);
private final ThreadSlots<CaveCarveScratch> scratchCache = new ThreadSlots<>(CaveCarveScratch::new);
private final CaveDensityGrid densityGrid;
private final CaveDensityGrid.Owner densityOwner;
private final CaveDensityGrid.Owner warpOwner;
@@ -122,6 +125,7 @@ public class IrisCaveCarver3D {
this.engine = engine;
this.densityGrid = densityGrid;
this.data = engine.getData();
this.runtime = PackRuntime.of(engine, data);
this.profile = profile;
this.carveAir = new MatterCavern(true, "", LIQUID_AIR);
this.carveFluid = new MatterCavern(true, "", LIQUID_FLUID);
@@ -130,10 +134,10 @@ public class IrisCaveCarver3D {
List<CaveFieldModuleState> moduleStates = new ArrayList<>();
RNG baseRng = new RNG(engine.getSeedManager().getCarve());
this.baseDensity = NoiseProgram.compileSigned3D(profile.getBaseDensityStyle().create(baseRng.nextParallelRNG(934_447), data));
this.detailDensity = NoiseProgram.compileSigned3D(profile.getDetailDensityStyle().create(baseRng.nextParallelRNG(612_991), data));
this.warpDensity = NoiseProgram.compileSigned3D(profile.getWarpStyle().create(baseRng.nextParallelRNG(770_713), data));
this.surfaceBreakDensity = profile.getSurfaceBreakStyle().create(baseRng.nextParallelRNG(341_219), data);
this.baseDensity = NoiseProgram.compileSigned3D(profile.getBaseDensityStyle().create(baseRng.nextParallelRNG(934_447), runtime));
this.detailDensity = NoiseProgram.compileSigned3D(profile.getDetailDensityStyle().create(baseRng.nextParallelRNG(612_991), runtime));
this.warpDensity = NoiseProgram.compileSigned3D(profile.getWarpStyle().create(baseRng.nextParallelRNG(770_713), runtime));
this.surfaceBreakDensity = profile.getSurfaceBreakStyle().create(baseRng.nextParallelRNG(341_219), runtime);
this.thresholdRng = baseRng.nextParallelRNG(489_112);
this.baseWeight = profile.getBaseWeight();
this.detailWeight = profile.getDetailWeight();
@@ -149,7 +153,7 @@ public class IrisCaveCarver3D {
double weight = Math.abs(baseWeight) + Math.abs(detailWeight);
int index = 0;
for (IrisCaveFieldModule module : profile.getModules()) {
CNG moduleDensity = module.getStyle().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), data);
CNG moduleDensity = module.getStyle().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), runtime);
CaveFieldModuleState state = new CaveFieldModuleState(module, NoiseProgram.compileSigned3D(moduleDensity));
moduleStates.add(state);
weight += Math.abs(state.weight);
@@ -342,7 +346,7 @@ public class IrisCaveCarver3D {
} else if (densityThreshold.getStyle().isFlat()) {
constantThreshold = M.lerp(thresholdMin, thresholdMax, 0.5);
} else {
thresholdDensity = densityThreshold.getStyle().create(thresholdRng, data);
thresholdDensity = densityThreshold.getStyle().create(thresholdRng, runtime);
}
for (int lx = 0; lx < 16; lx++) {
@@ -26,7 +26,7 @@ import art.arcane.volmlib.util.structure.StructureCarveEnvelope;
import art.arcane.volmlib.nativelib.terrain.structure.StructureWaterRules;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.cache.Cache;
import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.iris.generation.runtime.GenerationFailures;
@@ -197,6 +197,7 @@ public class IrisStructureComponent extends IrisMantleComponent {
settings.getPalette(), "Structure stilt palette must not be null");
int mantleOffset = getEngineMantle().getEngine().getMinHeight();
int maxDepth = Math.max(1, settings.getMaxDepth());
PackRuntime runtime = PackRuntime.of(getEngineMantle().getEngine(), getData());
for (Long2IntMap.Entry column : columns.long2IntEntrySet()) {
int worldX = StructureFoundationPlanner.unpackX(column.getLongKey());
int worldZ = StructureFoundationPlanner.unpackZ(column.getLongKey());
@@ -225,16 +226,16 @@ public class IrisStructureComponent extends IrisMantleComponent {
}
StructureFoundationPlanner.fillSupportColumn(foundationY, groundY, y -> {
writeFoundationSupport(
writer, palette, rng, getData(), worldX, y, worldZ, mantleOffset);
writer, palette, rng, runtime, worldX, y, worldZ, mantleOffset);
});
}
}
static void writeFoundationSupport(MantleWriter writer, IrisMaterialPalette palette, RNG rng,
IrisData data, int worldX, int mantleY, int worldZ,
PackRuntime runtime, int worldX, int mantleY, int worldZ,
int mantleOffset) {
int worldY = mantleY + mantleOffset;
NativeBlockState support = palette.get(rng, worldX, worldY, worldZ, data);
NativeBlockState support = palette.get(rng, worldX, worldY, worldZ, runtime);
if (support == null) {
throw new IllegalStateException("Structure stilt palette resolved no block at "
+ worldX + "," + worldY + "," + worldZ);
@@ -152,7 +152,7 @@ public class MantleCarvingComponent extends IrisMantleComponent {
private void generateLayer(MantleWriter writer, int x, int z, ChunkContext context, BlendScratch blendScratch) {
IrisComplex complex = context.getComplex();
IrisDimensionCarvingResolver.State resolverState = blendScratch.resolverState;
IrisDimensionCarvingResolver.State resolverState = IrisDimensionCarvingResolver.threadState(getEngineMantle().getEngine());
int[] chunkSurfaceHeights = prepareChunkSurfaceHeights(x, z, context, blendScratch.chunkSurfaceHeights);
PrecisionStopwatch resolveStopwatch = PrecisionStopwatch.start();
List<WeightedProfile> weightedProfiles = resolveWeightedProfiles(x, z, complex, resolverState);
@@ -766,7 +766,6 @@ public class MantleCarvingComponent extends IrisMantleComponent {
private final double[][] neighbourHeights = new double[NEIGHBOURS][CHUNK_AREA];
private final Object[][] neighbourObjects = new Object[NEIGHBOURS][CHUNK_AREA];
private final long[][] neighbourSubmerged = new long[NEIGHBOURS][4];
private final IrisDimensionCarvingResolver.State resolverState = new IrisDimensionCarvingResolver.State();
private int nextWeightBuffer;
private boolean inUse;
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.mantle;
import art.arcane.iris.generation.runtime.PackRuntime;
import java.io.UncheckedIOException;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.GenerationFailures;
@@ -76,7 +77,7 @@ public class MantleFloatingObjectComponent extends IrisMantleComponent {
RNG chunkRng = new RNG(Cache.key(x, z) + seed() + 0x0FA710BEL);
FloatingIslandSampleResolver sampleResolver = new FloatingIslandSampleResolver(getEngineMantle(), context.getFloatingIslandBoundarySampler());
FloatingIslandSample.clearChunkMemo();
FloatingIslandSample.clearChunkMemo(sampleResolver.runtime());
FloatingIslandSample[] samples = new FloatingIslandSample[256];
for (int xf = 0; xf < 16; xf++) {
@@ -180,7 +181,7 @@ public class MantleFloatingObjectComponent extends IrisMantleComponent {
if (placement.isCompatExcluded(data)) {
return;
}
int density = placement.getDensity(rng, minX, minZ, data);
int density = placement.getDensity(rng, minX, minZ, PackRuntime.of(getEngineMantle().getEngine(), data));
double perAttempt = placement.getChance();
for (int i = 0; i < density; i++) {
if (!rng.chance(perAttempt + rng.d(-0.005, 0.005))) {
@@ -249,7 +250,7 @@ public class MantleFloatingObjectComponent extends IrisMantleComponent {
if (placement.isCompatExcluded(data)) {
return;
}
int density = placement.getDensity(rng, minX, minZ, data);
int density = placement.getDensity(rng, minX, minZ, PackRuntime.of(getEngineMantle().getEngine(), data));
double perAttempt = placement.getChance();
for (int i = 0; i < density; i++) {
@@ -345,7 +346,7 @@ public class MantleFloatingObjectComponent extends IrisMantleComponent {
if (placement.isCompatExcluded(data)) {
return;
}
int density = placement.getDensity(rng, minX, minZ, data);
int density = placement.getDensity(rng, minX, minZ, PackRuntime.of(getEngineMantle().getEngine(), data));
double perAttempt = placement.getChance();
for (int i = 0; i < density; i++) {
@@ -19,6 +19,7 @@
package art.arcane.iris.generation.mantle;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.generation.block.B;
import art.arcane.iris.generation.cache.Cache;
@@ -959,7 +960,7 @@ public class MantleObjectComponent extends IrisMantleComponent {
int rejected = 0;
int nullObjects = 0;
int errors = 0;
int density = objectPlacement.getDensity(rng, x, z, getData());
int density = objectPlacement.getDensity(rng, x, z, PackRuntime.of(getEngineMantle().getEngine(), getData()));
boolean golden = GoldenDebugObjectPlacer.isGoldenDebugChunk(chunkX, chunkZ);
for (int i = 0; i < density; i++) {
@@ -1094,7 +1095,7 @@ public class MantleObjectComponent extends IrisMantleComponent {
int errors = 0;
int minX = chunkX << 4;
int minZ = chunkZ << 4;
int density = objectPlacement.getDensity(rng, minX, minZ, getData());
int density = objectPlacement.getDensity(rng, minX, minZ, PackRuntime.of(getEngineMantle().getEngine(), getData()));
IrisCaveAnchorMode anchorMode = resolveAnchorMode(objectPlacement, caveProfile);
if (objectPlacement.getMode() == ObjectPlaceMode.CEILING_HANG) {
anchorMode = IrisCaveAnchorMode.CEILING;
@@ -1328,7 +1329,7 @@ public class MantleObjectComponent extends IrisMantleComponent {
int chunkHeight = getEngineMantle().getEngine().getHeight();
int minX = chunkX << 4;
int minZ = chunkZ << 4;
int density = objectPlacement.getDensity(rng, minX, minZ, getData());
int density = objectPlacement.getDensity(rng, minX, minZ, PackRuntime.of(getEngineMantle().getEngine(), getData()));
for (int i = 0; i < density; i++) {
IrisObject v = objectPlacement.scaleObject(rng, objectPlacement.getObject(upperCtx, rng), upperCtx.getDimension());
@@ -1734,7 +1735,7 @@ public class MantleObjectComponent extends IrisMantleComponent {
@BlockCoordinates
private Set<String> guessPlacedKeys(RNG rng, int x, int z, IrisObjectPlacement objectPlacement) {
Set<String> f = new KSet<>();
for (int i = 0; i < objectPlacement.getDensity(rng, x, z, getData()); i++) {
for (int i = 0; i < objectPlacement.getDensity(rng, x, z, PackRuntime.of(getEngineMantle().getEngine(), getData())); i++) {
IrisObject v = objectPlacement.scaleObject(rng, objectPlacement.getObject(getComplex(), rng), getDimension());
if (v == null) {
continue;
@@ -19,6 +19,7 @@
package art.arcane.iris.generation.mantle;
import art.arcane.iris.generation.runtime.ThreadSlots;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.structure.object.ObjectWaterRule;
import art.arcane.iris.world.storage.matter.TileWrapper;
@@ -84,14 +85,14 @@ public class MantleWriter implements ObjectPassPlacer, AutoCloseable {
@Setter(AccessLevel.NONE)
@EqualsAndHashCode.Exclude
@ToString.Exclude
private final ThreadLocal<Integer> activeComponentPriority = new ThreadLocal<>();
private final ThreadSlots<Integer> activeComponentPriority = ThreadSlots.bindings();
@Getter(AccessLevel.NONE)
private final ThreadLocal<ObjectPlacementCapture> objectPlacementCapture = new ThreadLocal<>();
private final ThreadSlots<ObjectPlacementCapture> objectPlacementCapture = ThreadSlots.bindings();
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
@EqualsAndHashCode.Exclude
@ToString.Exclude
private final ThreadLocal<ObjectWater> objectWater = new ThreadLocal<>();
private final ThreadSlots<ObjectWater> objectWater = ThreadSlots.bindings();
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
@EqualsAndHashCode.Exclude
@@ -24,9 +24,9 @@ import art.arcane.volmlib.util.math.RNG;
public class ExpressionNoise implements NoiseGenerator {
private final RNG rng;
private final IrisExpression expression;
private final ExpressionRuntime expression;
public ExpressionNoise(RNG rng, IrisExpression expression) {
public ExpressionNoise(RNG rng, ExpressionRuntime expression) {
this.rng = rng;
this.expression = expression;
}
@@ -0,0 +1,258 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* 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 <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.SeedTable;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG;
import art.arcane.volmlib.util.stream.ProceduralStream;
import art.arcane.volmlib.util.stream.interpolation.Interpolated;
import com.dfsek.paralithic.Expression;
import com.dfsek.paralithic.functions.dynamic.Context;
import com.dfsek.paralithic.functions.dynamic.DynamicFunction;
import com.dfsek.paralithic.node.Statefulness;
import lombok.NonNull;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Objects;
/**
* An {@link IrisExpression} parsed for one runtime scope: its functions and variables read that scope's engine
* streams and seeded styles, so the parsed expression belongs to the scope and not to the pack object.
*/
public final class ExpressionRuntime {
private static final int SEED_CAPACITY = 8;
private static final int MAX_RETAINED_EVALUATION_DEPTH = 8;
private static final int MAX_RETAINED_ARGUMENTS = 256;
private static final ThreadLocal<EvaluationScratch> EVALUATION_SCRATCH =
ThreadLocal.withInitial(EvaluationScratch::new);
private final VariableRuntime[] variables;
private final Expression parsed;
private final SeedTable<ProceduralStream<Double>> streams;
public ExpressionRuntime(IrisExpression expression, PackRuntime runtime) {
this.variables = expression.getVariables().stream()
.map(variable -> new VariableRuntime(variable, runtime))
.toArray(VariableRuntime[]::new);
this.parsed = expression.parse(function -> new FunctionRuntime(function, runtime));
this.streams = new SeedTable<>(SEED_CAPACITY, seed -> {
RNG streamRng = new RNG(seed);
return ProceduralStream.of((x, z) -> evaluate(streamRng, x, z),
(x, y, z) -> evaluate(streamRng, x, y, z), Interpolated.DOUBLE);
});
}
public ProceduralStream<Double> stream(RNG rng) {
return streams.get(rng.getSeed());
}
public double evaluate(RNG rng, double x, double z) {
EvaluationScratch scratch = EVALUATION_SCRATCH.get();
double[] arguments = scratch.acquire(3 + variables.length);
try {
int index = 0;
for (VariableRuntime variable : variables) {
arguments[index++] = variable.value(rng, x, z);
}
arguments[index++] = x;
arguments[index++] = z;
arguments[index] = -1;
return parsed.evaluate(new FunctionContext(rng), arguments);
} finally {
scratch.release();
}
}
public double evaluate(RNG rng, double x, double y, double z) {
EvaluationScratch scratch = EVALUATION_SCRATCH.get();
double[] arguments = scratch.acquire(3 + variables.length);
try {
int index = 0;
for (VariableRuntime variable : variables) {
arguments[index++] = variable.value(rng, x, y, z);
}
arguments[index++] = x;
arguments[index++] = y;
arguments[index] = z;
return parsed.evaluate(new FunctionContext(rng), arguments);
} finally {
scratch.release();
}
}
public record FunctionContext(@NonNull RNG rng) implements Context {
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
FunctionContext that = (FunctionContext) o;
return rng.getSeed() == that.rng.getSeed();
}
@Override
public int hashCode() {
return Long.hashCode(rng.getSeed());
}
}
private static Engine requireEngine(PackRuntime runtime, String kind, String name) {
Engine engine = runtime.engine();
if (engine == null) {
throw new IllegalStateException("Expression " + kind + " '" + name + "' requires an active Iris engine.");
}
return engine;
}
private static final class FunctionRuntime implements DynamicFunction {
private final IrisExpressionFunction function;
private final PackRuntime runtime;
private final SeedTable<Provider> providers;
private FunctionRuntime(IrisExpressionFunction function, PackRuntime runtime) {
this.function = function;
this.runtime = runtime;
this.providers = new SeedTable<>(SEED_CAPACITY, this::createProvider);
}
@Override
public int getArgNumber() {
return function.argumentCount();
}
@NotNull
@Override
public Statefulness statefulness() {
return Statefulness.STATEFUL;
}
@Override
public double eval(double... doubles) {
return 0;
}
@Override
public double eval(@Nullable Context raw, double... args) {
FunctionContext context = Objects.requireNonNull((FunctionContext) raw, "Expression context");
return providers.get(context.rng().getSeed()).eval(args);
}
private Provider createProvider(long seed) {
if (function.getEngineStreamValue() != null) {
Engine engine = requireEngine(runtime, "function", function.getName());
ProceduralStream<Double> stream = function.getEngineStreamValue().get(engine);
return coordinates -> stream.get(coordinates[0], coordinates[1]);
}
if (function.getStyleValue() != null) {
return function.getStyleValue().create(seed, runtime)::noise;
}
return coordinates -> Double.NaN;
}
}
@FunctionalInterface
private interface Provider {
double eval(double... args);
}
private static final class VariableRuntime {
private final IrisExpressionLoad variable;
private final PackRuntime runtime;
private final SeedTable<CNG> styles;
private volatile ProceduralStream<Double> engineStream;
private volatile Double engineValue;
private VariableRuntime(IrisExpressionLoad variable, PackRuntime runtime) {
this.variable = variable;
this.runtime = runtime;
this.styles = new SeedTable<>(SEED_CAPACITY,
seed -> variable.getStyleValue().createNoCache(new RNG(seed), runtime));
}
private double value(RNG rng, double x, double z) {
if (variable.getEngineValue() != null) {
return engineValue();
}
if (variable.getEngineStreamValue() != null) {
return engineStream().get(x, z);
}
if (variable.getStyleValue() != null) {
return styles.get(rng.getSeed()).noise(x, z);
}
return variable.getStaticValue();
}
private double value(RNG rng, double x, double y, double z) {
if (variable.getEngineValue() != null) {
return engineValue();
}
if (variable.getEngineStreamValue() != null) {
return engineStream().get(x, z);
}
if (variable.getStyleValue() != null) {
return styles.get(rng.getSeed()).noise(x, y, z);
}
return variable.getStaticValue();
}
private double engineValue() {
Double value = engineValue;
if (value == null) {
value = variable.getEngineValue().get(requireEngine(runtime, "variable", variable.getName()));
engineValue = value;
}
return value;
}
private ProceduralStream<Double> engineStream() {
ProceduralStream<Double> stream = engineStream;
if (stream == null) {
stream = variable.getEngineStreamValue().get(requireEngine(runtime, "variable", variable.getName()));
engineStream = stream;
}
return stream;
}
}
private static final class EvaluationScratch {
private final double[][] retained = new double[MAX_RETAINED_EVALUATION_DEPTH][];
private int depth;
private double[] acquire(int length) {
double[] arguments;
if (depth >= retained.length || length > MAX_RETAINED_ARGUMENTS) {
arguments = new double[length];
} else {
arguments = retained[depth];
if (arguments == null || arguments.length != length) {
arguments = new double[length];
retained[depth] = arguments;
}
}
depth++;
return arguments;
}
private void release() {
depth--;
}
}
}
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.volmlib.util.interpolation.IrisInterpolation;
import java.util.Arrays;
@@ -21,9 +22,14 @@ public final class GeneratorProgram {
private final double cliffHeightMin;
private final double cliffHeightMax;
private final boolean cellCracks;
private final PackRuntime runtime;
private final IrisGenerator.SurfaceCacheStripe[] surfaceStripes;
GeneratorProgram(IrisGenerator generator, long superSeed, NoiseLayerProgram[] layers, double totalOpacity, NoiseLayerProgram cliffs) {
GeneratorProgram(IrisGenerator generator, long superSeed, NoiseLayerProgram[] layers, double totalOpacity,
NoiseLayerProgram cliffs, PackRuntime runtime) {
this.generator = generator;
this.runtime = runtime;
this.surfaceStripes = runtime.generator(generator).surfaceStripes();
this.superSeed = superSeed;
this.layers = layers;
this.totalOpacity = totalOpacity;
@@ -69,7 +75,7 @@ public final class GeneratorProgram {
double lowerZ = Math.floor(z / SURFACE_GRID) * SURFACE_GRID;
double dx = (x - lowerX) / SURFACE_GRID;
double dz = (z - lowerZ) / SURFACE_GRID;
IrisGenerator.SurfaceCacheStripe[] stripes = generator.surfaceStripes();
IrisGenerator.SurfaceCacheStripe[] stripes = surfaceStripes;
double northWest = lattice(scratch, stripes, lowerX, lowerZ);
if (dx == 0D && dz == 0D) {
return northWest;
@@ -124,7 +130,7 @@ public final class GeneratorProgram {
double height = IrisInterpolation.lerp(cliffHeightMin, cliffHeightMax, cliffs.sample(scratch, sampleX, sampleZ));
value = (Math.round((value * 255D) / height) * height) / 255D;
}
return cellCracks ? generator.cell(x, z, value, 0D) : value;
return cellCracks ? generator.cell(runtime, x, z, value, 0D) : value;
}
private void surfaceHeights(TerrainBatchScratch scratch, double[] xs, double[] zs, int count, double[] out) {
@@ -226,7 +232,7 @@ public final class GeneratorProgram {
}
private void resolveLattice(TerrainBatchScratch scratch, int nodes, double[] lattice) {
IrisGenerator.SurfaceCacheStripe[] stripes = generator.surfaceStripes();
IrisGenerator.SurfaceCacheStripe[] stripes = surfaceStripes;
int indexMark = scratch.indexMark();
int mark = scratch.mark();
try {
@@ -308,7 +314,7 @@ public final class GeneratorProgram {
}
if (cellCracks) {
for (int index = 0; index < count; index++) {
out[index] = generator.cell(xs[index], zs[index], out[index], 0D);
out[index] = generator.cell(runtime, xs[index], zs[index], out[index], 0D);
}
}
}
@@ -0,0 +1,45 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* 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 <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.SeedTable;
import art.arcane.volmlib.util.noise.CellGenerator;
/**
* What one engine derives from an {@link IrisGenerator}: the lattice of smoothed surface heights it has sampled and
* the cell generators of its crack seeds.
*/
public final class GeneratorRuntime {
private static final int CELL_SEED_CAPACITY = 8;
private final IrisGenerator.SurfaceCacheStripe[] surfaceStripes = IrisGenerator.createSurfaceStripes();
private final SeedTable<CellGenerator> cellGenerators;
public GeneratorRuntime(IrisGenerator generator) {
this.cellGenerators = new SeedTable<>(CELL_SEED_CAPACITY, generator::buildCellGenerator);
}
IrisGenerator.SurfaceCacheStripe[] surfaceStripes() {
return surfaceStripes;
}
public CellGenerator cellGenerator(long seed) {
return cellGenerators.get(seed);
}
}
@@ -20,28 +20,22 @@ package art.arcane.iris.generation.noise;
import art.arcane.iris.spi.IrisLogging;
import com.dfsek.paralithic.Expression;
import com.dfsek.paralithic.functions.dynamic.DynamicFunction;
import com.dfsek.paralithic.eval.parser.Parser;
import com.dfsek.paralithic.eval.parser.Scope;
import art.arcane.iris.pack.loading.IrisRegistrant;
import art.arcane.volmlib.util.cache.AtomicCache;
import art.arcane.iris.generation.cache.LazyBoundedCache;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import art.arcane.iris.generation.noise.IrisExpressionFunction.FunctionContext;
import art.arcane.iris.pack.schema.annotation.ArrayType;
import art.arcane.volmlib.util.documentation.Description;
import art.arcane.iris.pack.schema.annotation.Required;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.stream.ProceduralStream;
import art.arcane.volmlib.util.stream.interpolation.Interpolated;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.util.function.Function;
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
@@ -49,9 +43,6 @@ import lombok.experimental.Accessors;
@Data
@EqualsAndHashCode(callSuper = false)
public class IrisExpression extends IrisRegistrant {
private static final int MAX_RETAINED_EVALUATION_DEPTH = 8;
private static final int MAX_RETAINED_ARGUMENTS = 256;
@ArrayType(type = IrisExpressionLoad.class, min = 1)
@Description("Variables to use in this expression")
private KList<IrisExpressionLoad> variables = new KList<>();
@@ -64,88 +55,38 @@ public class IrisExpression extends IrisRegistrant {
@Description("The expression. Inherited variables are x, y and z. Avoid using those variable names.")
private String expression;
private transient AtomicCache<Expression> expressionCache = new AtomicCache<>();
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient LazyBoundedCache<Long, ProceduralStream<Double>> streams = new LazyBoundedCache<>(8);
/**
* Parses this expression with each valid function bound to the runtime object the caller built for it.
* Returns null when the expression does not parse; the failure is reported.
*/
public Expression parse(Function<IrisExpressionFunction, DynamicFunction> functionRuntime) {
Scope scope = new Scope(); // Create variable scope. This scope can hold both constants and invocation variables.
Parser parser = new Parser();
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient ThreadLocal<EvaluationScratch> evaluationScratch = ThreadLocal.withInitial(EvaluationScratch::new);
private Expression expression() {
return expressionCache.aquire(() -> {
Scope scope = new Scope(); // Create variable scope. This scope can hold both constants and invocation variables.
Parser parser = new Parser();
try {
for (IrisExpressionLoad i : variables) {
scope.addInvocationVariable(i.getName());
}
scope.addInvocationVariable("x");
scope.addInvocationVariable("y");
scope.addInvocationVariable("z");
} catch (Throwable e) {
IrisLogging.reportError("Script variable load failed in " + getLoadFile().getPath() + ".", e);
}
for (IrisExpressionFunction f : functions) {
if (!f.isValid()) continue;
f.setData(getLoader());
parser.registerFunction(f.getName(), f);
}
try {
return parser.parse(getExpression(), scope);
} catch (Throwable e) {
IrisLogging.reportError("Script load failed in " + getLoadFile().getPath() + ".", e);
}
return null;
});
}
public ProceduralStream<Double> stream(RNG rng) {
return streams.computeIfAbsent(rng.getSeed(), seed -> {
RNG streamRng = new RNG(seed);
return ProceduralStream.of((x, z) -> evaluate(streamRng, x, z),
(x, y, z) -> evaluate(streamRng, x, y, z), Interpolated.DOUBLE);
});
}
public double evaluate(RNG rng, double x, double z) {
EvaluationScratch scratch = evaluationScratch.get();
double[] arguments = scratch.acquire(3 + getVariables().size());
try {
int index = 0;
for (IrisExpressionLoad variable : getVariables()) {
arguments[index++] = variable.getValue(rng, getLoader(), x, z);
for (IrisExpressionLoad i : variables) {
scope.addInvocationVariable(i.getName());
}
arguments[index++] = x;
arguments[index++] = z;
arguments[index] = -1;
return expression().evaluate(new FunctionContext(rng), arguments);
} finally {
scratch.release();
}
}
public double evaluate(RNG rng, double x, double y, double z) {
EvaluationScratch scratch = evaluationScratch.get();
double[] arguments = scratch.acquire(3 + getVariables().size());
try {
int index = 0;
for (IrisExpressionLoad variable : getVariables()) {
arguments[index++] = variable.getValue(rng, getLoader(), x, y, z);
}
arguments[index++] = x;
arguments[index++] = y;
arguments[index] = z;
return expression().evaluate(new FunctionContext(rng), arguments);
} finally {
scratch.release();
scope.addInvocationVariable("x");
scope.addInvocationVariable("y");
scope.addInvocationVariable("z");
} catch (Throwable e) {
IrisLogging.reportError("Script variable load failed in " + getLoadFile().getPath() + ".", e);
}
for (IrisExpressionFunction f : functions) {
if (!f.isValid()) continue;
parser.registerFunction(f.getName(), functionRuntime.apply(f));
}
try {
return parser.parse(getExpression(), scope);
} catch (Throwable e) {
IrisLogging.reportError("Script load failed in " + getLoadFile().getPath() + ".", e);
}
return null;
}
@Override
@@ -157,28 +98,4 @@ public class IrisExpression extends IrisRegistrant {
public String getTypeName() {
return "Expression";
}
private static final class EvaluationScratch {
private final double[][] retained = new double[MAX_RETAINED_EVALUATION_DEPTH][];
private int depth;
private double[] acquire(int length) {
double[] arguments;
if (depth >= retained.length || length > MAX_RETAINED_ARGUMENTS) {
arguments = new double[length];
} else {
arguments = retained[depth];
if (arguments == null || arguments.length != length) {
arguments = new double[length];
retained[depth] = arguments;
}
}
depth++;
return arguments;
}
private void release() {
depth--;
}
}
}
@@ -2,31 +2,15 @@ package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.IrisEngineStreamType;
import com.dfsek.paralithic.functions.dynamic.Context;
import com.dfsek.paralithic.functions.dynamic.DynamicFunction;
import com.dfsek.paralithic.node.Statefulness;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.volmlib.util.documentation.Description;
import art.arcane.iris.pack.schema.annotation.MinNumber;
import art.arcane.iris.pack.schema.annotation.Required;
import art.arcane.iris.pack.schema.annotation.Snippet;
import art.arcane.iris.generation.cache.LazyBoundedCache;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.volmlib.util.stream.ProceduralStream;
import java.util.Objects;
import art.arcane.volmlib.util.math.RNG;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@Snippet("expression-function")
@Accessors(chain = true)
@@ -35,7 +19,7 @@ import org.jetbrains.annotations.Nullable;
@Description("Represents a function to use in your expression. Do not set the name to x, y, or z, also don't duplicate names.")
@Data
@EqualsAndHashCode(callSuper = false)
public class IrisExpressionFunction implements DynamicFunction {
public class IrisExpressionFunction {
@Required
@Description("The function to assign this value to. Do not set the name to x, y, or z")
private String name;
@@ -50,102 +34,12 @@ public class IrisExpressionFunction implements DynamicFunction {
@Description("Number of arguments for the function")
private int args = 2;
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private transient final LazyBoundedCache<FunctionKey, Provider> providers = new LazyBoundedCache<>(8);
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private transient volatile CachedProvider recentProvider;
private transient IrisData data;
public boolean isValid() {
return styleValue != null || engineStreamValue != null;
}
@Override
public int getArgNumber() {
public int argumentCount() {
if (engineStreamValue != null) return 2;
return Math.max(args, 2);
}
@NotNull
@Override
public Statefulness statefulness() {
return Statefulness.STATEFUL;
}
@Override
public double eval(double... doubles) {
return 0;
}
@Override
public double eval(@Nullable Context raw, double... args) {
FunctionContext context = Objects.requireNonNull((FunctionContext) raw, "Expression context");
IrisData currentData = data;
Engine engine = currentData == null ? null : currentData.getEngine();
long seed = context.rng.getSeed();
CachedProvider recent = recentProvider;
if (recent != null && recent.key.matches(seed, currentData, engine)) {
return recent.provider.eval(args);
}
FunctionKey key = new FunctionKey(seed, currentData, engine);
Provider provider = providers.computeIfAbsent(key, ignored -> createProvider(key));
recentProvider = new CachedProvider(key, provider);
return provider.eval(args);
}
private Provider createProvider(FunctionKey key) {
if (engineStreamValue != null) {
if (key.engine == null) {
throw new IllegalStateException("Expression function '" + name + "' requires an active Iris engine.");
}
ProceduralStream<Double> stream = engineStreamValue.get(key.engine);
return coordinates -> stream.get(coordinates[0], coordinates[1]);
}
if (styleValue != null) {
return styleValue.create(new RNG(key.seed), key.data, key.engine)::noise;
}
return coordinates -> Double.NaN;
}
private record FunctionKey(long seed, IrisData data, Engine engine) {
private boolean matches(long seed, IrisData data, Engine engine) {
return this.seed == seed && this.data == data && this.engine == engine;
}
@Override
public boolean equals(Object object) {
return object instanceof FunctionKey other && matches(other.seed, other.data, other.engine);
}
@Override
public int hashCode() {
int hash = Long.hashCode(seed);
hash = 31 * hash + System.identityHashCode(data);
return 31 * hash + System.identityHashCode(engine);
}
}
private record CachedProvider(FunctionKey key, Provider provider) {
}
public record FunctionContext(@NonNull RNG rng) implements Context {
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
FunctionContext that = (FunctionContext) o;
return rng.getSeed() == that.rng.getSeed();
}
@Override
public int hashCode() {
return Long.hashCode(rng.getSeed());
}
}
@FunctionalInterface
private interface Provider {
double eval(double... args);
}
}
@@ -21,30 +21,15 @@ package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.IrisEngineStreamType;
import art.arcane.iris.generation.runtime.IrisEngineValueType;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.volmlib.util.cache.AtomicCache;
import art.arcane.iris.generation.cache.LazyBoundedCache;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.volmlib.util.documentation.Description;
import art.arcane.iris.pack.schema.annotation.Required;
import art.arcane.iris.pack.schema.annotation.Snippet;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG;
import art.arcane.volmlib.util.stream.ProceduralStream;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.Map;
@Snippet("expression-load")
@Accessors(chain = true)
@NoArgsConstructor
@@ -53,7 +38,6 @@ import java.util.Map;
@Data
@EqualsAndHashCode(callSuper = false)
public class IrisExpressionLoad {
private static final int STYLE_CACHE_SIZE = 8;
@Required
@Description("The variable to assign this value to. Do not set the name to x, y, or z")
private String name = "";
@@ -69,119 +53,4 @@ public class IrisExpressionLoad {
@Description("If defined, iris will use an internal value from the engine as it's value")
private IrisEngineValueType engineValue = null;
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private transient final Map<Engine, EngineCache> engineCaches =
Collections.synchronizedMap(new IdentityHashMap<>());
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private transient final LazyBoundedCache<StandaloneStyleKey, CNG> standaloneStyleCache =
new LazyBoundedCache<>(STYLE_CACHE_SIZE);
public double getValue(RNG rng, IrisData data, double x, double z) {
if (engineValue != null) {
Engine engine = requireEngine(data);
return cacheFor(engine).value.aquire(() -> engineValue.get(engine));
}
if (engineStreamValue != null) {
Engine engine = requireEngine(data);
return cacheFor(engine).stream.aquire(() -> engineStreamValue.get(engine)).get(x, z);
}
if (styleValue != null) {
return style(data, rng).noise(x, z);
}
return staticValue;
}
public double getValue(RNG rng, IrisData data, double x, double y, double z) {
if (engineValue != null) {
Engine engine = requireEngine(data);
return cacheFor(engine).value.aquire(() -> engineValue.get(engine));
}
if (engineStreamValue != null) {
Engine engine = requireEngine(data);
return cacheFor(engine).stream.aquire(() -> engineStreamValue.get(engine)).get(x, z);
}
if (styleValue != null) {
return style(data, rng).noise(x, y, z);
}
return staticValue;
}
private Engine requireEngine(IrisData data) {
Engine engine = data.getEngine();
if (engine == null) {
throw new IllegalStateException("Expression variable '" + name + "' requires an active Iris engine.");
}
return engine;
}
private EngineCache cacheFor(Engine engine) {
synchronized (engineCaches) {
Iterator<Map.Entry<Engine, EngineCache>> iterator = engineCaches.entrySet().iterator();
while (iterator.hasNext()) {
if (iterator.next().getKey().isClosed()) {
iterator.remove();
}
}
EngineCache cache = engineCaches.get(engine);
if (cache != null) {
return cache;
}
EngineCache created = new EngineCache();
engineCaches.put(engine, created);
return created;
}
}
private CNG style(IrisData data, RNG rng) {
Engine engine = data.getEngine();
long seed = rng.getSeed();
if (engine != null) {
return cacheFor(engine).styles.computeIfAbsent(seed,
ignored -> styleValue.createNoCache(new RNG(seed), data));
}
StandaloneStyleKey key = new StandaloneStyleKey(data, seed);
return standaloneStyleCache.computeIfAbsent(key,
ignored -> styleValue.createNoCache(new RNG(seed), data));
}
private static final class EngineCache {
private final AtomicCache<ProceduralStream<Double>> stream = new AtomicCache<>();
private final AtomicCache<Double> value = new AtomicCache<>();
private final LazyBoundedCache<Long, CNG> styles = new LazyBoundedCache<>(STYLE_CACHE_SIZE);
}
private static final class StandaloneStyleKey {
private final IrisData data;
private final long seed;
private StandaloneStyleKey(IrisData data, long seed) {
this.data = data;
this.seed = seed;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof StandaloneStyleKey key)) {
return false;
}
return data == key.data && seed == key.seed;
}
@Override
public int hashCode() {
return 31 * System.identityHashCode(data) + Long.hashCode(seed);
}
}
}
@@ -19,9 +19,7 @@
package art.arcane.iris.generation.noise;
import art.arcane.iris.pack.loading.IrisRegistrant;
import art.arcane.iris.generation.cache.LazyBoundedCache;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.schema.annotation.ArrayType;
import art.arcane.volmlib.util.documentation.Description;
import art.arcane.iris.pack.schema.annotation.MaxNumber;
@@ -32,13 +30,10 @@ import art.arcane.volmlib.util.interpolation.IrisInterpolation;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CellGenerator;
import java.util.concurrent.atomic.AtomicReferenceArray;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import java.util.List;
@@ -54,15 +49,6 @@ public class IrisGenerator extends IrisRegistrant {
private static final int SURFACE_CACHE_STRIPES = 16;
private static final int SURFACE_CACHE_STRIPE_SIZE = 1024;
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient LazyBoundedCache<Long, CellGenerator> cellGenerators = new LazyBoundedCache<>(8);
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private transient volatile CachedCellGenerator recentCellGenerator;
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private transient volatile SurfaceCache surfaceSamples;
@MinNumber(0.001)
@Description("The zoom or frequency.")
private double zoom = 1;
@@ -119,21 +105,13 @@ public class IrisGenerator extends IrisRegistrant {
return cliffHeightMax > 0;
}
public CellGenerator getCellGenerator(long seed) {
CachedCellGenerator recent = recentCellGenerator;
if (recent != null && recent.seed == seed) {
return recent.generator;
}
CellGenerator generator = cellGenerators.computeIfAbsent(seed, ignored -> {
CellGenerator created = new CellGenerator(new RNG(seed + 239466));
created.setShuffle(getCellFractureShuffle());
return created;
});
recentCellGenerator = new CachedCellGenerator(seed, generator);
return generator;
CellGenerator buildCellGenerator(long seed) {
CellGenerator created = new CellGenerator(new RNG(seed + 239466));
created.setShuffle(getCellFractureShuffle());
return created;
}
public <T> T fit(T[] v, long superSeed, double rx, double rz) {
public <T> T fit(PackRuntime runtime, T[] v, long superSeed, double rx, double rz) {
if (v.length == 0) {
return null;
}
@@ -142,10 +120,10 @@ public class IrisGenerator extends IrisRegistrant {
return v[0];
}
return v[fit(0, v.length - 1, superSeed, rx, rz)];
return v[fit(runtime, 0, v.length - 1, superSeed, rx, rz)];
}
public <T> T fit(List<T> v, long superSeed, double rx, double rz) {
public <T> T fit(PackRuntime runtime, List<T> v, long superSeed, double rx, double rz) {
if (v.size() == 0) {
return null;
}
@@ -154,61 +132,59 @@ public class IrisGenerator extends IrisRegistrant {
return v.get(0);
}
return v.get(fit(0, v.size() - 1, superSeed, rx, rz));
return v.get(fit(runtime, 0, v.size() - 1, superSeed, rx, rz));
}
public int fit(int min, int max, long superSeed, double rx, double rz) {
public int fit(PackRuntime runtime, int min, int max, long superSeed, double rx, double rz) {
if (min == max) {
return min;
}
double noise = getHeight(rx, rz, superSeed);
double noise = getHeight(runtime, rx, rz, superSeed);
return (int) Math.round(IrisInterpolation.lerp(min, max, noise));
}
public int fit(double min, double max, long superSeed, double rx, double rz) {
public int fit(PackRuntime runtime, double min, double max, long superSeed, double rx, double rz) {
if (min == max) {
return (int) Math.round(min);
}
double noise = getHeight(rx, rz, superSeed);
double noise = getHeight(runtime, rx, rz, superSeed);
return (int) Math.round(IrisInterpolation.lerp(min, max, noise));
}
public double fitDouble(double min, double max, long superSeed, double rx, double rz) {
public double fitDouble(PackRuntime runtime, double min, double max, long superSeed, double rx, double rz) {
if (min == max) {
return min;
}
double noise = getHeight(rx, rz, superSeed);
double noise = getHeight(runtime, rx, rz, superSeed);
return IrisInterpolation.lerp(min, max, noise);
}
public double getHeight(double rx, double rz, long superSeed) {
return getHeight(rx, 0, rz, superSeed, true);
public double getHeight(PackRuntime runtime, double rx, double rz, long superSeed) {
return getHeight(runtime, rx, 0, rz, superSeed, true);
}
public double getHeight(double rx, double ry, double rz, long superSeed) {
return getHeight(rx, ry, rz, superSeed, false);
public double getHeight(PackRuntime runtime, double rx, double ry, double rz, long superSeed) {
return getHeight(runtime, rx, ry, rz, superSeed, false);
}
public double getHeight(double rx, double ry, double rz, long superSeed, boolean no3d) {
public double getHeight(PackRuntime runtime, double rx, double ry, double rz, long superSeed, boolean no3d) {
if (!Double.isFinite(surfaceDetail) || surfaceDetail < 0D || surfaceDetail > 1D) {
throw new IllegalArgumentException("Generator surfaceDetail must be finite and between 0 and 1");
}
if (composite.isEmpty()) {
return 0D;
}
IrisData data = getLoader();
Engine engine = data == null ? null : data.getEngine();
if (surfaceDetail == 1D) {
return sampleHeight(rx, rz, superSeed, data, engine);
return sampleHeight(rx, rz, superSeed, runtime);
}
return surfaceHeight(rx, rz, superSeed, data, engine);
return surfaceHeight(rx, rz, superSeed, runtime);
}
public boolean supportsBatch() {
@@ -224,35 +200,28 @@ public class IrisGenerator extends IrisRegistrant {
return !hasCliffs() || cliffHeightGenerator.supportsBatch();
}
public GeneratorProgram compileProgram(long superSeed) {
public GeneratorProgram compileProgram(PackRuntime runtime, long superSeed) {
if (!Double.isFinite(surfaceDetail) || surfaceDetail < 0D || surfaceDetail > 1D) {
throw new IllegalArgumentException("Generator surfaceDetail must be finite and between 0 and 1");
}
if (!supportsBatch()) {
throw new IllegalStateException("Generator " + getLoadKey() + " cannot be compiled into a batch program");
}
IrisData data = getLoader();
Engine engine = data == null ? null : data.getEngine();
int hc = (int) ((cliffHeightMin * 10) + 10 + cliffHeightMax * getSeed() + offsetX + offsetZ);
NoiseLayerProgram[] layers = new NoiseLayerProgram[composite.size()];
double totalOpacity = 0D;
for (int index = 0; index < layers.length; index++) {
IrisNoiseGenerator layer = composite.get(index);
layers[index] = layer.compileProgram(getSeed() + superSeed + hc, data, engine);
layers[index] = layer.compileProgram(getSeed() + superSeed + hc, runtime);
if (!multiplicitive) {
totalOpacity += layer.getOpacity();
}
}
double cliffSeed = (double) (superSeed + 294596 + hc) - 34857;
NoiseLayerProgram cliffs = hasCliffs()
? cliffHeightGenerator.compileProgram((long) (getSeed() + cliffSeed + hc), data, engine)
? cliffHeightGenerator.compileProgram((long) (getSeed() + cliffSeed + hc), runtime)
: null;
return new GeneratorProgram(this, superSeed, layers, totalOpacity, cliffs);
}
SurfaceCacheStripe[] surfaceStripes() {
IrisData data = getLoader();
return surfaceCache(data, data == null ? null : data.getEngine()).stripes();
return new GeneratorProgram(this, superSeed, layers, totalOpacity, cliffs, runtime);
}
static boolean cachedSurface(SurfaceCacheStripe[] stripes, double x, double z, long superSeed, double[] target, int index) {
@@ -281,30 +250,30 @@ public class IrisGenerator extends IrisRegistrant {
return mixed;
}
private double surfaceHeight(double rx, double rz, long superSeed, IrisData data, Engine engine) {
SurfaceCacheStripe[] stripes = surfaceCache(data, engine).stripes();
private double surfaceHeight(double rx, double rz, long superSeed, PackRuntime runtime) {
SurfaceCacheStripe[] stripes = runtime.generator(this).surfaceStripes();
double lowerX = Math.floor(rx / SURFACE_GRID) * SURFACE_GRID;
double lowerZ = Math.floor(rz / SURFACE_GRID) * SURFACE_GRID;
double dx = (rx - lowerX) / SURFACE_GRID;
double dz = (rz - lowerZ) / SURFACE_GRID;
double northWest = cachedSurfaceHeight(lowerX, lowerZ, superSeed, stripes, data, engine);
double northWest = cachedSurfaceHeight(lowerX, lowerZ, superSeed, stripes, runtime);
if (dx == 0D && dz == 0D) {
return northWest;
}
double north = dx == 0D ? northWest : IrisInterpolation.lerp(northWest,
cachedSurfaceHeight(lowerX + SURFACE_GRID, lowerZ, superSeed, stripes, data, engine), dx);
cachedSurfaceHeight(lowerX + SURFACE_GRID, lowerZ, superSeed, stripes, runtime), dx);
double smooth = north;
if (dz != 0D) {
double southWest = cachedSurfaceHeight(lowerX, lowerZ + SURFACE_GRID, superSeed, stripes, data, engine);
double southWest = cachedSurfaceHeight(lowerX, lowerZ + SURFACE_GRID, superSeed, stripes, runtime);
double south = dx == 0D ? southWest : IrisInterpolation.lerp(southWest,
cachedSurfaceHeight(lowerX + SURFACE_GRID, lowerZ + SURFACE_GRID, superSeed, stripes, data, engine), dx);
cachedSurfaceHeight(lowerX + SURFACE_GRID, lowerZ + SURFACE_GRID, superSeed, stripes, runtime), dx);
smooth = IrisInterpolation.lerp(north, south, dz);
}
return surfaceDetail == 0D ? smooth
: smooth + (sampleHeight(rx, rz, superSeed, data, engine) - smooth) * surfaceDetail;
: smooth + (sampleHeight(rx, rz, superSeed, runtime) - smooth) * surfaceDetail;
}
private double sampleHeight(double rx, double rz, long superSeed, IrisData data, Engine engine) {
private double sampleHeight(double rx, double rz, long superSeed, PackRuntime runtime) {
int hc = (int) ((cliffHeightMin * 10) + 10 + cliffHeightMax * getSeed() + offsetX + offsetZ);
double h = multiplicitive ? 1 : 0;
double tp = 0;
@@ -313,18 +282,18 @@ public class IrisGenerator extends IrisRegistrant {
if (composite.size() == 1) {
if (multiplicitive) {
h *= composite.get(0).getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, data, engine);
h *= composite.get(0).getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, runtime);
} else {
tp += composite.get(0).getOpacity();
h += composite.get(0).getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, data, engine);
h += composite.get(0).getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, runtime);
}
} else {
for (IrisNoiseGenerator i : composite) {
if (multiplicitive) {
h *= i.getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, data, engine);
h *= i.getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, runtime);
} else {
tp += i.getOpacity();
h += i.getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, data, engine);
h += i.getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, runtime);
}
}
}
@@ -335,15 +304,15 @@ public class IrisGenerator extends IrisRegistrant {
v = 0;
}
v = hasCliffs() ? cliff(rx, rz, v, superSeed + 294596 + hc, data, engine) : v;
v = hasCellCracks() ? cell(rx, rz, v, superSeed + 48622 + hc) : v;
v = hasCliffs() ? cliff(runtime, rx, rz, v, superSeed + 294596 + hc) : v;
v = hasCellCracks() ? cell(runtime, rx, rz, v, superSeed + 48622 + hc) : v;
return v;
}
private double cachedSurfaceHeight(double x, double z, long superSeed, SurfaceCacheStripe[] stripes, IrisData data, Engine engine) {
private double cachedSurfaceHeight(double x, double z, long superSeed, SurfaceCacheStripe[] stripes, PackRuntime runtime) {
if (x != (int) x || z != (int) z) {
return sampleHeight(x, z, superSeed, data, engine);
return sampleHeight(x, z, superSeed, runtime);
}
long key = ((long) (int) x << 32) | ((int) z & 0xffffffffL);
long mixed = surfaceMix(key);
@@ -353,27 +322,12 @@ public class IrisGenerator extends IrisRegistrant {
if (cached != null) {
return cached.height();
}
double height = sampleHeight(x, z, superSeed, data, engine);
double height = sampleHeight(x, z, superSeed, runtime);
stripe.put(slot, new SurfaceSample(key, superSeed, height));
return height;
}
private SurfaceCache surfaceCache(IrisData data, Engine engine) {
SurfaceCache cached = surfaceSamples;
if (cached != null && cached.data() == data && cached.engine() == engine) {
return cached;
}
synchronized (this) {
cached = surfaceSamples;
if (cached == null || cached.data() != data || cached.engine() != engine) {
cached = new SurfaceCache(data, engine, createSurfaceCache());
surfaceSamples = cached;
}
return cached;
}
}
private static SurfaceCacheStripe[] createSurfaceCache() {
static SurfaceCacheStripe[] createSurfaceStripes() {
SurfaceCacheStripe[] stripes = new SurfaceCacheStripe[SURFACE_CACHE_STRIPES];
for (int i = 0; i < stripes.length; i++) {
stripes[i] = new SurfaceCacheStripe();
@@ -381,45 +335,29 @@ public class IrisGenerator extends IrisRegistrant {
return stripes;
}
public double cell(double rx, double rz, double v, double superSeed) {
public double cell(PackRuntime runtime, double rx, double rz, double v, double superSeed) {
double fractureX = rx / getCellFractureZoom();
double fractureZ = rz / getCellFractureZoom();
return getCellGenerator(getSeed() + 46222).getDistance(fractureX, fractureZ) > getCellPercentSize() ? (v * getCellFractureHeight()) : v;
return runtime.generator(this).cellGenerator(getSeed() + 46222).getDistance(fractureX, fractureZ) > getCellPercentSize() ? (v * getCellFractureHeight()) : v;
}
private boolean hasCellCracks() {
return getCellFractureHeight() != 0;
}
public double getCliffHeight(double rx, double rz, double superSeed) {
IrisData data = getLoader();
return getCliffHeight(rx, rz, superSeed, data, data == null ? null : data.getEngine());
}
private double getCliffHeight(double rx, double rz, double superSeed, IrisData data, Engine engine) {
public double getCliffHeight(PackRuntime runtime, double rx, double rz, double superSeed) {
int hc = (int) ((cliffHeightMin * 10) + 10 + cliffHeightMax * getSeed() + offsetX + offsetZ);
double sampleX = (rx + offsetX) / zoom;
double sampleZ = (rz + offsetZ) / zoom;
double h = cliffHeightGenerator.getNoise((long) (getSeed() + superSeed + hc), sampleX, sampleZ, data, engine);
double h = cliffHeightGenerator.getNoise((long) (getSeed() + superSeed + hc), sampleX, sampleZ, runtime);
return IrisInterpolation.lerp(cliffHeightMin, cliffHeightMax, h);
}
public double cliff(double rx, double rz, double v, double superSeed) {
IrisData data = getLoader();
return cliff(rx, rz, v, superSeed, data, data == null ? null : data.getEngine());
}
private double cliff(double rx, double rz, double v, double superSeed, IrisData data, Engine engine) {
double cliffHeight = getCliffHeight(rx, rz, superSeed - 34857, data, engine);
public double cliff(PackRuntime runtime, double rx, double rz, double v, double superSeed) {
double cliffHeight = getCliffHeight(runtime, rx, rz, superSeed - 34857);
return (Math.round((v * 255D) / cliffHeight) * cliffHeight) / 255D;
}
public IrisGenerator rescale(double scale) {
zoom /= scale;
surfaceSamples = null;
return this;
}
public KList<IrisNoiseGenerator> getAllComposites() {
KList<IrisNoiseGenerator> g = new KList<>();
@@ -440,9 +378,6 @@ public class IrisGenerator extends IrisRegistrant {
return "Generator";
}
private record SurfaceCache(IrisData data, Engine engine, SurfaceCacheStripe[] stripes) {
}
private record SurfaceSample(long key, long seed, double height) {
}
@@ -458,7 +393,4 @@ public class IrisGenerator extends IrisRegistrant {
entries.set(slot, sample);
}
}
private record CachedCellGenerator(long seed, CellGenerator generator) {
}
}
@@ -20,10 +20,9 @@ package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.image.IrisImageMap;
import art.arcane.iris.generation.runtime.EngineRef;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.cache.LazyBoundedCache;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.world.history.GenerationKernelRegistry;
import art.arcane.volmlib.util.documentation.Description;
import art.arcane.iris.pack.schema.annotation.MaxNumber;
@@ -53,15 +52,7 @@ import java.util.concurrent.ConcurrentHashMap;
@Description("A gen style")
@Data
public class IrisGeneratorStyle {
private static final int GENERATOR_CACHE_SIZE = 8;
private static final ConcurrentHashMap<String, String> ACTIVE_CACHE_KEYS = new ConcurrentHashMap<>();
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient LazyBoundedCache<GeneratorCacheKey, CNG> generatorCache =
new LazyBoundedCache<>(GENERATOR_CACHE_SIZE);
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private transient volatile CachedGenerator recentGenerator;
@Description("The base noise style. Used when neither expression nor imageMap is set; a failed expression also falls back to this style, except one that names an unknown engine stream, which fails the pack load.")
private NoiseStyle style = NoiseStyle.FLAT;
@@ -102,24 +93,20 @@ public class IrisGeneratorStyle {
return this;
}
public CNG createNoCache(RNG rng, IrisData data) {
return createNoCache(rng, data, 1, 0, false, resolveEngine(data));
public CNG createNoCache(RNG rng, PackRuntime runtime) {
return createNoCache(rng, runtime, 1, 0, false);
}
public CNG createScaledGenerator(RNG rng, IrisData data, double scaleFactor) {
return createNoCache(rng, data).bake().scale(scaleFactor).bake();
public CNG createScaledGenerator(RNG rng, PackRuntime runtime, double scaleFactor) {
return createNoCache(rng, runtime).bake().scale(scaleFactor).bake();
}
public CNG createForLayer(RNG rng, IrisData data, int octaveMultiplier) {
return createForLayer(rng, data, octaveMultiplier, resolveEngine(data));
public CNG createForLayer(RNG rng, PackRuntime runtime, int octaveMultiplier) {
return createNoCache(rng, runtime, Math.clamp(octaveMultiplier, 1, 16), 0, false);
}
CNG createForLayer(RNG rng, IrisData data, int octaveMultiplier, Engine engine) {
return createNoCache(rng, data, Math.clamp(octaveMultiplier, 1, 16), 0, false, engine);
}
public CNG createForPrebake(RNG rng, IrisData data, int fallbackCacheSize) {
return createNoCache(rng, data, 1, Math.max(0, fallbackCacheSize), true, resolveEngine(data));
public CNG createForPrebake(RNG rng, PackRuntime runtime, int fallbackCacheSize) {
return createNoCache(rng, runtime, 1, Math.max(0, fallbackCacheSize), true);
}
@@ -176,8 +163,10 @@ public class IrisGeneratorStyle {
}
}
private CNG createNoCache(RNG rng, IrisData data, int octaveMultiplier, int fallbackCacheSize,
boolean quietCacheLog, Engine engine) {
private CNG createNoCache(RNG rng, PackRuntime runtime, int octaveMultiplier, int fallbackCacheSize,
boolean quietCacheLog) {
IrisData data = runtime.data();
Engine engine = runtime.engine();
requirePositiveFinite("zoom", zoom);
requirePositiveFinite("exponent", exponent);
if (!Double.isFinite(cellularFrequency) || cellularFrequency < 0D) {
@@ -194,7 +183,7 @@ public class IrisGeneratorStyle {
if (getExpression() != null) {
IrisExpression e = data.getExpressionLoader().load(getExpression());
if (e != null) {
cng = new CNG(rng, new ExpressionNoise(rng, e), 1D, 1).bake();
cng = new CNG(rng, new ExpressionNoise(rng, runtime.expression(e)), 1D, 1).bake();
sourceStamp = Integer.toUnsignedLong(Objects.hash(getExpression(),
e.getLoadFile() == null ? 0L : e.getLoadFile().lastModified()));
}
@@ -212,8 +201,8 @@ public class IrisGeneratorStyle {
.pow(cng.getPower() * exponent);
if (fracture != null) {
cng.fractureWith(fracture.createNoCache(rng.nextParallelRNG(2934), data, 1,
fallbackCacheSize, quietCacheLog, engine), fracture.getMultiplier());
cng.fractureWith(fracture.createNoCache(rng.nextParallelRNG(2934), runtime, 1,
fallbackCacheSize, quietCacheLog), fracture.getMultiplier());
}
if (cellularFrequency > 0) {
@@ -233,32 +222,17 @@ public class IrisGeneratorStyle {
return cng;
}
public double warp(RNG rng, IrisData data, double value, double... coords) {
return create(rng, data).noise(coords) + value;
public double warp(RNG rng, PackRuntime runtime, double value, double... coords) {
return create(rng, runtime).noise(coords) + value;
}
public CNG create(RNG rng, IrisData data) {
return create(rng, data, resolveEngine(data));
/** The generator this runtime shares for this style and seed. */
public CNG create(RNG rng, PackRuntime runtime) {
return create(rng.getSeed(), runtime);
}
public CNG create(long seed, IrisData data) {
return cachedGenerator(seed, data, resolveEngine(data));
}
public CNG create(RNG rng, IrisData data, Engine engine) {
return cachedGenerator(rng.getSeed(), data, engine);
}
private CNG cachedGenerator(long seed, IrisData data, Engine engine) {
CachedGenerator recent = recentGenerator;
if (recent != null && recent.key.matches(data, engine, seed)) {
return recent.generator;
}
GeneratorCacheKey key = new GeneratorCacheKey(data, engine, seed);
CNG generator = generatorCache.computeIfAbsent(key,
ignored -> createNoCache(new RNG(seed), data, 1, 0, false, engine));
recentGenerator = new CachedGenerator(key, generator);
return generator;
public CNG create(long seed, PackRuntime runtime) {
return runtime.styleGenerator(this, seed);
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
@@ -283,10 +257,6 @@ public class IrisGeneratorStyle {
));
}
private Engine resolveEngine(IrisData data) {
return data == null ? null : data.getEngine();
}
private static void requirePositiveFinite(String field, double value) {
if (!Double.isFinite(value) || value <= 0D || !Double.isFinite(1D / value)) {
throw new IllegalArgumentException(field + " must be finite and positive");
@@ -305,41 +275,4 @@ public class IrisGeneratorStyle {
}
}
}
private static final class GeneratorCacheKey {
private final IrisData data;
private final EngineRef engine;
private final long seed;
private GeneratorCacheKey(IrisData data, Engine engine, long seed) {
this.data = data;
this.engine = EngineRef.of(engine);
this.seed = seed;
}
private boolean matches(IrisData data, Engine engine, long seed) {
return this.data == data && this.engine.refersTo(engine) && this.seed == seed;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof GeneratorCacheKey key)) {
return false;
}
return data == key.data && engine.equals(key.engine) && seed == key.seed;
}
@Override
public int hashCode() {
int result = System.identityHashCode(data);
result = 31 * result + engine.hashCode();
return 31 * result + Long.hashCode(seed);
}
}
private record CachedGenerator(GeneratorCacheKey key, CNG generator) {
}
}
@@ -18,10 +18,7 @@
package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.EngineRef;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.cache.LazyBoundedCache;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.schema.annotation.ArrayType;
import art.arcane.volmlib.util.documentation.Description;
import art.arcane.iris.pack.schema.annotation.MaxNumber;
@@ -41,16 +38,12 @@ import art.arcane.volmlib.util.noise.OffsetNoiseGenerator;
import art.arcane.volmlib.util.noise.PerlinNoise;
import art.arcane.volmlib.util.noise.SimplexNoise;
import art.arcane.volmlib.util.noise.program.NoiseProgram;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
@Snippet("generator")
@Accessors(chain = true)
@@ -59,7 +52,6 @@ import java.util.concurrent.atomic.AtomicReference;
@Description("A noise generator")
@Data
public class IrisNoiseGenerator {
private static final int GENERATOR_CACHE_SIZE = 32;
private static final long GENERATOR_SEED_SALT = 33_955_677L;
private static final int MINIMUM_FRACTURE_DEPTH = 4;
private static final int MAXIMUM_FRACTURE_NODES = 32;
@@ -68,13 +60,6 @@ public class IrisNoiseGenerator {
static final int Z_AXIS = 1;
private static final ThreadLocal<FractureSamples> FRACTURE_SAMPLES = ThreadLocal.withInitial(FractureSamples::new);
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient LazyBoundedCache<GeneratorKey, CNG> generators =
new LazyBoundedCache<>(GENERATOR_CACHE_SIZE);
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient AtomicReference<CachedGenerator> recentGenerator = new AtomicReference<>();
@MinNumber(0.0001)
@Description("The coordinate input zoom")
private double zoom = 1;
@@ -119,43 +104,28 @@ public class IrisNoiseGenerator {
this.enabled = enabled;
}
CNG getGenerator(long superSeed, IrisData data, Engine engine) {
long generatorSeed = superSeed + GENERATOR_SEED_SALT - seed;
CachedGenerator recent = recentGenerator.get();
if (recent != null && recent.key.matches(data, engine, generatorSeed)) {
return recent.generator;
}
CNG getGenerator(long superSeed, PackRuntime runtime) {
return runtime.noiseLayerGenerator(this, superSeed + GENERATOR_SEED_SALT - seed);
}
GeneratorKey key = new GeneratorKey(data, engine, generatorSeed);
CNG generator = generators.computeIfAbsent(key,
ignored -> style.createForLayer(new RNG(generatorSeed), data, octaves, engine));
if (generator != null) {
recentGenerator.set(new CachedGenerator(key, generator));
}
return generator;
/** Builds this layer's generator for one derived seed; {@link PackRuntime} shares the result. */
public CNG buildGenerator(long generatorSeed, PackRuntime runtime) {
return style.createForLayer(new RNG(generatorSeed), runtime, octaves);
}
public double getMax() {
return getOffsetY() + opacity;
}
public double getNoise(long superSeed, double xv, double zv, IrisData data) {
if (!enabled) {
return offsetY;
}
return getNoise(superSeed, xv, zv, data, data == null ? null : data.getEngine());
}
double getNoise(long superSeed, double xv, double zv, IrisData data, Engine engine) {
return getNoiseForAxis(superSeed, xv, zv, data, engine, X_AXIS);
public double getNoise(long superSeed, double xv, double zv, PackRuntime runtime) {
return getNoiseForAxis(superSeed, xv, zv, runtime, X_AXIS);
}
/**
* This layer read as the fracture of one axis. Each axis samples this layer's generator reseeded for that axis at
* the same coordinates, so the x and z warps are uncorrelated instead of mirror images of each other.
*/
private double getNoiseForAxis(long superSeed, double xv, double zv, IrisData data, Engine engine, int axis) {
private double getNoiseForAxis(long superSeed, double xv, double zv, PackRuntime runtime, int axis) {
if (!enabled) {
return offsetY;
}
@@ -165,7 +135,7 @@ public class IrisNoiseGenerator {
if (!samples.active) {
samples.active = true;
try {
if (samples.prepare(this, superSeed, data, engine)) {
if (samples.prepare(this, superSeed, runtime)) {
return samples.sample(xv, zv, axis);
}
} finally {
@@ -181,13 +151,13 @@ public class IrisNoiseGenerator {
for (IrisNoiseGenerator i : fracture) {
if (i.isEnabled()) {
double fractureOffset = i.getOpacity() / 2D;
x += i.getNoiseForAxis(superSeed + seed + g, xv, zv, data, engine, X_AXIS) - fractureOffset;
z += i.getNoiseForAxis(superSeed + seed + g, xv, zv, data, engine, Z_AXIS) - fractureOffset;
x += i.getNoiseForAxis(superSeed + seed + g, xv, zv, runtime, X_AXIS) - fractureOffset;
z += i.getNoiseForAxis(superSeed + seed + g, xv, zv, runtime, Z_AXIS) - fractureOffset;
}
g += 819;
}
return sample(getGenerator(superSeed, data, engine).reseededForAxis(axis), x, z);
return sample(getGenerator(superSeed, runtime).reseededForAxis(axis), x, z);
}
boolean supportsBatch() {
@@ -211,11 +181,11 @@ public class IrisNoiseGenerator {
return true;
}
NoiseLayerProgram compileProgram(long superSeed, IrisData data, Engine engine) {
return compileProgram(superSeed, data, engine, false);
NoiseLayerProgram compileProgram(long superSeed, PackRuntime runtime) {
return compileProgram(superSeed, runtime, false);
}
private NoiseLayerProgram compileProgram(long superSeed, IrisData data, Engine engine, boolean readAsFracture) {
private NoiseLayerProgram compileProgram(long superSeed, PackRuntime runtime, boolean readAsFracture) {
if (!enabled) {
return NoiseLayerProgram.disabled(this);
}
@@ -231,12 +201,12 @@ public class IrisNoiseGenerator {
int compiled = 0;
for (IrisNoiseGenerator child : fracture) {
if (child.isEnabled()) {
children[compiled] = child.compileProgram(superSeed + seed + salt, data, engine, true);
children[compiled] = child.compileProgram(superSeed + seed + salt, runtime, true);
offsets[compiled++] = child.getOpacity() / 2D;
}
salt += 819;
}
CNG generator = Objects.requireNonNull(getGenerator(superSeed, data, engine), "Noise layer generator");
CNG generator = Objects.requireNonNull(getGenerator(superSeed, runtime), "Noise layer generator");
NoiseProgram zAxisProgram = readAsFracture ? NoiseProgram.compile2D(generator.reseededForAxis(Z_AXIS)) : null;
return NoiseLayerProgram.of(this, NoiseProgram.compile2D(generator), zAxisProgram, children, offsets);
}
@@ -312,54 +282,19 @@ public class IrisNoiseGenerator {
return false;
}
private static final class GeneratorKey {
private final IrisData data;
private final EngineRef engine;
private final long seed;
private GeneratorKey(IrisData data, Engine engine, long seed) {
this.data = data;
this.engine = EngineRef.of(engine);
this.seed = seed;
}
private boolean matches(IrisData data, Engine engine, long seed) {
return this.data == data && this.engine.refersTo(engine) && this.seed == seed;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (!(object instanceof GeneratorKey other)) {
return false;
}
return data == other.data && engine.equals(other.engine) && seed == other.seed;
}
@Override
public int hashCode() {
int result = System.identityHashCode(data);
result = 31 * result + engine.hashCode();
result = 31 * result + Long.hashCode(seed);
return result;
}
}
private static final class FractureSamples {
private final IrisNoiseGenerator[] nodes = new IrisNoiseGenerator[MAXIMUM_FRACTURE_NODES];
private final CNG[] generators = new CNG[MAXIMUM_FRACTURE_NODES];
private int size;
private boolean active;
private boolean prepare(IrisNoiseGenerator node, long superSeed, IrisData data, Engine engine) {
private boolean prepare(IrisNoiseGenerator node, long superSeed, PackRuntime runtime) {
while (size < MAXIMUM_FRACTURE_NODES) {
if (node.getClass() != IrisNoiseGenerator.class || !node.enabled || !node.hasPureStyle()
|| node.fracture.size() > 1) {
return false;
}
CNG generator = node.getGenerator(superSeed, data, engine);
CNG generator = node.getGenerator(superSeed, runtime);
if (!isPureGenerator(generator)) {
return false;
}
@@ -405,14 +340,4 @@ public class IrisNoiseGenerator {
active = false;
}
}
private static final class CachedGenerator {
private final GeneratorKey key;
private final CNG generator;
private CachedGenerator(GeneratorKey key, CNG generator) {
this.key = key;
this.generator = generator;
}
}
}
@@ -18,7 +18,7 @@
package art.arcane.iris.generation.noise;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.volmlib.util.documentation.Description;
import art.arcane.iris.pack.schema.annotation.MaxNumber;
import art.arcane.iris.pack.schema.annotation.MinNumber;
@@ -63,16 +63,16 @@ public class IrisShapedGeneratorStyle {
this.generator = new IrisGeneratorStyle(style);
}
public double get(RNG rng, IrisData data, double... dim) {
return generator.create(rng, data).fitDouble(min, max, dim);
public double get(RNG rng, PackRuntime runtime, double... dim) {
return generator.create(rng, runtime).fitDouble(min, max, dim);
}
public double get(RNG rng, IrisData data, double x, double z) {
return generator.create(rng, data).fitDouble(min, max, x, z);
public double get(RNG rng, PackRuntime runtime, double x, double z) {
return generator.create(rng, runtime).fitDouble(min, max, x, z);
}
public double get(RNG rng, IrisData data, double x, double y, double z) {
return generator.create(rng, data).fitDouble(min, max, x, y, z);
public double get(RNG rng, PackRuntime runtime, double x, double y, double z) {
return generator.create(rng, runtime).fitDouble(min, max, x, y, z);
}
public boolean isFlat() {
@@ -18,7 +18,7 @@
package art.arcane.iris.generation.noise;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.volmlib.util.documentation.Description;
import art.arcane.iris.pack.schema.annotation.Snippet;
import art.arcane.volmlib.util.math.M;
@@ -46,7 +46,7 @@ public class IrisStyledRange {
@Description("The style to pick the range")
private IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.STATIC);
public double get(RNG rng, double x, double z, IrisData data) {
public double get(RNG rng, double x, double z, PackRuntime runtime) {
if (min == max) {
return min;
}
@@ -55,11 +55,11 @@ public class IrisStyledRange {
return M.lerp(min, max, 0.5);
}
return style.create(rng, data).fitDouble(min, max, x, z);
return style.create(rng, runtime).fitDouble(min, max, x, z);
}
public ProceduralStream<Double> stream(RNG rng, IrisData data) {
return ProceduralStream.of((x, z) -> get(rng, x, z, data), Interpolated.DOUBLE);
public ProceduralStream<Double> stream(RNG rng, PackRuntime runtime) {
return ProceduralStream.of((x, z) -> get(rng, x, z, runtime), Interpolated.DOUBLE);
}
public boolean isFlat() {
@@ -133,7 +133,7 @@ public final class DimensionStackContext {
upper.getDimension().getLoadKey()
);
RNG seamRng = new RNG(engine.getSeedManager().getTerrain() ^ salt);
CNG seamNoise = style.create(seamRng, engine.getData(), engine);
CNG seamNoise = style.create(seamRng, PackRuntime.of(engine, engine.getData()));
int amplitude = blend.getAmplitude();
samplers.add((x, z) -> clampSeamOffset(
seamNoise.fitDouble(-amplitude, amplitude, x, z), amplitude));
@@ -154,6 +154,7 @@ public final class DimensionTerrainContext implements DataProvider {
resolvedData = engine.getData();
}
IrisData dimensionData = resolvedData;
PackRuntime dimensionRuntime = PackRuntime.of(engine, dimensionData);
IrisImageMapRuntime imageMapRuntime = IrisImageMapRuntime.compile(
dimensionData,
dimension,
@@ -219,7 +220,7 @@ public final class DimensionTerrainContext implements DataProvider {
}
ProceduralStream<Double> regionStyleStream = dimension.getRegionStyle()
.create(rng.nextParallelRNG(883), dimensionData).stream()
.create(rng.nextParallelRNG(883), dimensionRuntime).stream()
.zoom(dimension.getRegionZoom());
KList<IrisRegion> regionPool = new KList<>();
for (IrisRegion region : dimensionData.getRegionLoader().loadAll(dimension.getRegions())) {
@@ -238,7 +239,7 @@ public final class DimensionTerrainContext implements DataProvider {
.convertAware2D((region, x, z) -> mappedRegion(imageMapRuntime, region, x, z)), cachePrefix + "ImageMappedRegionStream", engine, cacheSize)
: proceduralRegionStream;
Map<IrisRegion, Map<InferredType, ProceduralStream<IrisBiome>>> preparedBiomeStreams =
compileInferredBiomeStreams(dimension, dimensionData, rng, preparedRegions);
compileInferredBiomeStreams(dimension, dimensionRuntime, rng, preparedRegions);
ProceduralStream<IrisBiome> landBiomeStream = regionStream
.convert(region -> IrisComplex.preparedInferredBiomeStream(
@@ -259,7 +260,7 @@ public final class DimensionTerrainContext implements DataProvider {
inferredStreams.put(InferredType.SHORE, shoreBiomeStream);
ProceduralStream<InferredType> bridgeStream = focusBiome == null
? ContinentGenerator.create(dimension, rng, dimensionData).stream()
? ContinentGenerator.create(dimension, rng, dimensionRuntime).stream()
.convert(value -> value >= dimension.getLandChance()
? InferredType.SEA
: InferredType.LAND)
@@ -277,7 +278,7 @@ public final class DimensionTerrainContext implements DataProvider {
: inferredStreams.get(InferredType.LAND).get(x, z);
})
.convertAware2D((biome, x, z) -> implode(
biome, x, z, rng, dataProvider, childSelectionPlans, 3))
biome, x, z, rng, dimensionRuntime, dataProvider, childSelectionPlans, 3))
: ProceduralStream.of(
(x, z) -> focusBiome,
Interpolated.of(value -> 0D, value -> focusBiome)
@@ -293,7 +294,7 @@ public final class DimensionTerrainContext implements DataProvider {
: ProceduralStream.ofDouble((x, z) -> {
double value = 0D;
for (IrisShapedGeneratorStyle style : overlayNoise) {
value += style.get(rng, dimensionData, x, z);
value += style.get(rng, dimensionRuntime, x, z);
}
return value;
});
@@ -340,6 +341,7 @@ public final class DimensionTerrainContext implements DataProvider {
}
});
interpolatedHeight += IrisComplex.averageGeneratorHeights(
dimensionRuntime,
groupGenerators,
sampledBounds.min(),
sampledBounds.max(),
@@ -377,7 +379,7 @@ public final class DimensionTerrainContext implements DataProvider {
);
return resolvedBiome == baseBiome
? baseBiome
: implode(resolvedBiome, x, z, rng, dataProvider, childSelectionPlans, 3);
: implode(resolvedBiome, x, z, rng, dimensionRuntime, dataProvider, childSelectionPlans, 3);
}), cachePrefix + "ImageMappedFinalBiomeStream", engine, cacheSize)
: GenerationStreams.cache2D(ProceduralStream.of(
(x, z) -> focusBiome,
@@ -394,19 +396,19 @@ public final class DimensionTerrainContext implements DataProvider {
Terrain3DRuntime terrain3D = !terrain3DEnabled ? null : new Terrain3DRuntime(
new Terrain3DRuntime.Sources(heightStream::getDouble, finalBiomeStream::get),
new Terrain3DRuntime.Options(engine.getSeedManager().getTerrain() ^ seedOffset,
localHeight, fluidHeight, dimensionData, true, Math.max(4096, cacheSize))
localHeight, fluidHeight, dimensionRuntime, true, Math.max(4096, cacheSize))
);
ProceduralStream<Double> shapedHeightStream = terrain3D == null ? heightStream
: GenerationStreams.cache2DDouble(ProceduralStream.ofDouble((x, z) -> shapedHeight(terrain3D, x, z)), cachePrefix + "Terrain3DHeightStream", engine, cacheSize);
ProceduralStream<Double> slopeStream = GenerationStreams.cache2DDouble(shapedHeightStream.slope(3), cachePrefix + "SlopeStream", engine, cacheSize);
ProceduralStream<NativeBlockState> rockStream = dimension.getRockPalette()
.getLayerGenerator(rng.nextParallelRNG(45), dimensionData).stream()
.getLayerGenerator(rng.nextParallelRNG(45), dimensionRuntime).stream()
.select(dimension.getRockPalette().getBlockData(dimensionData));
FluidBlockSampler fluidBlockSampler;
if (includeFluid) {
ProceduralStream<NativeBlockState> fluidStream = dimension.getFluidPalette()
.getLayerGenerator(rng.nextParallelRNG(78), dimensionData).stream()
.getLayerGenerator(rng.nextParallelRNG(78), dimensionRuntime).stream()
.select(dimension.getFluidPalette().getBlockData(dimensionData));
fluidBlockSampler = fluidStream::get;
} else {
@@ -505,7 +507,7 @@ public final class DimensionTerrainContext implements DataProvider {
private static Map<IrisRegion, Map<InferredType, ProceduralStream<IrisBiome>>> compileInferredBiomeStreams(
IrisDimension dimension,
IrisData data,
PackRuntime runtime,
RNG rng,
Iterable<IrisRegion> regions
) {
@@ -517,11 +519,11 @@ public final class DimensionTerrainContext implements DataProvider {
}
EnumMap<InferredType, ProceduralStream<IrisBiome>> streams = new EnumMap<>(InferredType.class);
streams.put(InferredType.LAND, createInferredBiomeStream(
dimension, data, rng, region, InferredType.LAND));
dimension, runtime, rng, region, InferredType.LAND));
streams.put(InferredType.SEA, createInferredBiomeStream(
dimension, data, rng, region, InferredType.SEA));
dimension, runtime, rng, region, InferredType.SEA));
streams.put(InferredType.SHORE, createInferredBiomeStream(
dimension, data, rng, region, InferredType.SHORE));
dimension, runtime, rng, region, InferredType.SHORE));
compiled.put(region, Collections.unmodifiableMap(streams));
}
return Collections.unmodifiableMap(compiled);
@@ -529,29 +531,29 @@ public final class DimensionTerrainContext implements DataProvider {
private static ProceduralStream<IrisBiome> createInferredBiomeStream(
IrisDimension dimension,
IrisData data,
PackRuntime runtime,
RNG rng,
IrisRegion region,
InferredType type
) {
return switch (type) {
case LAND -> dimension.getLandBiomeStyle()
.create(rng.nextParallelRNG(InferredType.LAND.ordinal()), data).stream()
.create(rng.nextParallelRNG(InferredType.LAND.ordinal()), runtime).stream()
.zoom(dimension.getBiomeZoom())
.zoom(dimension.getLandZoom())
.zoom(region.getLandBiomeZoom())
.selectRarity(loadInferredBiomes(data, region.getLandBiomes(), InferredType.LAND));
.selectRarity(loadInferredBiomes(runtime.data(), region.getLandBiomes(), InferredType.LAND));
case SEA -> dimension.getSeaBiomeStyle()
.create(rng.nextParallelRNG(InferredType.SEA.ordinal()), data).stream()
.create(rng.nextParallelRNG(InferredType.SEA.ordinal()), runtime).stream()
.zoom(dimension.getBiomeZoom())
.zoom(dimension.getSeaZoom())
.zoom(region.getSeaBiomeZoom())
.selectRarity(loadInferredBiomes(data, region.getSeaBiomes(), InferredType.SEA));
.selectRarity(loadInferredBiomes(runtime.data(), region.getSeaBiomes(), InferredType.SEA));
case SHORE -> dimension.getShoreBiomeStyle()
.create(rng.nextParallelRNG(InferredType.SHORE.ordinal()), data).stream()
.create(rng.nextParallelRNG(InferredType.SHORE.ordinal()), runtime).stream()
.zoom(dimension.getBiomeZoom())
.zoom(region.getShoreBiomeZoom())
.selectRarity(loadInferredBiomes(data, region.getShoreBiomes(), InferredType.SHORE));
.selectRarity(loadInferredBiomes(runtime.data(), region.getShoreBiomes(), InferredType.SHORE));
default -> throw new IllegalArgumentException("Unsupported stacked terrain biome type: " + type);
};
}
@@ -594,6 +596,7 @@ public final class DimensionTerrainContext implements DataProvider {
double x,
double z,
RNG rng,
PackRuntime runtime,
DataProvider dataProvider,
Map<IrisBiome, IrisComplex.ChildSelectionPlan> childSelectionPlans,
int remainingDepth
@@ -621,7 +624,7 @@ public final class DimensionTerrainContext implements DataProvider {
}
IrisBiome selected = selectionPlan.select(
biome.getChildrenGenerator(rng, 123, biome.getChildShrinkFactor()), x, z);
biome.getChildrenGenerator(runtime, rng, 123, biome.getChildShrinkFactor()), x, z);
if (selected == null) {
return biome;
}
@@ -630,6 +633,7 @@ public final class DimensionTerrainContext implements DataProvider {
x,
z,
rng,
runtime,
dataProvider,
childSelectionPlans,
remainingDepth - 1
@@ -85,6 +85,9 @@ import java.util.stream.Collectors;
public interface Engine extends DataProvider, Fallible, BlockUpdater, Renderer, Hotloadable {
IrisComplex getComplex();
/** The runtime objects this engine derived from its pack, or null while no runtime is active. */
PackRuntime getPackRuntime();
default BiomeEnvironment getBiomeEnvironment(int x, int y, int z) {
return new BiomeEnvironment(0L, getBiome(x, y, z), getRegion(x, y, z), getDimension(), getData());
}
@@ -76,6 +76,7 @@ final class EngineHotloader {
engine.sealForTransition("complex hotload", false);
engine.prepareRuntimeHotload();
assembly = new RuntimeAssembly(
engine,
RuntimeAssembly.nextRuntimeId(),
previousGeneration.target(),
previousGeneration.mantleStorageDirectory(),
@@ -94,6 +95,7 @@ final class EngineHotloader {
GenerationRuntime nextGeneration = previousGeneration.withComplex(
assembly.cacheId,
assembly.complex,
assembly.packRuntime,
assembly.upperContext,
assembly.dimensionStackContext,
biomeMaxes);
@@ -1,52 +0,0 @@
package art.arcane.iris.generation.runtime;
import java.lang.ref.WeakReference;
/**
* Identifies an engine in pack-object cache keys without keeping it alive. Pack objects outlive
* worlds and sit in thread-local scratch on pooled threads, so a strong engine there pins a closed world.
*/
public final class EngineRef {
private static final EngineRef NONE = new EngineRef(null);
private final WeakReference<Engine> engine;
private final int identity;
EngineRef(Engine engine) {
this.engine = new WeakReference<>(engine);
this.identity = System.identityHashCode(engine);
}
public static EngineRef of(Engine engine) {
if (engine == null) {
return NONE;
}
if (engine instanceof IrisEngine irisEngine) {
return irisEngine.getCacheRef();
}
return new EngineRef(engine);
}
public boolean refersTo(Engine candidate) {
if (candidate == null) {
return this == NONE;
}
return this != NONE && engine.refersTo(candidate);
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (!(object instanceof EngineRef other) || this == NONE || other == NONE || identity != other.identity) {
return false;
}
Engine live = engine.get();
return live != null && other.engine.refersTo(live);
}
@Override
public int hashCode() {
return identity;
}
}
@@ -88,6 +88,7 @@ final class EngineRuntimeBuilder {
PreparedHydrologyCacheIdentity cacheIdentity
) {
RuntimeAssembly assembly = new RuntimeAssembly(
engine,
RuntimeAssembly.nextRuntimeId(),
runtimeTarget,
mantleStorageDirectory,
@@ -167,6 +168,7 @@ final class EngineRuntimeBuilder {
TransitionGenerationPlan transitionPlan
) {
RuntimeAssembly assembly = new RuntimeAssembly(
engine,
RuntimeAssembly.nextRuntimeId(),
runtimeTarget,
mantleStorageDirectory,
@@ -421,6 +423,7 @@ final class EngineRuntimeBuilder {
final GenerationKernelRegistry.RuntimeKernel runtimeKernel;
final SeedManager seedManager;
final TransitionGenerationPlan transitionPlan;
final PackRuntime packRuntime;
static int nextRuntimeId() {
return RUNTIME_IDS.incrementAndGet();
@@ -435,8 +438,9 @@ final class EngineRuntimeBuilder {
CompletableFuture<Long> hash32;
boolean ownsMantle;
RuntimeAssembly(int cacheId, EngineTarget target) {
RuntimeAssembly(Engine engine, int cacheId, EngineTarget target) {
this(
engine,
cacheId,
target,
null,
@@ -444,8 +448,9 @@ final class EngineRuntimeBuilder {
null);
}
RuntimeAssembly(int cacheId, EngineTarget target, Path mantleStorageDirectory) {
RuntimeAssembly(Engine engine, int cacheId, EngineTarget target, Path mantleStorageDirectory) {
this(
engine,
cacheId,
target,
mantleStorageDirectory,
@@ -454,6 +459,7 @@ final class EngineRuntimeBuilder {
}
RuntimeAssembly(
Engine engine,
int cacheId,
EngineTarget target,
Path mantleStorageDirectory,
@@ -469,6 +475,7 @@ final class EngineRuntimeBuilder {
this.seedManager = this.runtimeKernel.createSeedManager(target.getWorld().getRawWorldSeed());
this.kernelVersion = this.runtimeKernel.version();
this.transitionPlan = transitionPlan;
this.packRuntime = PackRuntime.forEngine(engine, target.getData());
}
GenerationRuntime freezeGeneration(BiomeMaxes biomeMaxes) {
@@ -485,6 +492,7 @@ final class EngineRuntimeBuilder {
seedManager,
transitionPlan,
complex,
packRuntime,
upperContext,
dimensionStackContext,
mode,
@@ -18,6 +18,10 @@
package art.arcane.iris.generation.runtime;
import art.arcane.iris.structure.nativegen.NativeStructureVolumeIndex;
import art.arcane.iris.structure.placement.StructureReachability;
import art.arcane.iris.structure.placement.StructurePlacementScope;
import art.arcane.iris.structure.placement.IrisStructureLocator;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.EngineBackgroundTasks.BackgroundTaskDrain;
import art.arcane.iris.generation.runtime.EngineRuntimeBuilder.RuntimeAssembly;
@@ -180,6 +184,7 @@ final class EngineShutdownSequence {
engine.closed = true;
engine.lifecycleState = LifecycleState.CLOSED;
}
failure = appendFailure(failure, runCleanup(null, this::releaseStructureRegistries));
IrisLogging.debug("Engine Fully Shutdown!");
}
}
@@ -207,6 +212,15 @@ final class EngineShutdownSequence {
throw new IllegalStateException("Iris engine shutdown remains incomplete after cleanup failures.", failure);
}
/** Engine-keyed structure registries hold only live engines, so a closed engine removes itself from each one. */
private void releaseStructureRegistries() {
NativeStructureOwnershipStore.release(engine);
IrisStructureLocator.invalidate(engine);
StructurePlacementScope.invalidate(engine);
StructureReachability.invalidate(engine);
NativeStructureVolumeIndex.uninstall(engine);
}
void cleanupFailedConstruction(Throwable original) {
engine.getClosing().set(true);
engine.backgroundTasks.closeBackgroundTaskAdmission();
@@ -251,6 +265,7 @@ final class EngineShutdownSequence {
cleanupFailure = releaseGenerationAdmissions(cleanupFailure);
if (generationAdmissions.isEmpty()) {
engine.closed = true;
cleanupFailure = appendFailure(cleanupFailure, runCleanup(null, this::releaseStructureRegistries));
}
}
}
@@ -23,29 +23,17 @@ import art.arcane.iris.generation.runtime.IrisEngine.BiomeEnvironmentBinding;
import art.arcane.iris.generation.runtime.IrisEngine.GenerationRuntimeBinding;
import art.arcane.iris.generation.runtime.IrisEngine.GenerationRuntimeScope;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReferenceArray;
/**
* Every per-thread engine binding (runtime assembly, biome environment, generation runtime scope) in one frame.
* The engine getters run on generation hot paths, where a ThreadLocal lookup probes long collision chains in the
* workers' crowded thread-local maps. Frames therefore live in a table indexed by thread id and owned by their
* thread; a frame whose slot is taken by another thread falls back to a ThreadLocal.
* workers' crowded thread-local maps. Frames therefore live in thread slots the engine owns, so a closed engine
* leaves nothing behind on its pooled workers.
*/
final class EngineThreadState {
private static final int SLOTS = 256;
private final AtomicReferenceArray<Frame> slots = new AtomicReferenceArray<>(SLOTS);
private final ThreadLocal<Frame> overflow = new ThreadLocal<>();
private final AtomicInteger overflowFrames = new AtomicInteger();
private final ThreadSlots<Frame> frames = ThreadSlots.bindings();
Frame current() {
Thread thread = Thread.currentThread();
Frame frame = slots.getPlain(slot(thread));
if (frame != null && frame.owner == thread) {
return frame;
}
return overflowFrames.get() == 0 ? null : overflow.get();
return frames.get();
}
GenerationRuntimeBinding binding() {
@@ -122,13 +110,8 @@ final class EngineThreadState {
if (frame != null) {
return frame;
}
Thread thread = Thread.currentThread();
frame = new Frame(thread);
if (!slots.compareAndSet(slot(thread), null, frame)) {
frame.overflow = true;
overflow.set(frame);
overflowFrames.incrementAndGet();
}
frame = new Frame();
frames.set(frame);
return frame;
}
@@ -136,27 +119,12 @@ final class EngineThreadState {
if (frame.assembly != null || frame.environment != null || frame.binding != null) {
return;
}
if (frame.overflow) {
overflow.remove();
overflowFrames.decrementAndGet();
return;
}
slots.compareAndSet(slot(frame.owner), frame, null);
}
private static int slot(Thread thread) {
return (int) thread.threadId() & (SLOTS - 1);
frames.remove();
}
static final class Frame {
private final Thread owner;
private boolean overflow;
RuntimeAssembly assembly;
BiomeEnvironmentBinding environment;
GenerationRuntimeBinding binding;
private Frame(Thread owner) {
this.owner = owner;
}
}
}
@@ -48,6 +48,7 @@ public final class GenerationCacheWarmer {
public static void warm(Engine engine) {
long start = M.ms();
IrisData data = engine.getData();
PackRuntime runtime = PackRuntime.of(engine, data);
RNG root = new RNG(engine.getSeedManager().getComponent() + 7777L);
int[] counter = {0};
List<ProceduralWarmTask> proceduralTasks = new ArrayList<>();
@@ -55,28 +56,28 @@ public final class GenerationCacheWarmer {
KList<IrisBiome> biomes = engine.getAllBiomes();
biomes.sort(Comparator.comparing(IrisBiome::getLoadKey));
for (IrisBiome biome : biomes) {
warmPlacements(biome.getObjects(), root, counter, data, engine);
warmDecorators(biome.getDecorators(), engine.getSeedManager().getComponent(), counter, data);
warmOres(biome.getOres(), engine.getSeedManager().getTerrain(), counter, data);
warmPlacements(biome.getObjects(), root, counter, runtime);
warmDecorators(biome.getDecorators(), engine.getSeedManager().getComponent(), counter, runtime);
warmOres(biome.getOres(), engine.getSeedManager().getTerrain(), counter, runtime);
collectProcedural(biome.getProceduralObjects(), root, counter, proceduralTasks);
}
KList<IrisRegion> regions = engine.getDimension().getAllRegions(engine);
regions.sort(Comparator.comparing(IrisRegion::getLoadKey));
for (IrisRegion region : regions) {
warmPlacements(region.getObjects(), root, counter, data, engine);
warmOres(region.getOres(), engine.getSeedManager().getTerrain(), counter, data);
warmPlacements(region.getObjects(), root, counter, runtime);
warmOres(region.getOres(), engine.getSeedManager().getTerrain(), counter, runtime);
collectProcedural(region.getProceduralObjects(), root, counter, proceduralTasks);
}
warmOres(engine.getDimension().getOres(), engine.getSeedManager().getTerrain(), counter, data);
warmOres(engine.getDimension().getOres(), engine.getSeedManager().getTerrain(), counter, runtime);
warmProcedural(proceduralTasks, data);
IrisLogging.debug("[IrisEngine timing] cache warm " + counter[0] + " configs=" + (M.ms() - start) + "ms");
}
private static void warmPlacements(KList<IrisObjectPlacement> placements, RNG root, int[] counter,
IrisData data, Engine engine) {
PackRuntime runtime) {
if (placements == null) {
return;
}
@@ -85,12 +86,12 @@ public final class GenerationCacheWarmer {
continue;
}
RNG rng = root.nextParallelRNG(counter[0]++);
placement.getSurfaceWarp(rng, data, engine);
placement.getDensity(rng, 0, 0, data);
placement.getSurfaceWarp(rng, runtime);
placement.getDensity(rng, 0, 0, runtime);
}
}
private static void warmDecorators(KList<IrisDecorator> decorators, long componentSeed, int[] counter, IrisData data) {
private static void warmDecorators(KList<IrisDecorator> decorators, long componentSeed, int[] counter, PackRuntime runtime) {
if (decorators == null) {
return;
}
@@ -100,13 +101,13 @@ public final class GenerationCacheWarmer {
}
counter[0]++;
RNG rng = new RNG(IrisEngineDecorator.seedForPart(componentSeed, decorator.getPartOf()));
decorator.getHeightGenerator(rng, data);
decorator.getGenerator(rng, data);
decorator.getVarianceGenerator(rng, data);
decorator.getHeightGenerator(rng, runtime);
decorator.getGenerator(rng, runtime);
decorator.getVarianceGenerator(rng, runtime);
}
}
private static void warmOres(KList<IrisOreGenerator> ores, long terrainSeed, int[] counter, IrisData data) {
private static void warmOres(KList<IrisOreGenerator> ores, long terrainSeed, int[] counter, PackRuntime runtime) {
if (ores == null) {
return;
}
@@ -115,7 +116,7 @@ public final class GenerationCacheWarmer {
continue;
}
counter[0]++;
ore.warm(new RNG(terrainSeed), data);
ore.warm(new RNG(terrainSeed), runtime);
}
}
@@ -38,6 +38,7 @@ record GenerationRuntime(
SeedManager seedManager,
TransitionGenerationPlan transitionPlan,
IrisComplex complex,
PackRuntime packRuntime,
UpperDimensionContext upperContext,
DimensionStackContext dimensionStackContext,
EngineMode mode,
@@ -57,6 +58,7 @@ record GenerationRuntime(
throw new IllegalArgumentException("Generation kernel version does not match its executable runtime.");
}
Objects.requireNonNull(complex, "generation complex");
Objects.requireNonNull(packRuntime, "generation pack runtime");
Objects.requireNonNull(mode, "generation mode");
Objects.requireNonNull(mantle, "generation mantle");
mantleStorageDirectory = IrisEngineMantle.normalizeStorageDirectory(mantleStorageDirectory);
@@ -70,6 +72,7 @@ record GenerationRuntime(
GenerationRuntime withComplex(
int nextCacheId,
IrisComplex nextComplex,
PackRuntime nextPackRuntime,
UpperDimensionContext nextUpperContext,
DimensionStackContext nextDimensionStackContext,
BiomeMaxes nextBiomeMaxes
@@ -84,6 +87,7 @@ record GenerationRuntime(
seedManager,
transitionPlan,
nextComplex,
nextPackRuntime,
nextUpperContext,
nextDimensionStackContext,
mode,
@@ -24,7 +24,6 @@ import art.arcane.iris.generation.bake.ChunkPlanes;
import art.arcane.iris.generation.bake.GeneratorEvaluations;
import art.arcane.iris.generation.bake.PlaneSource;
import art.arcane.iris.generation.bake.TerrainProgram;
import art.arcane.iris.generation.cache.ReleasableThreadLocal;
import art.arcane.iris.generation.noise.TerrainBatchScratch;
import art.arcane.iris.generation.stream.BakedDoubleStream;
import art.arcane.iris.generation.stream.BakedHeightStream;
@@ -156,9 +155,9 @@ public class IrisComplex implements DataProvider {
InferredType.SHORE
};
@Getter(AccessLevel.NONE)
private final transient ReleasableThreadLocal<GridBoundsCache> gridBoundsCache = new ReleasableThreadLocal<>(GridBoundsCache::new);
private final transient ThreadSlots<GridBoundsCache> gridBoundsCache = new ThreadSlots<>(GridBoundsCache::new);
@Getter(AccessLevel.NONE)
private final transient ReleasableThreadLocal<EffectiveWater.Chunks> effectiveChunks = new ReleasableThreadLocal<>(EffectiveWater.Chunks::new);
private final transient ThreadSlots<EffectiveWater.Chunks> effectiveChunks = new ThreadSlots<>(EffectiveWater.Chunks::new);
@Getter(AccessLevel.NONE)
private final int biomeBoundsSamplingStep;
private transient volatile SharedCornerBounds sharedCornerBounds;
@@ -201,6 +200,7 @@ public class IrisComplex implements DataProvider {
private RNG rng;
private double fluidHeight;
private IrisData data;
private final transient PackRuntime packRuntime;
private Map<IrisInterpolator, Set<IrisGenerator>> generators;
private ProceduralStream<IrisRegion> regionStream;
private ProceduralStream<Double> regionStyleStream;
@@ -326,6 +326,7 @@ public class IrisComplex implements DataProvider {
this.rng = new RNG(engine.getSeedManager().getComplex());
childStyleSeed = IrisBiome.childStyleSeed(rng, 123);
this.data = engine.getData();
this.packRuntime = PackRuntime.of(engine, data);
imageMapRuntime = IrisImageMapRuntime.compile(engine);
double height = engine.getMaxHeight();
fluidHeight = engine.getDimension().getFluidHeight();
@@ -413,20 +414,20 @@ public class IrisComplex implements DataProvider {
double value = 0D;
for (IrisShapedGeneratorStyle style : overlayNoise) {
value += style.get(rng, getData(), x, z);
value += style.get(rng, packRuntime, x, z);
}
return value;
});
bakeCache = new ChunkBakeCache(new BakeSource(), detached ? ChunkBakeCache.MINIMUM_CAPACITY
: ChunkBakeCache.capacityFor(Runtime.getRuntime().maxMemory()));
rockSource = engine.getDimension().getRockPalette().getLayerGenerator(rng.nextParallelRNG(45), data).stream()
rockSource = engine.getDimension().getRockPalette().getLayerGenerator(rng.nextParallelRNG(45), packRuntime).stream()
.select(engine.getDimension().getRockPalette().getBlockData(data));
rockStream = new BakedStream<>(bakeCache, BakePlane.ROCK, rockSource);
fluidSource = engine.getDimension().getFluidPalette().getLayerGenerator(rng.nextParallelRNG(78), data).stream()
fluidSource = engine.getDimension().getFluidPalette().getLayerGenerator(rng.nextParallelRNG(78), packRuntime).stream()
.select(engine.getDimension().getFluidPalette().getBlockData(data));
fluidStream = new BakedStream<>(bakeCache, BakePlane.FLUID, fluidSource);
regionStyleStream = engine.getDimension().getRegionStyle().create(rng.nextParallelRNG(883), getData()).stream()
regionStyleStream = engine.getDimension().getRegionStyle().create(rng.nextParallelRNG(883), packRuntime).stream()
.zoom(engine.getDimension().getRegionZoom());
regionIdentityStream = regionStyleStream.fit(Integer.MIN_VALUE, Integer.MAX_VALUE);
regionSource = focusedRegions != null ? focusedRegions
@@ -452,7 +453,7 @@ public class IrisComplex implements DataProvider {
.convertAware2D(ProceduralStream::get);
inferredStreams.put(InferredType.SHORE, shoreBiomeStream);
bridgeStream = focusedBiomes != null ? focusedBiomes.convert(IrisBiome::getInferredType) :
ContinentGenerator.create(engine.getDimension(), rng, getData()).stream()
ContinentGenerator.create(engine.getDimension(), rng, packRuntime).stream()
.convert((v) -> v >= engine.getDimension().getLandChance() ? InferredType.SEA : InferredType.LAND);
ProceduralStream<IrisBiome> proceduralBaseBiomeStream = focusedBiomes != null ? focusedBiomes
: ProceduralStream.of(this::proceduralBaseBiome,
@@ -484,7 +485,7 @@ public class IrisComplex implements DataProvider {
(x, z) -> baseTerrainHeightStream.getDouble(x, z),
this::sampleTerrain3DBiome),
new Terrain3DRuntime.Options(engine.getSeedManager().getTerrain(), engine.getHeight(),
fluidHeight, data, terrain3DEnabled, TERRAIN_COLUMN_CACHE_SIZE));
fluidHeight, packRuntime, terrain3DEnabled, TERRAIN_COLUMN_CACHE_SIZE));
unblendedNaturalHeightStream = terrain3DEnabled
? ProceduralStream.ofDouble(this::sampleTerrain3DHeight)
: baseTerrainHeightStream;
@@ -1057,7 +1058,7 @@ public class IrisComplex implements DataProvider {
synchronized (this) {
program = terrainProgram;
if (program == null) {
program = TerrainProgram.compile(frozenGenerators, terrainEngine.getSeedManager().getHeight() + 239945);
program = TerrainProgram.compile(packRuntime, frozenGenerators, terrainEngine.getSeedManager().getHeight() + 239945);
terrainProgram = program;
}
}
@@ -1175,21 +1176,21 @@ public class IrisComplex implements DataProvider {
private ProceduralStream<Double> biomePickNoiseStream(IrisDimension dimension, IrisRegion region, InferredType inferredType) {
return switch (inferredType) {
case CAVE -> dimension.getCaveBiomeStyle()
.create(rng.nextParallelRNG(InferredType.CAVE.ordinal()), getData()).stream()
.create(rng.nextParallelRNG(InferredType.CAVE.ordinal()), packRuntime).stream()
.zoom(dimension.getBiomeZoom())
.zoom(region.getCaveBiomeZoom());
case LAND -> dimension.getLandBiomeStyle()
.create(rng.nextParallelRNG(InferredType.LAND.ordinal()), getData()).stream()
.create(rng.nextParallelRNG(InferredType.LAND.ordinal()), packRuntime).stream()
.zoom(dimension.getBiomeZoom())
.zoom(dimension.getLandZoom())
.zoom(region.getLandBiomeZoom());
case SEA -> dimension.getSeaBiomeStyle()
.create(rng.nextParallelRNG(InferredType.SEA.ordinal()), getData()).stream()
.create(rng.nextParallelRNG(InferredType.SEA.ordinal()), packRuntime).stream()
.zoom(dimension.getBiomeZoom())
.zoom(dimension.getSeaZoom())
.zoom(region.getSeaBiomeZoom());
case SHORE -> dimension.getShoreBiomeStyle()
.create(rng.nextParallelRNG(InferredType.SHORE.ordinal()), getData()).stream()
.create(rng.nextParallelRNG(InferredType.SHORE.ordinal()), packRuntime).stream()
.zoom(dimension.getBiomeZoom())
.zoom(region.getShoreBiomeZoom());
};
@@ -1309,7 +1310,7 @@ public class IrisComplex implements DataProvider {
configurationName + " fluidPalette may contain only fluid blocks");
}
}
return palette.getLayerGenerator(fluidRng, data).stream().select(blocks);
return palette.getLayerGenerator(fluidRng, packRuntime).stream().select(blocks);
}
public NativeBlockState resolveSeaFluid(double x, double z) {
@@ -1962,7 +1963,7 @@ public class IrisComplex implements DataProvider {
}
if (program == null || program.heightSeed() != heightSeed || group >= program.groups()
|| program.groupSize(group) != generators.length || generators != frozenGenerators[group]) {
return averageGeneratorHeights(generators, low, high, x, z, heightSeed);
return averageGeneratorHeights(packRuntime, generators, low, high, x, z, heightSeed);
}
return program.average(group, BATCH_SCRATCH.get(), low, high, x, z);
}
@@ -2129,7 +2130,7 @@ public class IrisComplex implements DataProvider {
IrisBiome biome = focusedBiomeAt(x, z);
for (GeneratorGroup group : biomeBuffetGenerators.get(biome)) {
NoiseBounds bounds = generatorBounds.get(group.interpolator()).get(biome).noiseBounds;
h += averageGeneratorHeights(group.generators(), bounds.min(), bounds.max(), x, z, seed + 239945);
h += averageGeneratorHeights(packRuntime, group.generators(), bounds.min(), bounds.max(), x, z, seed + 239945);
}
return h;
}
@@ -2408,6 +2409,7 @@ public class IrisComplex implements DataProvider {
}
static double averageGeneratorHeights(
PackRuntime runtime,
IrisGenerator[] generators,
double low,
double high,
@@ -2434,7 +2436,7 @@ public class IrisComplex implements DataProvider {
GenerationCounter.GENERATOR_EVALUATIONS.add(generators.length);
}
for (IrisGenerator generator : generators) {
double noise = generator.getHeight(x, z, seed);
double noise = generator.getHeight(runtime, x, z, seed);
if (!Double.isFinite(noise)) {
throw new IllegalStateException("Terrain generator noise was not finite at " + x + "," + z
+ " (generator=" + generator.getLoadKey() + ", noise=" + noise
@@ -2528,7 +2530,7 @@ public class IrisComplex implements DataProvider {
}
private IrisBiome pickChild(IrisBiome parent, double x, double z) {
CNG childCell = parent.getChildrenGenerator(childStyleSeed, parent.getChildShrinkFactor());
CNG childCell = parent.getChildrenGenerator(packRuntime, childStyleSeed, parent.getChildShrinkFactor());
return resolveChildSelectionPlan(parent).select(childCell, x, z).withInferredType(parent.getInferredType());
}
@@ -2994,8 +2996,6 @@ public class IrisComplex implements DataProvider {
terrain3D.clear();
}
bakeCache.clear();
gridBoundsCache.releaseAll();
effectiveChunks.releaseAll();
if (transitionDisplacement != null) {
transitionDisplacement.clear();
}
@@ -65,10 +65,8 @@ import art.arcane.volmlib.util.scheduling.ChronoLatch;
import art.arcane.volmlib.util.scheduling.PrecisionStopwatch;
import lombok.AccessLevel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.awt.Color;
import java.io.IOException;
@@ -101,10 +99,6 @@ public class IrisEngine implements Engine {
private final AtomicDouble perSecond;
private final AtomicLong lastGPS;
private final EngineTarget target;
@Getter(AccessLevel.PACKAGE)
@EqualsAndHashCode.Exclude
@ToString.Exclude
private final EngineRef cacheRef = new EngineRef(this);
private final InitializationMode initializationMode;
private final Path initialMantleStorageDirectory;
private final GenerationKernelRegistry.Version initialKernelVersion;
@@ -1430,6 +1424,17 @@ public class IrisEngine implements Engine {
return complexIn(threadState.current());
}
@Override
public PackRuntime getPackRuntime() {
EngineThreadState.Frame frame = threadState.current();
RuntimeAssembly assembly = frame == null ? null : frame.assembly;
if (assembly != null) {
return assembly.packRuntime;
}
GenerationRuntime current = selectedGenerationRuntime(frame);
return current == null ? null : current.packRuntime();
}
private IrisComplex complexIn(EngineThreadState.Frame frame) {
RuntimeAssembly assembly = frame == null ? null : frame.assembly;
if (assembly != null && assembly.complex != null) {
@@ -0,0 +1,258 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* 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 <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.generation.runtime;
import art.arcane.iris.generation.biome.BiomeRuntime;
import art.arcane.iris.generation.biome.FloatingChildRuntime;
import art.arcane.iris.generation.biome.FloatingIslandMemo;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.biome.IrisBiomePaletteLayer;
import art.arcane.iris.generation.biome.IrisFloatingChildBiomes;
import art.arcane.iris.generation.biome.PaletteLayerRuntime;
import art.arcane.iris.generation.decoration.DecoratorRuntime;
import art.arcane.iris.generation.decoration.DepositRuntime;
import art.arcane.iris.generation.decoration.IrisDecorator;
import art.arcane.iris.generation.decoration.IrisDepositGenerator;
import art.arcane.iris.generation.decoration.IrisOreBands;
import art.arcane.iris.generation.decoration.IrisOreGenerator;
import art.arcane.iris.generation.decoration.OreBandsRuntime;
import art.arcane.iris.generation.noise.ExpressionRuntime;
import art.arcane.iris.generation.noise.GeneratorRuntime;
import art.arcane.iris.generation.noise.IrisExpression;
import art.arcane.iris.generation.noise.IrisGenerator;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.IrisNoiseGenerator;
import art.arcane.iris.generation.terrain.IrisDimensionCarvingEntry;
import art.arcane.iris.generation.terrain.IrisDimensionCarvingResolver;
import art.arcane.iris.generation.terrain.IrisMaterialPalette;
import art.arcane.iris.structure.graph.StructureGraphCompilation;
import art.arcane.iris.structure.object.IrisObjectPlacement;
import art.arcane.iris.world.entity.IrisEffect;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG;
import art.arcane.volmlib.util.scheduling.ChronoLatch;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* The runtime objects one owner derives from pack objects: seeded generators, samplers and profiles. Pack objects are
* read-only configuration, so everything built for a seed, an engine or a world lives here and dies with the owner.
* An engine owns one per generation runtime; engine-less tools use the scope their {@link IrisData} owns.
*/
public final class PackRuntime {
private static final int STYLE_SEED_CAPACITY = 8;
private static final int NOISE_LAYER_SEED_CAPACITY = 32;
private static final int MATERIAL_PALETTE_SEED_CAPACITY = 32;
private static final int CARVING_CHILD_SEED_CAPACITY = 8;
private static final int ORE_CHANCE_SEED_CAPACITY = 32;
private static final int ORE_BANDS_SEED_CAPACITY = 8;
private static final int SURFACE_WARP_SEED_CAPACITY = 8;
private final Engine engine;
private final IrisData data;
private final RuntimeTable<IrisData, PackRuntime> foreignDataScopes;
private final RuntimeTable<IrisGeneratorStyle, SeedTable<CNG>> styleGenerators = new RuntimeTable<>(
style -> new SeedTable<>(STYLE_SEED_CAPACITY, seed -> style.createNoCache(new RNG(seed), this)));
private final RuntimeTable<IrisNoiseGenerator, SeedTable<CNG>> noiseLayerGenerators = new RuntimeTable<>(
layer -> new SeedTable<>(NOISE_LAYER_SEED_CAPACITY, seed -> layer.buildGenerator(seed, this)));
private final RuntimeTable<IrisMaterialPalette, SeedTable<CNG>> materialPaletteGenerators = new RuntimeTable<>(
palette -> new SeedTable<>(MATERIAL_PALETTE_SEED_CAPACITY, seed -> palette.createLayerGenerator(seed, this)));
private final RuntimeTable<IrisDimensionCarvingEntry, SeedTable<CNG>> carvingChildGenerators = new RuntimeTable<>(
entry -> new SeedTable<>(CARVING_CHILD_SEED_CAPACITY, seed -> entry.createChildrenGenerator(seed, this)));
private final RuntimeTable<IrisOreGenerator, SeedTable<IrisOreGenerator.OreChance>> oreChances = new RuntimeTable<>(
ore -> new SeedTable<>(ORE_CHANCE_SEED_CAPACITY, seed -> ore.createChance(seed, this)));
private final RuntimeTable<IrisOreBands, SeedTable<OreBandsRuntime>> oreBands = new RuntimeTable<>(
bands -> new SeedTable<>(ORE_BANDS_SEED_CAPACITY, seed -> new OreBandsRuntime(bands, seed, this)));
private final RuntimeTable<IrisObjectPlacement, SeedTable<CNG>> surfaceWarps = new RuntimeTable<>(
placement -> new SeedTable<>(SURFACE_WARP_SEED_CAPACITY, seed -> placement.createSurfaceWarp(seed, this)));
private final ConcurrentMap<String, StructureGraphCompilation> structureGraphs = new ConcurrentHashMap<>();
private final ConcurrentMap<String, Boolean> structureRuntimeOutputs = new ConcurrentHashMap<>();
private final ThreadSlots<IrisDimensionCarvingResolver.State> carvingResolverStates =
new ThreadSlots<>(IrisDimensionCarvingResolver.State::new);
private final RuntimeTable<IrisEffect, ChronoLatch> effectLatches =
new RuntimeTable<>(effect -> new ChronoLatch(effect.getInterval()));
private final RuntimeTable<IrisDecorator, DecoratorRuntime> decorators =
new RuntimeTable<>(decorator -> new DecoratorRuntime(decorator, this));
private final RuntimeTable<IrisDepositGenerator, DepositRuntime> deposits =
new RuntimeTable<>(deposit -> new DepositRuntime(deposit, this));
private final RuntimeTable<IrisGenerator, GeneratorRuntime> generators = new RuntimeTable<>(GeneratorRuntime::new);
private final RuntimeTable<IrisExpression, ExpressionRuntime> expressions =
new RuntimeTable<>(expression -> new ExpressionRuntime(expression, this));
private final RuntimeTable<IrisBiome, BiomeRuntime> biomes = new RuntimeTable<>(biome -> new BiomeRuntime(biome, this));
private final RuntimeTable<IrisBiomePaletteLayer, PaletteLayerRuntime> paletteLayers =
new RuntimeTable<>(layer -> new PaletteLayerRuntime(layer, this));
private final RuntimeTable<IrisFloatingChildBiomes, FloatingChildRuntime> floatingChildren =
new RuntimeTable<>(entry -> new FloatingChildRuntime(entry, this));
private final ThreadSlots<FloatingIslandMemo> floatingIslandMemos = new ThreadSlots<>(FloatingIslandMemo::new);
private PackRuntime(Engine engine, IrisData data) {
this.engine = engine;
this.data = data;
this.foreignDataScopes = engine == null ? null : new RuntimeTable<>(foreign -> new PackRuntime(engine, foreign));
}
/** The scope an engine owns for its pack; the engine creates it with each generation runtime. */
public static PackRuntime forEngine(Engine engine, IrisData data) {
return new PackRuntime(Objects.requireNonNull(engine, "engine"), data);
}
/** A scope for tools without an engine. A null pack is allowed for content that never loads other files. */
public static PackRuntime standalone(IrisData data) {
return new PackRuntime(null, data);
}
/**
* The runtime scope for work on this pack: the engine's while one is generating, otherwise the scope the pack
* data owns. Resolve it once per chunk or column and pass it down.
*/
public static PackRuntime of(Engine engine, IrisData data) {
PackRuntime engineRuntime = engine == null ? null : engine.getPackRuntime();
if (engineRuntime == null) {
return forPack(data);
}
return engineRuntime.scopeFor(data);
}
/** The scope a pack keeps for content baked from its own files alone, such as procedural object variants. */
public static PackRuntime forPack(IrisData data) {
return data == null ? standalone(null) : data.standalonePackRuntime();
}
/** The engine's scope for its own pack. */
public static PackRuntime of(Engine engine) {
return of(engine, engine.getData());
}
/** The owning engine, or null for an engine-less scope. */
public Engine engine() {
return engine;
}
public IrisData data() {
return data;
}
/**
* The scope this owner keeps for another pack, such as a stacked dimension's. Pack objects resolve expressions
* and images through their own data, so runtime objects of a foreign pack must be built against it.
*/
public PackRuntime scopeFor(IrisData packData) {
if (packData == null || packData == data || foreignDataScopes == null) {
return this;
}
return foreignDataScopes.get(packData);
}
/** Styles are shared configuration that each caller seeds itself, so a style keeps one generator per seed. */
public CNG styleGenerator(IrisGeneratorStyle style, long seed) {
return styleGenerators.get(style).get(seed);
}
/** Noise layers are seeded from the generator that reads them, so a layer keeps one generator per seed. */
public CNG noiseLayerGenerator(IrisNoiseGenerator layer, long seed) {
return noiseLayerGenerators.get(layer).get(seed);
}
/** Material palettes are seeded by the stream or decorator that reads them, so a palette keeps one generator per seed. */
public CNG materialPaletteGenerator(IrisMaterialPalette palette, long seed) {
return materialPaletteGenerators.get(palette).get(seed);
}
/** Carving entries pick their children from the carve seed, so an entry keeps one child generator per seed. */
public CNG carvingChildGenerator(IrisDimensionCarvingEntry entry, long seed) {
return carvingChildGenerators.get(entry).get(seed);
}
/** Ores are seeded by the stage that places them, so an ore keeps one chance field per seed. */
public IrisOreGenerator.OreChance oreChance(IrisOreGenerator ore, long seed) {
return oreChances.get(ore).get(seed);
}
/** An ore list's chance fields for one seed, resolved together so painting a column holds them directly. */
public OreBandsRuntime oreBands(IrisOreBands bands, long seed) {
return oreBands.get(bands).get(seed);
}
/** Object placements warp by the engine's component seed, so a placement keeps one warp generator per seed. */
public CNG surfaceWarp(IrisObjectPlacement placement, long seed) {
return surfaceWarps.get(placement).get(seed);
}
/** Structure graphs compile from the pack's own files, so the pack scope keeps one compilation per structure key. */
public ConcurrentMap<String, StructureGraphCompilation> structureGraphs() {
return structureGraphs;
}
/** Whether each structure's sampled assemblies always place output, keyed like {@link #structureGraphs()}. */
public ConcurrentMap<String, Boolean> structureRuntimeOutputs() {
return structureRuntimeOutputs;
}
/** Hotload drops the compiled structure graphs of a pack whose files changed. */
public void forgetStructureGraphs() {
structureGraphs.clear();
structureRuntimeOutputs.clear();
}
/** Carving lookups that are not handed a resolver state memoize their roots in the calling thread's state. */
public IrisDimensionCarvingResolver.State carvingResolverState() {
return carvingResolverStates.get();
}
/** Every player and entity of this owner shares one interval latch per effect. */
public ChronoLatch effectLatch(IrisEffect effect) {
return effectLatches.get(effect);
}
public DecoratorRuntime decorator(IrisDecorator decorator) {
return decorators.get(decorator);
}
public DepositRuntime deposit(IrisDepositGenerator deposit) {
return deposits.get(deposit);
}
public GeneratorRuntime generator(IrisGenerator generator) {
return generators.get(generator);
}
public ExpressionRuntime expression(IrisExpression expression) {
return expressions.get(expression);
}
public BiomeRuntime biome(IrisBiome biome) {
return biomes.get(biome);
}
public PaletteLayerRuntime paletteLayer(IrisBiomePaletteLayer layer) {
return paletteLayers.get(layer);
}
public FloatingChildRuntime floatingChild(IrisFloatingChildBiomes entry) {
return floatingChildren.get(entry);
}
/** The calling worker's floating island samples for its current chunk. */
public FloatingIslandMemo floatingIslandMemo() {
return floatingIslandMemos.get();
}
}
@@ -0,0 +1,68 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* 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 <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.generation.runtime;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
/**
* Runtime objects of one kind keyed by the identity of the pack object they were built from. Pack types compare by
* value, so two equal configurations still get their own runtime object. A builder may resolve other runtime objects
* from the same table, so entries are built outside the map and the first one published wins.
*/
public final class RuntimeTable<C, R> {
private final ConcurrentHashMap<Identity, R> entries = new ConcurrentHashMap<>();
private final Function<C, R> builder;
public RuntimeTable(Function<C, R> builder) {
this.builder = Objects.requireNonNull(builder, "runtime builder");
}
public R get(C config) {
Identity key = new Identity(Objects.requireNonNull(config, "pack object"));
R existing = entries.get(key);
if (existing != null) {
return existing;
}
R built = Objects.requireNonNull(builder.apply(config), "runtime object");
R raced = entries.putIfAbsent(key, built);
return raced == null ? built : raced;
}
private static final class Identity {
private final Object referent;
private final int hash;
private Identity(Object referent) {
this.referent = referent;
this.hash = System.identityHashCode(referent);
}
@Override
public boolean equals(Object other) {
return other instanceof Identity identity && identity.referent == referent;
}
@Override
public int hashCode() {
return hash;
}
}
}
@@ -0,0 +1,99 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* 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 <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.generation.runtime;
import java.util.LinkedHashMap;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.function.LongFunction;
/**
* The values one runtime object builds per seed, for pack objects that callers sample with seeds they derive
* themselves. Bounded by least-recent use; an evicted value is rebuilt from the same seed, so eviction never changes
* output. Recently used values are kept aside in seed-indexed slots because callers usually ask for the same few
* seeds many times in a row.
*/
public final class SeedTable<T> {
private static final int SINGLE_RECENT_SLOT = 1;
private final int capacity;
private final LongFunction<T> builder;
private final LinkedHashMap<Long, T> entries;
private final AtomicReferenceArray<Recent<T>> recent;
private final int recentMask;
public SeedTable(int capacity, LongFunction<T> builder) {
this(capacity, SINGLE_RECENT_SLOT, builder);
}
/** @param recentSlots a power of two: how many seeds stay on the lock-free path at once */
public SeedTable(int capacity, int recentSlots, LongFunction<T> builder) {
if (capacity < 1) {
throw new IllegalArgumentException("Seed table capacity must be positive.");
}
if (recentSlots < 1 || Integer.bitCount(recentSlots) != 1) {
throw new IllegalArgumentException("Recent seed slots must be a positive power of two.");
}
this.capacity = capacity;
this.builder = Objects.requireNonNull(builder, "seed builder");
this.entries = new LinkedHashMap<>(capacity * 2, 0.75F, true);
this.recent = new AtomicReferenceArray<>(recentSlots);
this.recentMask = recentSlots - 1;
}
public T get(long seed) {
int slot = (int) seed & recentMask;
Recent<T> last = recent.getAcquire(slot);
if (last != null && last.seed == seed) {
return last.value;
}
T value = stored(seed);
if (value == null) {
value = publish(seed, Objects.requireNonNull(builder.apply(seed), "seeded runtime value"));
}
recent.setRelease(slot, new Recent<>(seed, value));
return value;
}
private T stored(long seed) {
synchronized (entries) {
return entries.get(seed);
}
}
private T publish(long seed, T built) {
synchronized (entries) {
T raced = entries.putIfAbsent(seed, built);
if (raced != null) {
return raced;
}
evictBeyondCapacity();
return built;
}
}
private void evictBeyondCapacity() {
while (entries.size() > capacity) {
entries.sequencedKeySet().removeFirst();
}
}
private record Recent<T>(long seed, T value) {
}
}
@@ -0,0 +1,150 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* 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 <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.generation.runtime;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.function.Supplier;
/**
* Per-thread values owned by the object that holds this table, typically an engine-owned runtime. Unlike a
* ThreadLocal, the values live here and not in the worker threads, so they become unreachable with their owner even
* while the pooled workers that filled them stay alive. A live thread never loses its value: a thread whose probed
* slots all belong to other live threads keeps its value in an overflow map, which drops dead threads whenever it
* takes a new one. The size therefore follows the live threads and not the worker churn.
* <p>
* Owners and values sit in parallel arrays so the common lookup, a thread in its home slot, is one owner compare and
* one value read that do not depend on each other. Only the owning thread writes a slot's value, and a slot changes
* owner only once its previous owner removed its value or died, so an owner match always pairs with that owner's
* value. Until some thread has had to store away from its home slot, a thread missing from its home slot has no
* value at all, so unbound threads skip the probe too.
*/
public final class ThreadSlots<T> {
private static final int SLOT_COUNT = 256;
private static final int SLOT_MASK = SLOT_COUNT - 1;
private static final int PROBE_LIMIT = 8;
private static final int NOT_FOUND = -1;
private final AtomicReferenceArray<Thread> owners = new AtomicReferenceArray<>(SLOT_COUNT);
private final AtomicReferenceArray<T> values = new AtomicReferenceArray<>(SLOT_COUNT);
private final ConcurrentHashMap<Thread, T> overflow = new ConcurrentHashMap<>();
private final Supplier<T> factory;
private volatile boolean storedAwayFromHome;
/** A table whose threads each get a value from the factory on first use. */
public ThreadSlots(Supplier<T> factory) {
this.factory = Objects.requireNonNull(factory, "thread value factory");
}
private ThreadSlots() {
this.factory = null;
}
/** A table of values each thread binds with {@link #set} and clears with {@link #remove}. */
public static <T> ThreadSlots<T> bindings() {
return new ThreadSlots<>();
}
/** This thread's value, created by the factory on first use; null for an unbound thread of a bindings table. */
public T get() {
Thread thread = Thread.currentThread();
int home = home(thread);
if (owners.getPlain(home) == thread) {
return values.getPlain(home);
}
T awayFromHome = storedAwayFromHome ? getAwayFromHome(thread) : null;
if (awayFromHome != null || factory == null) {
return awayFromHome;
}
T created = factory.get();
store(thread, created);
return created;
}
public void set(T value) {
if (value == null) {
remove();
return;
}
Thread thread = Thread.currentThread();
int index = find(thread);
if (index != NOT_FOUND) {
values.set(index, value);
return;
}
if (overflow.replace(thread, value) == null) {
store(thread, value);
}
}
public void remove() {
Thread thread = Thread.currentThread();
int index = find(thread);
if (index != NOT_FOUND) {
values.set(index, null);
owners.set(index, null);
return;
}
if (!overflow.isEmpty()) {
overflow.remove(thread);
}
}
private T getAwayFromHome(Thread thread) {
int index = find(thread);
if (index != NOT_FOUND) {
return values.getPlain(index);
}
return overflow.isEmpty() ? null : overflow.get(thread);
}
private int find(Thread thread) {
int home = home(thread);
for (int probe = 0; probe < PROBE_LIMIT; probe++) {
int index = (home + probe) & SLOT_MASK;
if (owners.getPlain(index) == thread) {
return index;
}
}
return NOT_FOUND;
}
private void store(Thread thread, T value) {
int home = home(thread);
for (int probe = 0; probe < PROBE_LIMIT; probe++) {
int index = (home + probe) & SLOT_MASK;
Thread current = owners.get(index);
if ((current == null || !current.isAlive()) && owners.compareAndSet(index, current, thread)) {
values.set(index, value);
if (probe > 0) {
storedAwayFromHome = true;
}
return;
}
}
storedAwayFromHome = true;
overflow.keySet().removeIf(owner -> !owner.isAlive());
overflow.put(thread, value);
}
private static int home(Thread thread) {
return (int) thread.threadId() & SLOT_MASK;
}
}
@@ -61,6 +61,7 @@ public class IrisBiomeActuator extends EngineAssignedActuator<NativeBiome> {
ChunkedDataCache<IrisBiome> biomeCache = context.getBiome();
IrisComplex complex = context.getComplex();
DimensionStackContext dimensionStackContext = engine.getDimensionStackContext();
IrisDimension dimension = getDimension();
for (int xf = 0; xf < width; xf++) {
for (int zf = 0; zf < depth; zf++) {
@@ -69,7 +70,7 @@ public class IrisBiomeActuator extends EngineAssignedActuator<NativeBiome> {
IrisBiome biome = biomeCache.get(xf, zf);
NativeBiome platformBiome = resolve(biomeKey(
biome,
getDimension(),
dimension,
engine,
worldX,
0,
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.stage;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.subterrain.SubterrainCell;
import art.arcane.iris.generation.subterrain.SubterrainPlanner;
@@ -42,6 +43,7 @@ import art.arcane.iris.generation.mantle.TerrainMatterView;
import art.arcane.iris.generation.terrain.InferredType;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.biome.IrisBiomePaletteLayer;
import art.arcane.iris.generation.biome.PaletteLayerRuntime;
import art.arcane.iris.generation.decoration.IrisDecorationPart;
import art.arcane.iris.generation.decoration.IrisDecorator;
import art.arcane.iris.generation.terrain.IrisDimensionCarvingResolver;
@@ -230,6 +232,7 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
} finally {
getEngine().getMetrics().getCave().put(caveStopwatch.getMilliseconds());
mantleChunk.release();
scratch.releaseReferences();
}
}
@@ -340,7 +343,7 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
int blockZ = chunkZ << 4;
return new SubterrainSurfaceMaterials(planner,
planner.plansForBounds(blockX - 1, blockZ - 1, blockX + 16, blockZ + 16),
getEngine().getDimension(), getComplex(), getData(), rng, getEngine().getWorld().minHeight());
getEngine().getDimension(), getComplex(), PackRuntime.of(getEngine()), rng, getEngine().getWorld().minHeight());
}
static boolean hasExplicitCarveIntent(MatterCavern cavern) {
@@ -606,6 +609,9 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
private final IrisData data;
private final int chunkBlockX;
private final int chunkBlockZ;
private final PackRuntime wallRuntime;
private IrisBiomePaletteLayer lastWall;
private PaletteLayerRuntime lastWallRuntime;
private WallPainter(Hunk<NativeBlockState> output, CaveTerrainSnapshot terrain, CaveInputs inputs,
Long2ObjectOpenHashMap<IrisBiome> caveBiomeCache, Map<String, IrisBiome> customBiomeCache,
@@ -619,6 +625,7 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
this.data = data;
this.chunkBlockX = chunkBlockX;
this.chunkBlockZ = chunkBlockZ;
this.wallRuntime = inputs.runtime.scopeFor(data);
}
@Override
@@ -637,11 +644,20 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
if (biome == null) {
return;
}
NativeBlockState wall = biome.getWall().get(rng, worldX, yy, worldZ, data);
IrisBiomePaletteLayer wallLayer = biome.getWall();
NativeBlockState wall = wallLayer.get(rng, 0, worldX, yy, worldZ, wallLayerRuntime(wallLayer));
if (wall != null) {
output.setRaw(rx, yy, rz, wall);
}
}
private PaletteLayerRuntime wallLayerRuntime(IrisBiomePaletteLayer wallLayer) {
if (wallLayer != lastWall) {
lastWall = wallLayer;
lastWallRuntime = wallRuntime.paletteLayer(wallLayer);
}
return lastWallRuntime;
}
}
private void addInternalWallsFromMantle(CaveTerrainSnapshot terrain, CarveWallBuffer walls, CarveColumnMask[] columnMasks) {
@@ -1016,13 +1032,13 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
private KList<NativeBlockState> floorLayers(CaveLayerMemo layers, IrisBiome biome, int worldX, int worldZ, int floorY,
CaveInputs inputs) {
if (!hasHeightFreeFloorLayers(biome)) {
return biome.generateLayers(inputs.dimension, worldX, worldZ, rng, 3, floorY, inputs.data, inputs.complex);
return biome.generateLayers(inputs.dimension, worldX, worldZ, rng, 3, floorY, inputs.runtime, inputs.complex);
}
KList<NativeBlockState> remembered = layers.floor(biome);
if (remembered != null) {
return remembered;
}
KList<NativeBlockState> blocks = biome.generateLayers(inputs.dimension, worldX, worldZ, rng, 3, floorY, inputs.data, inputs.complex);
KList<NativeBlockState> blocks = biome.generateLayers(inputs.dimension, worldX, worldZ, rng, 3, floorY, inputs.runtime, inputs.complex);
layers.rememberFloor(biome, blocks);
return blocks;
}
@@ -1033,7 +1049,7 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
if (remembered != null) {
return remembered;
}
KList<NativeBlockState> blocks = biome.generateCeilingLayers(inputs.dimension, worldX, worldZ, rng, 3, ceilingY, inputs.data, inputs.complex);
KList<NativeBlockState> blocks = biome.generateCeilingLayers(inputs.dimension, worldX, worldZ, rng, 3, ceilingY, inputs.runtime, inputs.complex);
layers.rememberCeiling(biome, blocks);
return blocks;
}
@@ -1356,6 +1372,7 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
private final IrisComplex complex;
private final IrisDimension dimension;
private final IrisData data;
private final PackRuntime runtime;
private final int height;
private final IrisDimensionCarvingResolver.State state = new IrisDimensionCarvingResolver.State();
private final IrisDimensionCarvingResolver.Snapshot snapshot;
@@ -1393,6 +1410,7 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
complex = engine.getComplex();
dimension = engine.getDimension();
data = engine.getData();
runtime = PackRuntime.of(engine, data);
height = engine.getHeight();
cells = SubterrainChunkCells.of(engine, chunkX, chunkZ);
IrisContext context = IrisContext.get();
@@ -67,6 +67,12 @@ final class IrisCarveScratch {
caveBiomeCache.clear();
customCaveBiomePresent = false;
}
/** Drops every biome, block and cavern reference so the thread's scratch pins no pack once a chunk is carved. */
void releaseReferences() {
reset();
layers.reset();
}
}
final class CaveLayerMemo {
@@ -78,6 +84,8 @@ final class CaveLayerMemo {
private int ceilingCount;
void reset() {
Arrays.fill(floor, 0, floorCount, null);
Arrays.fill(ceiling, 0, ceilingCount, null);
floorCount = 0;
ceilingCount = 0;
}
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.stage;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.decoration.HydrologyVegetation;
import art.arcane.iris.generation.decoration.IrisCeilingDecorator;
import art.arcane.iris.generation.decoration.IrisSeaFloorDecorator;
@@ -140,6 +141,7 @@ public class IrisDecorantActuator extends EngineAssignedActuator<NativeBlockStat
PrecisionStopwatch p = PrecisionStopwatch.start();
HydrologyVegetation.Water water = new ComplexWater(getComplex());
PackRuntime runtime = PackRuntime.of(getEngine(), getData());
for (int i = 0; i < output.getWidth(); i++) {
int height;
int realX = Math.round(x + i);
@@ -159,7 +161,7 @@ public class IrisDecorantActuator extends EngineAssignedActuator<NativeBlockStat
getComplex().getWaterHeadStream().get(realX, realZ)) : transitionTerrain.fluidHeight();
if (role != WaterRole.NONE) {
getHydrologyVegetation().decorate(output, i, j, realX, realZ, role, water, getData());
getHydrologyVegetation().decorate(output, i, j, realX, realZ, role, water, runtime);
}
if (biome.getDecorators().isEmpty() && (cave == null || cave.getDecorators().isEmpty())) {
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.stage;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.GenerationFailures;
import art.arcane.iris.generation.runtime.IrisEngine;
@@ -100,10 +101,11 @@ public class IrisDepositModifier extends EngineAssignedModifier<NativeBlockState
try {
List<DepositPlan> plans = new ArrayList<>(generators.size());
AboveTerrainHosts aboveTerrainHosts = new AboveTerrainHosts(terrain, context);
PackRuntime runtime = PackRuntime.of(getEngine(), getData());
int attempts = 0;
for (int i = 0; i < generators.size(); i++) {
try {
DepositPlan plan = plan(generators.get(i), rng.nextParallelRNG(seed * (i + 1L)), context);
DepositPlan plan = plan(generators.get(i), rng.nextParallelRNG(seed * (i + 1L)), context, runtime);
if (plan.attempts() == 0 || footprintsMissTerrain(plan, highestSurface)
|| plan.generator().getPlacementScope() == IrisDepositPlacementScope.ABOVE_TERRAIN
&& !aboveTerrainHosts.present(plan.generator().getSurfaceClearance())) {
@@ -209,7 +211,7 @@ public class IrisDepositModifier extends EngineAssignedModifier<NativeBlockState
}
public void generate(IrisDepositGenerator k, MantleChunk chunk, Hunk<NativeBlockState> data, RNG rng, int cx, int cz, boolean safe, HeightMap he, ChunkContext context) {
DepositPlan plan = plan(k, rng, context);
DepositPlan plan = plan(k, rng, context, PackRuntime.of(getEngine(), getData()));
if (plan.attempts() == 0) {
return;
}
@@ -231,13 +233,13 @@ public class IrisDepositModifier extends EngineAssignedModifier<NativeBlockState
return lowest > (long) highestSurface - Math.max(0, generator.getSurfaceClearance());
}
private DepositPlan plan(IrisDepositGenerator generator, RNG rng, ChunkContext context) {
private DepositPlan plan(IrisDepositGenerator generator, RNG rng, ChunkContext context, PackRuntime runtime) {
if (generator.getSpawnChance() < rng.d()) {
return new DepositPlan(generator, rng.getSeed(), false, 0);
return new DepositPlan(generator, runtime, rng.getSeed(), false, 0);
}
boolean ore = generator.isOre(getData());
int attempts = rng.i(generator.getMinPerChunk(), generator.getMaxPerChunk() + 1);
return new DepositPlan(generator, rng.getSeed(), ore,
return new DepositPlan(generator, runtime, rng.getSeed(), ore,
attempts == 0 || surfaceBiomeMayMatch(generator, context) ? attempts : 0);
}
@@ -306,7 +308,7 @@ public class IrisDepositModifier extends EngineAssignedModifier<NativeBlockState
if (footprint != null && footprint.empty() && !scalable) {
return null;
}
IrisObject clump = footprint == null ? k.getClump(getEngine(), clumpRng, getData()) : null;
IrisObject clump = footprint == null ? k.getClump(plan.runtime(), clumpRng) : null;
int dim = footprint == null ? clump.getW() : footprint.width();
int min = dim / 2;
@@ -368,7 +370,7 @@ public class IrisDepositModifier extends EngineAssignedModifier<NativeBlockState
double sizeMultiplier = depositBiome.getOreDepositSizeMultiplier();
if (sizeMultiplier != 1D) {
IrisObject scaledClump = k.getClump(getEngine(), clumpRng, getData(), sizeMultiplier);
IrisObject scaledClump = k.getClump(plan.runtime(), clumpRng, sizeMultiplier);
int scaledDimension = scaledClump.getW();
x = clampDepositCenter(x, scaledDimension, 16);
if (clippedHeight) {
@@ -700,7 +702,7 @@ public class IrisDepositModifier extends EngineAssignedModifier<NativeBlockState
}
}
private record DepositPlan(IrisDepositGenerator generator, long seed, boolean ore, int attempts) {
private record DepositPlan(IrisDepositGenerator generator, PackRuntime runtime, long seed, boolean ore, int attempts) {
}
private static final class HostStates {
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.stage;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.integration.Identifier;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.DimensionStackLayout;
@@ -191,6 +192,7 @@ public final class IrisDimensionStackActuator extends EngineAssignedActuator<Nat
DimensionTerrainContext terrainContext = layer.terrainContext();
IrisDimension dimension = terrainContext.getDimension();
IrisData data = terrainContext.getData();
PackRuntime runtime = PackRuntime.of(getEngine(), data);
IrisBiome biome = layer.biome();
int bedrockDepth = dimension.isBedrock() ? 1 : 0;
int surfaceDepth = Math.max(0, layer.normalTerrainHeight() + 1 - bedrockDepth);
@@ -204,7 +206,7 @@ public final class IrisDimensionStackActuator extends EngineAssignedActuator<Nat
rng,
surfaceDepth,
layer.normalTerrainHeight(),
data,
runtime,
terrainContext.getSlopeStream()
);
int paletteSurfaceY = layer.normalTerrainHeight();
@@ -212,7 +214,7 @@ public final class IrisDimensionStackActuator extends EngineAssignedActuator<Nat
int terrainSpan = layer.terrainColumn() == null ? -1 : layer.terrainColumn().spanCount() - 1;
KList<NativeBlockState> seaBlocks = biome == null || fluidDepth == 0
? null
: biome.generateSeaLayers(worldX, worldZ, rng, fluidDepth, data);
: biome.generateSeaLayers(worldX, worldZ, rng, fluidDepth, runtime);
for (int y = layer.renderMaxY(); y >= layer.renderMinY(); y--) {
int sourceY = y - layer.localBaseY();
@@ -256,7 +258,7 @@ public final class IrisDimensionStackActuator extends EngineAssignedActuator<Nat
if (terrainSpan > 0 && depth >= 2 && ceilingDepth < 2) {
if (ceilingBlocks == null && biome != null) {
ceilingBlocks = biome.generateCeilingLayers(dimension, worldX, worldZ, rng,
2, ceilingY, data, null);
2, ceilingY, runtime, null);
}
writeBlock(output, metadata, localX, y, localZ,
ceilingBlocks != null && ceilingBlocks.hasIndex(ceilingDepth)
@@ -266,7 +268,7 @@ public final class IrisDimensionStackActuator extends EngineAssignedActuator<Nat
}
if (surfaceBlocks == null && biome != null) {
surfaceBlocks = biome.generateLayersWithSlope(dimension, worldX, worldZ, rng,
sourceSurfaceY + 1 - bedrockDepth, sourceSurfaceY, data,
sourceSurfaceY + 1 - bedrockDepth, sourceSurfaceY, runtime,
terrainContext.getSurfaceSlopeStream(sourceSurfaceY));
}
writeBlock(output, metadata, localX, y, localZ,
@@ -19,6 +19,7 @@
package art.arcane.iris.generation.stage;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.DimensionStackLayout;
import art.arcane.iris.generation.runtime.GenerationFailures;
@@ -64,14 +65,14 @@ public class IrisFloatingChildBiomeModifier extends EngineAssignedModifier<Nativ
private final RNG rng;
private final EngineDecorator seaSurfaceDecorator;
private static KList<NativeBlockState> generateBottomPaletteLayers(IrisFloatingChildBiomes entry, IrisDimension dimension, double wx, double wz, RNG random, int paletteDepth, IrisData data, IrisComplex complex) {
private static KList<NativeBlockState> generateBottomPaletteLayers(IrisFloatingChildBiomes entry, IrisDimension dimension, double wx, double wz, RNG random, int paletteDepth, PackRuntime runtime, IrisComplex complex) {
if (entry == null || entry.getBottomPaletteMode() != FloatingBottomPaletteMode.CUSTOM || entry.getBottomPalette() == null || entry.getBottomPalette().isEmpty()) {
return null;
}
return generatePaletteLayers(dimension, entry.getBottomPalette(), wx, wz, random.nextParallelRNG(0xB0770B), paletteDepth, data, complex);
return generatePaletteLayers(dimension, entry.getBottomPalette(), wx, wz, random.nextParallelRNG(0xB0770B), paletteDepth, runtime, complex);
}
private static KList<NativeBlockState> generatePaletteLayers(IrisDimension dimension, KList<IrisBiomePaletteLayer> layers, double wx, double wz, RNG random, int maxDepth, IrisData data, IrisComplex complex) {
private static KList<NativeBlockState> generatePaletteLayers(IrisDimension dimension, KList<IrisBiomePaletteLayer> layers, double wx, double wz, RNG random, int maxDepth, PackRuntime runtime, IrisComplex complex) {
KList<NativeBlockState> generated = new KList<>();
if (layers == null || layers.isEmpty() || maxDepth <= 0) {
return generated;
@@ -80,7 +81,7 @@ public class IrisFloatingChildBiomeModifier extends EngineAssignedModifier<Nativ
int generatorSeed = 7235;
for (int i = 0; i < layers.size(); i++) {
IrisBiomePaletteLayer layer = layers.get(i);
CNG heightGenerator = layer.getHeightGenerator(random.nextParallelRNG((generatorSeed++) * generatorSeed * generatorSeed * generatorSeed), data);
CNG heightGenerator = layer.getHeightGenerator(random.nextParallelRNG((generatorSeed++) * generatorSeed * generatorSeed * generatorSeed), runtime);
if (heightGenerator == null) {
continue;
}
@@ -101,7 +102,7 @@ public class IrisFloatingChildBiomeModifier extends EngineAssignedModifier<Nativ
}
try {
generated.add(layer.get(random.nextParallelRNG(i + j), (wx + j) / layer.getZoom(), j, (wz - j) / layer.getZoom(), data));
generated.add(layer.get(random.nextParallelRNG(i + j), (wx + j) / layer.getZoom(), j, (wz - j) / layer.getZoom(), runtime));
} catch (Throwable e) {
GenerationFailures.skipPlacement(e, "surface layer", "block", (int) wx, -1, (int) wz, "floating");
}
@@ -178,18 +179,18 @@ public class IrisFloatingChildBiomeModifier extends EngineAssignedModifier<Nativ
return block == null ? fallbackSolid : block;
}
private PaletteContext createPaletteContext(IrisBiome parent, IrisFloatingChildBiomes entry, IrisDimension dimension, int wx, int wz, int paletteDepth, int surfaceY, int baseY, IrisData data, IrisComplex complex) {
IrisBiome target = entry == null ? parent : entry.getRealBiome(parent, data);
private PaletteContext createPaletteContext(IrisBiome parent, IrisFloatingChildBiomes entry, IrisDimension dimension, int wx, int wz, int paletteDepth, int surfaceY, int baseY, PackRuntime runtime, IrisComplex complex) {
IrisBiome target = entry == null ? parent : entry.getRealBiome(parent, runtime.data());
RNG layerRng = paletteRng(rng, entry);
boolean physicalDepth = usesPhysicalDepth(target, entry);
int topPaletteDepth = physicalDepth ? Math.max(paletteDepth, surfaceY - baseY + 1) : paletteDepth;
KList<NativeBlockState> topBlocks = target == null ? null : target.generateLayers(dimension, wx, wz, layerRng, topPaletteDepth, surfaceY, data, complex);
KList<NativeBlockState> topBlocks = target == null ? null : target.generateLayers(dimension, wx, wz, layerRng, topPaletteDepth, surfaceY, runtime, complex);
if (topBlocks == null || topBlocks.isEmpty()) {
physicalDepth = usesPhysicalDepth(parent, entry);
topPaletteDepth = physicalDepth ? Math.max(paletteDepth, surfaceY - baseY + 1) : paletteDepth;
topBlocks = parent.generateLayers(dimension, wx, wz, layerRng, topPaletteDepth, surfaceY, data, complex);
topBlocks = parent.generateLayers(dimension, wx, wz, layerRng, topPaletteDepth, surfaceY, runtime, complex);
}
KList<NativeBlockState> bottomBlocks = generateBottomPaletteLayers(entry, dimension, wx, wz, layerRng, paletteDepth, data, complex);
KList<NativeBlockState> bottomBlocks = generateBottomPaletteLayers(entry, dimension, wx, wz, layerRng, paletteDepth, runtime, complex);
return new PaletteContext(topBlocks, bottomBlocks, B.getState("minecraft:stone"), surfaceY, physicalDepth);
}
@@ -230,11 +231,12 @@ public class IrisFloatingChildBiomeModifier extends EngineAssignedModifier<Nativ
PrecisionStopwatch p = PrecisionStopwatch.start();
int chunkHeight = output.getHeight();
IrisData data = getData();
PackRuntime runtime = PackRuntime.of(getEngine(), data);
IrisDimension dimension = getDimension();
IrisComplex complex = getComplex();
long baseSeed = getEngine().getSeedManager().getTerrain() ^ FLOATING_BASE_SEED_SALT;
FloatingIslandBoundarySampler boundarySampler = context.getFloatingIslandBoundarySampler();
FloatingIslandSample.clearChunkMemo();
FloatingIslandSample.clearChunkMemo(runtime);
for (int xf = 0; xf < 16; xf++) {
for (int zf = 0; zf < 16; zf++) {
@@ -244,7 +246,7 @@ public class IrisFloatingChildBiomeModifier extends EngineAssignedModifier<Nativ
if (parent == null || parent.getFloatingChildBiomes() == null || parent.getFloatingChildBiomes().isEmpty()) {
continue;
}
FloatingIslandSample sample = FloatingIslandSample.sampleMemoized(parent, wx, wz, chunkHeight, baseSeed, data, getEngine(), boundarySampler);
FloatingIslandSample sample = FloatingIslandSample.sampleMemoized(parent, wx, wz, chunkHeight, baseSeed, runtime, boundarySampler);
if (sample == null) {
continue;
}
@@ -265,7 +267,7 @@ public class IrisFloatingChildBiomeModifier extends EngineAssignedModifier<Nativ
IrisFloatingChildBiomes entry = sample.entryAt(k);
PaletteContext paletteContext = paletteContexts.get(entry);
if (paletteContext == null) {
paletteContext = createPaletteContext(parent, entry, dimension, wx, wz, paletteDepth, y, sample.islandBaseY, data, complex);
paletteContext = createPaletteContext(parent, entry, dimension, wx, wz, paletteDepth, y, sample.islandBaseY, runtime, complex);
paletteContexts.put(entry, paletteContext);
}
int depth = topDepthByEntry.getOrDefault(entry, 0);
@@ -327,6 +329,7 @@ public class IrisFloatingChildBiomeModifier extends EngineAssignedModifier<Nativ
public void decorateColumns(int x, int z, Hunk<NativeBlockState> output, boolean multicore, ChunkContext context) {
int chunkHeight = output.getHeight();
IrisData data = getData();
PackRuntime runtime = PackRuntime.of(getEngine(), data);
IrisComplex complex = getComplex();
long baseSeed = getEngine().getSeedManager().getTerrain() ^ FLOATING_BASE_SEED_SALT;
FloatingIslandBoundarySampler boundarySampler = context.getFloatingIslandBoundarySampler();
@@ -342,7 +345,7 @@ public class IrisFloatingChildBiomeModifier extends EngineAssignedModifier<Nativ
if (parent == null || parent.getFloatingChildBiomes() == null || parent.getFloatingChildBiomes().isEmpty()) {
continue;
}
FloatingIslandSample sample = FloatingIslandSample.sampleMemoized(parent, wx, wz, chunkHeight, baseSeed, data, getEngine(), boundarySampler);
FloatingIslandSample sample = FloatingIslandSample.sampleMemoized(parent, wx, wz, chunkHeight, baseSeed, runtime, boundarySampler);
if (sample == null) {
continue;
}
@@ -212,7 +212,7 @@ public class IrisPostModifier extends EngineAssignedModifier<NativeBlockState> {
int max = Math.abs(Math.max(h - ha, Math.max(h - hb, Math.max(h - hc, h - hd))));
for (int i = h; i > h - max; i--) {
NativeBlockState d = biome.getWall().get(rng, x + i, i + h, z + i, getData());
NativeBlockState d = biome.getWall().get(rng, x + i, i + h, z + i, getComplex().getPackRuntime());
if (d != null) {
if (isAirOrWater(x, i, z, originX, originZ, currentData)) {
@@ -241,7 +241,7 @@ public class IrisPostModifier extends EngineAssignedModifier<NativeBlockState> {
//@done
{
IrisSlopeClip sc = biome.getSlab().getSlopeCondition();
NativeBlockState d = sc.isValid(getComplex().getSlopeStream().get(x, z)) ? biome.getSlab().get(rng, x, h, z, getData()) : null;
NativeBlockState d = sc.isValid(getComplex().getSlopeStream().get(x, z)) ? biome.getSlab().get(rng, x, h, z, getComplex().getPackRuntime()) : null;
if (d != null) {
boolean cancel = B.isAir(d);
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.stage;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.EngineAssignedActuator;
import art.arcane.iris.pack.loading.IrisData;
@@ -30,6 +31,7 @@ import art.arcane.iris.generation.hydrology.config.IrisHydrologyMaterials;
import art.arcane.iris.generation.hydrology.raster.WaterRole;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.decoration.IrisOreBands;
import art.arcane.iris.generation.decoration.OreBandsRuntime;
import art.arcane.iris.generation.terrain.IrisMaterialPalette;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.iris.generation.terrain.Terrain3DColumn;
@@ -114,13 +116,13 @@ public class IrisTerrainNormalActuator extends EngineAssignedActuator<NativeBloc
int x,
int y,
int z,
IrisData data
PackRuntime runtime
) {
if (palette == null || depth >= paintDepth) {
return layerBlock;
}
NativeBlockState painted = palette.get(rng, x, y, z, data);
NativeBlockState painted = palette.get(rng, x, y, z, runtime);
return painted == null ? layerBlock : painted;
}
@@ -143,7 +145,7 @@ public class IrisTerrainNormalActuator extends EngineAssignedActuator<NativeBloc
private final int chunkHeight;
private final IrisDimension dimension;
private final IrisData data;
private final Engine oreEngine;
private final PackRuntime runtime;
private final IrisComplex complex;
private final ProceduralStream<Double> waterHeadStream;
private final ProceduralStream<WaterRole> waterRoleStream;
@@ -155,14 +157,14 @@ public class IrisTerrainNormalActuator extends EngineAssignedActuator<NativeBloc
private final ChunkedDataCache<NativeBlockState> rockCache;
private final ChunkedDataCache<NativeBlockState> fluidCache;
private final UpperDimensionContext upperContext;
private final IrisOreBands dimensionSurfaceOres;
private final IrisOreBands dimensionUndergroundOres;
private final OreBandsRuntime dimensionSurfaceOres;
private final OreBandsRuntime dimensionUndergroundOres;
private final NativeBlockState air;
private final NativeBlockState bedrock;
private IrisOreBands biomeSurfaceOres;
private IrisOreBands regionSurfaceOres;
private IrisOreBands biomeUndergroundOres;
private IrisOreBands regionUndergroundOres;
private OreBandsRuntime biomeSurfaceOres;
private OreBandsRuntime regionSurfaceOres;
private OreBandsRuntime biomeUndergroundOres;
private OreBandsRuntime regionUndergroundOres;
private int surfaceOreTop;
private int surfaceOreFloor;
private int undergroundOreTop;
@@ -181,7 +183,7 @@ public class IrisTerrainNormalActuator extends EngineAssignedActuator<NativeBloc
chunkHeight = h.getHeight();
dimension = getDimension();
data = getData();
oreEngine = data == null ? null : data.getEngine();
runtime = PackRuntime.of(getEngine(), data);
complex = getComplex();
waterHeadStream = complex.getWaterHeadStream();
waterRoleStream = complex.getWaterRoleStream();
@@ -193,8 +195,8 @@ public class IrisTerrainNormalActuator extends EngineAssignedActuator<NativeBloc
rockCache = context.getRock();
fluidCache = context.getFluid();
upperContext = getEngine().getUpperContext();
dimensionSurfaceOres = hideOres ? IrisOreBands.EMPTY : dimension.getSurfaceOreBands();
dimensionUndergroundOres = hideOres ? IrisOreBands.EMPTY : dimension.getUndergroundOreBands();
dimensionSurfaceOres = ores(hideOres ? IrisOreBands.EMPTY : dimension.getSurfaceOreBands(), null);
dimensionUndergroundOres = ores(hideOres ? IrisOreBands.EMPTY : dimension.getUndergroundOreBands(), null);
air = AIR.get();
bedrock = BEDROCK.get();
}
@@ -234,10 +236,10 @@ public class IrisTerrainNormalActuator extends EngineAssignedActuator<NativeBloc
: fluidCache.get(xf, zf);
NativeBlockState rock = rockCache.get(xf, zf);
NativeBlockState mappedSurfaceBlock = complex.getImageMapRuntime().sampleSurfaceBlock(realX, realZ);
biomeSurfaceOres = hideOres ? IrisOreBands.EMPTY : biome.getSurfaceOreBands();
regionSurfaceOres = hideOres ? IrisOreBands.EMPTY : region.getSurfaceOreBands();
biomeUndergroundOres = hideOres ? IrisOreBands.EMPTY : biome.getUndergroundOreBands();
regionUndergroundOres = hideOres ? IrisOreBands.EMPTY : region.getUndergroundOreBands();
biomeSurfaceOres = ores(hideOres ? IrisOreBands.EMPTY : biome.getSurfaceOreBands(), biomeSurfaceOres);
regionSurfaceOres = ores(hideOres ? IrisOreBands.EMPTY : region.getSurfaceOreBands(), regionSurfaceOres);
biomeUndergroundOres = ores(hideOres ? IrisOreBands.EMPTY : biome.getUndergroundOreBands(), biomeUndergroundOres);
regionUndergroundOres = ores(hideOres ? IrisOreBands.EMPTY : region.getUndergroundOreBands(), regionUndergroundOres);
surfaceOreTop = oreTop(biomeSurfaceOres, regionSurfaceOres, dimensionSurfaceOres);
surfaceOreFloor = oreFloor(biomeSurfaceOres, regionSurfaceOres, dimensionSurfaceOres);
undergroundOreTop = oreTop(biomeUndergroundOres, regionUndergroundOres, dimensionUndergroundOres);
@@ -278,7 +280,7 @@ public class IrisTerrainNormalActuator extends EngineAssignedActuator<NativeBloc
if (i > he && i <= hf) {
int fdepth = hf - i;
if (seaFloor && fblocks == null) {
fblocks = biome.generateSeaLayers(realX, realZ, rng, role == WaterRole.INLET ? INLET_SEA_LAYERS : hf - he, data);
fblocks = biome.generateSeaLayers(realX, realZ, rng, role == WaterRole.INLET ? INLET_SEA_LAYERS : hf - he, runtime);
}
put(i, HydrologyFluidLayerSelector.select(
fblocks,
@@ -297,7 +299,7 @@ public class IrisTerrainNormalActuator extends EngineAssignedActuator<NativeBloc
}
if (blocks == null) {
blocks = biome.generateLayers(dimension, realX, realZ, rng,
layerSurfaceY + 1 - bedrockFloor, layerSurfaceY, data, complex);
layerSurfaceY + 1 - bedrockFloor, layerSurfaceY, runtime, complex);
}
int deepFloor = Math.max(bedrockFloor, layerCeilingY > 0 ? layerCeilingY + 2 : 0);
@@ -310,7 +312,7 @@ public class IrisTerrainNormalActuator extends EngineAssignedActuator<NativeBloc
if (layerCeilingY > 0 && depth >= 2 && i - layerCeilingY < 2) {
if (ceilingBlocks == null) {
ceilingBlocks = biome.generateCeilingLayers(dimension, realX, realZ, rng,
2, layerCeilingY, data, complex);
2, layerCeilingY, runtime, complex);
}
int ceilingDepth = i - layerCeilingY;
put(i, ceilingBlocks.hasIndex(ceilingDepth)
@@ -320,7 +322,7 @@ public class IrisTerrainNormalActuator extends EngineAssignedActuator<NativeBloc
NativeBlockState layerBlock = paintWaterMaterial(
blocks.hasIndex(depth) ? blocks.get(depth) : null,
rolePalette, paintDepth, depth, rng, realX, i, realZ, data);
rolePalette, paintDepth, depth, rng, realX, i, realZ, runtime);
if (submerged && layerSurfaceY == he) {
layerBlock = submergedSoil(layerBlock);
}
@@ -403,7 +405,14 @@ public class IrisTerrainNormalActuator extends EngineAssignedActuator<NativeBloc
runState = null;
}
private static int oreTop(IrisOreBands first, IrisOreBands second, IrisOreBands third) {
private OreBandsRuntime ores(IrisOreBands bands, OreBandsRuntime previousColumn) {
if (previousColumn != null && previousColumn.bands() == bands) {
return previousColumn;
}
return runtime.oreBands(bands, rng.getSeed());
}
private static int oreTop(OreBandsRuntime first, OreBandsRuntime second, OreBandsRuntime third) {
int top = Integer.MIN_VALUE;
if (first.hasOres()) {
top = Math.max(top, first.highestY());
@@ -417,7 +426,7 @@ public class IrisTerrainNormalActuator extends EngineAssignedActuator<NativeBloc
return top;
}
private static int oreFloor(IrisOreBands first, IrisOreBands second, IrisOreBands third) {
private static int oreFloor(OreBandsRuntime first, OreBandsRuntime second, OreBandsRuntime third) {
int floor = Integer.MAX_VALUE;
if (first.hasOres()) {
floor = Math.min(floor, first.lowestY());
@@ -434,13 +443,13 @@ public class IrisTerrainNormalActuator extends EngineAssignedActuator<NativeBloc
private NativeBlockState surfaceOre(int realX, int y, int realZ) {
NativeBlockState ore = null;
if (biomeSurfaceOres.contains(y)) {
ore = biomeSurfaceOres.generate(realX, y, realZ, rng, data, oreEngine);
ore = biomeSurfaceOres.generate(realX, y, realZ, rng);
}
if (ore == null && regionSurfaceOres.contains(y)) {
ore = regionSurfaceOres.generate(realX, y, realZ, rng, data, oreEngine);
ore = regionSurfaceOres.generate(realX, y, realZ, rng);
}
if (ore == null && dimensionSurfaceOres.contains(y)) {
ore = dimensionSurfaceOres.generate(realX, y, realZ, rng, data, oreEngine);
ore = dimensionSurfaceOres.generate(realX, y, realZ, rng);
}
return ore;
}
@@ -448,13 +457,13 @@ public class IrisTerrainNormalActuator extends EngineAssignedActuator<NativeBloc
private NativeBlockState undergroundOre(int realX, int y, int realZ) {
NativeBlockState ore = null;
if (biomeUndergroundOres.contains(y)) {
ore = biomeUndergroundOres.generate(realX, y, realZ, rng, data, oreEngine);
ore = biomeUndergroundOres.generate(realX, y, realZ, rng);
}
if (ore == null && regionUndergroundOres.contains(y)) {
ore = regionUndergroundOres.generate(realX, y, realZ, rng, data, oreEngine);
ore = regionUndergroundOres.generate(realX, y, realZ, rng);
}
if (ore == null && dimensionUndergroundOres.contains(y)) {
ore = dimensionUndergroundOres.generate(realX, y, realZ, rng, data, oreEngine);
ore = dimensionUndergroundOres.generate(realX, y, realZ, rng);
}
return ore;
}
@@ -495,7 +504,7 @@ public class IrisTerrainNormalActuator extends EngineAssignedActuator<NativeBloc
if (upperBlocks == null && upperBiome != null) {
upperBlocks = upperBiome.generateLayersWithSlope(upperContext.getDimension(),
realX, realZ, rng, sourceSurfaceY + 1 - (bedrockEnabled ? 1 : 0), sourceSurfaceY,
upperContext.getData(), upperContext.getSurfaceSlopeStream(sourceSurfaceY));
runtime.scopeFor(upperContext.getData()), upperContext.getSurfaceSlopeStream(sourceSurfaceY));
}
if (upperBlocks != null && upperBlocks.hasIndex(depthFromFace)) {
put(y, upperBlocks.get(depthFromFace));
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.subterrain;
import art.arcane.iris.generation.runtime.ThreadSlots;
import java.util.Objects;
public final class SubterrainPlan {
@@ -12,7 +13,7 @@ public final class SubterrainPlan {
private final SubterrainBounds bounds;
private final double shapePhase;
private final long shapeSeed;
private final ThreadLocal<ColumnCache> columnCache = ThreadLocal.withInitial(ColumnCache::new);
private final ThreadSlots<ColumnCache> columnCache = new ThreadSlots<>(ColumnCache::new);
SubterrainPlan(Options options) {
definition = Objects.requireNonNull(options.definition());
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.subterrain;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.decoration.IrisDecorationPart;
import art.arcane.iris.generation.decoration.IrisDecorator;
@@ -22,19 +23,21 @@ public final class SubterrainSurfaceMaterials {
private final IrisDimension dimension;
private final IrisComplex complex;
private final IrisData data;
private final PackRuntime runtime;
private final RNG random;
private final int minimumY;
private final Map<String, IrisBiome> biomes = new HashMap<>();
private final Map<String, Set<String>> floorSupports = new HashMap<>();
public SubterrainSurfaceMaterials(SubterrainPlanner planner, List<SubterrainPlan> plans,
IrisDimension dimension, IrisComplex complex, IrisData data,
IrisDimension dimension, IrisComplex complex, PackRuntime runtime,
RNG random, int minimumY) {
this.planner = planner;
this.plans = plans;
this.dimension = dimension;
this.complex = complex;
this.data = data;
this.runtime = runtime;
this.data = runtime.data();
this.random = random;
this.minimumY = minimumY;
}
@@ -54,11 +57,11 @@ public final class SubterrainSurfaceMaterials {
}
NativeBlockState candidate;
if (surface == Surface.WALL) {
candidate = biome.getWall().get(random, x, worldY - minimumY, z, data);
candidate = biome.getWall().get(random, x, worldY - minimumY, z, runtime);
} else {
KList<NativeBlockState> layers = surface == Surface.FLOOR
? biome.generateLayers(dimension, x, z, random, 1, worldY + 1 - minimumY, data, complex)
: biome.generateCeilingLayers(dimension, x, z, random, 1, worldY - 1 - minimumY, data, complex);
? biome.generateLayers(dimension, x, z, random, 1, worldY + 1 - minimumY, runtime, complex)
: biome.generateCeilingLayers(dimension, x, z, random, 1, worldY - 1 - minimumY, runtime, complex);
candidate = layers.isEmpty() ? null : layers.getFirst();
}
return SubterrainRasterizer.isRetainedSolid(candidate) ? candidate : fallback;
@@ -1,6 +1,6 @@
package art.arcane.iris.generation.terrain;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG;
@@ -10,12 +10,12 @@ public final class ContinentGenerator {
private ContinentGenerator() {
}
public static CNG create(IrisDimension dimension, RNG parentSeedSource, IrisData packData) {
return createScaledContinentalStyleGenerator(dimension, deriveContinentSeed(parentSeedSource), packData);
public static CNG create(IrisDimension dimension, RNG parentSeedSource, PackRuntime runtime) {
return createScaledContinentalStyleGenerator(dimension, deriveContinentSeed(parentSeedSource), runtime);
}
private static CNG createScaledContinentalStyleGenerator(IrisDimension dimension, RNG continentSeed, IrisData packData) {
return dimension.getContinentalStyle().createScaledGenerator(continentSeed, packData, inverseContinentZoom(dimension));
private static CNG createScaledContinentalStyleGenerator(IrisDimension dimension, RNG continentSeed, PackRuntime runtime) {
return dimension.getContinentalStyle().createScaledGenerator(continentSeed, runtime, inverseContinentZoom(dimension));
}
static RNG deriveContinentSeed(RNG parentSeedSource) {
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.terrain;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.world.entity.IrisSpawnGroup;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.biome.IrisBiomeCustom;
@@ -68,7 +69,6 @@ import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.IDataFixer;
import art.arcane.iris.pack.datapack.IDataFixer.Dimension;
import art.arcane.volmlib.util.cache.AtomicCache;
import art.arcane.iris.generation.cache.LazyBoundedCache;
import art.arcane.iris.world.history.GenerationRegistryContractFactory;
import art.arcane.iris.pack.schema.annotation.ArrayType;
import art.arcane.volmlib.util.documentation.Description;
@@ -88,7 +88,6 @@ import art.arcane.volmlib.util.json.JSONArray;
import art.arcane.volmlib.util.json.JSONObject;
import art.arcane.volmlib.util.mantle.flag.MantleFlag;
import art.arcane.volmlib.util.mantle.flag.ReservedFlag;
import art.arcane.volmlib.util.math.Position2;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG;
import lombok.Data;
@@ -133,21 +132,11 @@ import java.util.regex.Pattern;
public class IrisDimension extends IrisRegistrant {
private static final Pattern RESOURCE_KEY_PATTERN = Pattern.compile("[a-z0-9_.-]+:[a-z0-9/._-]+");
private final transient AtomicCache<Position2> parallaxSize = new AtomicCache<>();
private final transient AtomicCache<IrisStaticObjectLayer> staticObjectLayer = new AtomicCache<>();
private final transient AtomicCache<CNG> rockLayerGenerator = new AtomicCache<>();
private final transient AtomicCache<CNG> fluidLayerGenerator = new AtomicCache<>();
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient LazyBoundedCache<Long, CNG> coordinateFractures = new LazyBoundedCache<>(8);
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private transient volatile CachedCoordinateFracture recentCoordinateFracture;
private final transient AtomicCache<Double> sinr = new AtomicCache<>();
private final transient AtomicCache<Double> cosr = new AtomicCache<>();
private final transient AtomicCache<Double> rad = new AtomicCache<>();
private final transient AtomicCache<Boolean> undergroundSpawnTables = new AtomicCache<>();
private final transient AtomicCache<Boolean> featuresUsed = new AtomicCache<>();
private final transient AtomicCache<Map<String, IrisDimensionCarvingEntry>> carvingEntryIndex = new AtomicCache<>();
private final transient AtomicCache<KList<IrisOreGenerator>> surfaceOreCache = new AtomicCache<>();
private final transient AtomicCache<KList<IrisOreGenerator>> undergroundOreCache = new AtomicCache<>();
@@ -464,17 +453,17 @@ public class IrisDimension extends IrisRegistrant {
carvingEntryIndex.reset();
}
public NativeBlockState generateOres(int x, int y, int z, RNG rng, IrisData data, boolean surface) {
public NativeBlockState generateOres(int x, int y, int z, RNG rng, PackRuntime runtime, boolean surface) {
KList<IrisOreGenerator> localOres = surface ? getSurfaceOres() : getUndergroundOres();
return generateOres(localOres, x, y, z, rng, data);
return generateOres(localOres, x, y, z, rng, runtime);
}
public NativeBlockState generateSurfaceOres(int x, int y, int z, RNG rng, IrisData data) {
return generateOres(getSurfaceOres(), x, y, z, rng, data);
public NativeBlockState generateSurfaceOres(int x, int y, int z, RNG rng, PackRuntime runtime) {
return generateOres(getSurfaceOres(), x, y, z, rng, runtime);
}
public NativeBlockState generateUndergroundOres(int x, int y, int z, RNG rng, IrisData data) {
return generateOres(getUndergroundOres(), x, y, z, rng, data);
public NativeBlockState generateUndergroundOres(int x, int y, int z, RNG rng, PackRuntime runtime) {
return generateOres(getUndergroundOres(), x, y, z, rng, runtime);
}
public boolean hasSurfaceOres() {
@@ -485,7 +474,7 @@ public class IrisDimension extends IrisRegistrant {
return !getUndergroundOres().isEmpty();
}
private NativeBlockState generateOres(KList<IrisOreGenerator> localOres, int x, int y, int z, RNG rng, IrisData data) {
private NativeBlockState generateOres(KList<IrisOreGenerator> localOres, int x, int y, int z, RNG rng, PackRuntime runtime) {
if (localOres.isEmpty()) {
return null;
}
@@ -493,7 +482,7 @@ public class IrisDimension extends IrisRegistrant {
int oreCount = localOres.size();
for (int oreIndex = 0; oreIndex < oreCount; oreIndex++) {
IrisOreGenerator oreGenerator = localOres.get(oreIndex);
NativeBlockState ore = oreGenerator.generate(x, y, z, rng, data);
NativeBlockState ore = oreGenerator.generate(x, y, z, rng, runtime);
if (ore != null) {
return ore;
}
@@ -554,18 +543,6 @@ public class IrisDimension extends IrisRegistrant {
return fluidHeight - (int) dimensionHeight.getMin();
}
public CNG getCoordFracture(RNG rng, int signature) {
long seed = rng.getSeed() + signature;
CachedCoordinateFracture recent = recentCoordinateFracture;
if (recent != null && recent.seed == seed) {
return recent.generator;
}
CNG generator = coordinateFractures.computeIfAbsent(seed, ignored ->
CNG.signature(new RNG(seed)).scale(0.012 / coordFractureZoom));
recentCoordinateFracture = new CachedCoordinateFracture(seed, generator);
return generator;
}
public double getDimensionAngle() {
return rad.aquire(() -> Math.toRadians(dimensionAngleDeg));
}
@@ -1400,7 +1377,4 @@ public class IrisDimension extends IrisRegistrant {
IO.writeAll(dimTypeVanilla, json);
}
}
private record CachedCoordinateFracture(long seed, CNG generator) {
}
}
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.terrain;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.NoiseStyle;
@@ -21,8 +22,6 @@ import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Snippet("dimension-carving-entry")
@Accessors(chain = true)
@@ -34,7 +33,6 @@ public class IrisDimensionCarvingEntry {
private static final int CHILDREN_SEED_SALT = 2137;
private static final double MINIMUM_CHILD_SHRINK_FACTOR = 0.0001D;
private final transient AtomicCache<IrisBiome> realBiome = new AtomicCache<>(true);
private final transient Map<Long, CNG> childGenerators = new ConcurrentHashMap<>();
@Description("Stable id for this carving entry")
private String id = "";
@@ -82,12 +80,12 @@ public class IrisDimensionCarvingEntry {
});
}
public CNG getChildrenGenerator(long seed, IrisData data) {
return childGenerators.computeIfAbsent(deriveChildrenGeneratorSeed(seed), key -> createChildrenGenerator(key, data));
public CNG getChildrenGenerator(long seed, PackRuntime runtime) {
return runtime.carvingChildGenerator(this, deriveChildrenGeneratorSeed(seed));
}
private CNG createChildrenGenerator(long childrenGeneratorSeed, IrisData data) {
return getChildStyle().createScaledGenerator(deriveChildStyleSeed(childrenGeneratorSeed), data, childShrinkFactor());
public CNG createChildrenGenerator(long childrenGeneratorSeed, PackRuntime runtime) {
return getChildStyle().createScaledGenerator(deriveChildStyleSeed(childrenGeneratorSeed), runtime, childShrinkFactor());
}
long deriveChildrenGeneratorSeed(long worldSeed) {
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.terrain;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.pack.value.IrisRange;
@@ -22,8 +23,6 @@ import java.util.Map;
public final class IrisDimensionCarvingResolver {
private static final int MAX_CHILD_DEPTH = 32;
private static final long CHILD_SEED_SALT = 0x9E3779B97F4A7C15L;
private static final ThreadLocal<WeakReference<State>> THREAD_STATE =
ThreadLocal.withInitial(() -> new WeakReference<>(null));
private IrisDimensionCarvingResolver() {
@@ -34,7 +33,7 @@ public final class IrisDimensionCarvingResolver {
}
public static IrisBiome resolveBiome(Engine engine, int worldX, int worldY, int worldZ, State state) {
State resolvedState = state == null ? threadState() : state;
State resolvedState = state == null ? threadState(engine) : state;
IrisData data = resolvedState.bind(engine);
IrisDimensionCarvingEntry root = resolveBoundRootEntry(engine, worldY, data, resolvedState);
if (root == null) {
@@ -45,21 +44,21 @@ public final class IrisDimensionCarvingResolver {
}
public static IrisDimensionCarvingEntry resolveRootEntry(Engine engine, int worldY) {
return resolveRootEntry(engine, worldY, threadState());
return resolveRootEntry(engine, worldY, threadState(engine));
}
public static IrisDimensionCarvingEntry resolveRootEntry(Engine engine, int worldY, State state) {
State resolvedState = state == null ? threadState() : state;
State resolvedState = state == null ? threadState(engine) : state;
IrisData data = resolvedState.bind(engine);
return resolveBoundRootEntry(engine, worldY, data, resolvedState);
}
public static IrisDimensionCarvingEntry resolveFromRoot(Engine engine, IrisDimensionCarvingEntry rootEntry, int worldX, int worldY, int worldZ) {
return resolveFromRoot(engine, rootEntry, worldX, worldY, worldZ, threadState());
return resolveFromRoot(engine, rootEntry, worldX, worldY, worldZ, threadState(engine));
}
public static IrisDimensionCarvingEntry resolveFromRoot(Engine engine, IrisDimensionCarvingEntry rootEntry, int worldX, int worldY, int worldZ, State state) {
State resolvedState = state == null ? threadState() : state;
State resolvedState = state == null ? threadState(engine) : state;
IrisData data = resolvedState.bind(engine);
return resolveBoundFromRoot(engine, rootEntry, worldX, worldY, worldZ, data, resolvedState);
}
@@ -237,7 +236,7 @@ public final class IrisDimensionCarvingResolver {
}
long seed = resolveChildSeed(engine, state);
CNG childGenerator = parent.getChildrenGenerator(seed, data);
CNG childGenerator = parent.getChildrenGenerator(seed, PackRuntime.of(engine, data));
double sample = childGenerator.noiseFast2D(worldX, worldZ);
CarvingChoice selected = selectionPlan.select(sample);
if (selected == null || selected.entry == null) {
@@ -313,15 +312,10 @@ public final class IrisDimensionCarvingResolver {
return state.childSeed;
}
private static State threadState() {
WeakReference<State> reference = THREAD_STATE.get();
State state = reference.get();
if (state != null) {
return state;
}
State replacement = new State();
THREAD_STATE.set(new WeakReference<>(replacement));
return replacement;
/** The calling thread's resolver state for this engine; engines without a pack runtime resolve unmemoized. */
public static State threadState(Engine engine) {
PackRuntime runtime = engine.getPackRuntime();
return runtime == null ? new State() : runtime.carvingResolverState();
}
public static final class Snapshot {
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.terrain;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.volmlib.nativelib.terrain.structure.StructurePalette;
import art.arcane.iris.generation.block.IrisBlockData;
@@ -25,11 +26,8 @@ import art.arcane.iris.generation.block.TileData;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.NoiseStyle;
import art.arcane.iris.generation.runtime.EngineRef;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.volmlib.util.cache.AtomicCache;
import art.arcane.iris.generation.cache.LazyBoundedCache;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.pack.schema.annotation.ArrayType;
import art.arcane.volmlib.util.documentation.Description;
import art.arcane.iris.pack.schema.annotation.MinNumber;
@@ -48,7 +46,6 @@ import lombok.Setter;
import lombok.experimental.Accessors;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
@Snippet("palette")
@Accessors(chain = true)
@@ -57,19 +54,11 @@ import java.util.concurrent.atomic.AtomicReference;
@Description("A palette of materials")
@Data
public class IrisMaterialPalette implements StructurePalette {
private static final int LAYER_GENERATOR_CACHE_SIZE = 32;
private static final int LAYER_GENERATOR_SALT = -23_498_896;
private final transient AtomicCache<KList<NativeBlockState>> blockData = new AtomicCache<>();
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient LazyBoundedCache<LayerGeneratorKey, CNG> layerGenerators =
new LazyBoundedCache<>(LAYER_GENERATOR_CACHE_SIZE);
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient AtomicReference<CachedLayerGenerator> recentLayerGenerator = new AtomicReference<>();
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient IrisBlockData fallback = new IrisBlockData("STONE");
@Description("The style of noise")
private IrisGeneratorStyle style = NoiseStyle.STATIC.style();
@@ -85,8 +74,8 @@ public class IrisMaterialPalette implements StructurePalette {
return palette != null && palette.size() == 1 && palette.get(0) == fallback;
}
public NativeBlockState get(RNG rng, double x, double y, double z, IrisData rdata) {
KList<NativeBlockState> localBlockData = getBlockData(rdata);
public NativeBlockState get(RNG rng, double x, double y, double z, PackRuntime runtime) {
KList<NativeBlockState> localBlockData = getBlockData(runtime.data());
int blockDataSize = localBlockData.size();
if (blockDataSize == 0) {
return null;
@@ -99,7 +88,7 @@ public class IrisMaterialPalette implements StructurePalette {
double scaledX = x / zoom;
double scaledY = y / zoom;
double scaledZ = z / zoom;
return getLayerGenerator(rng, rdata).fit(localBlockData, scaledX, scaledY, scaledZ);
return getLayerGenerator(rng, runtime).fit(localBlockData, scaledX, scaledY, scaledZ);
}
public Optional<TileData> getTile(RNG rng, double x, double y, double z, IrisData rdata) {
@@ -110,22 +99,13 @@ public class IrisMaterialPalette implements StructurePalette {
return tile != null ? Optional.of(tile) : Optional.empty();
}
public CNG getLayerGenerator(RNG rng, IrisData rdata) {
Engine engine = rdata == null ? null : rdata.getEngine();
int generatorSignature = LAYER_GENERATOR_SALT + getBlockData(rdata).size();
long generatorSeed = rng.getSeed() + generatorSignature;
CachedLayerGenerator recent = recentLayerGenerator.get();
if (recent != null && recent.key.matches(rdata, engine, generatorSeed)) {
return recent.generator;
}
public CNG getLayerGenerator(RNG rng, PackRuntime runtime) {
int generatorSignature = LAYER_GENERATOR_SALT + getBlockData(runtime.data()).size();
return runtime.materialPaletteGenerator(this, rng.getSeed() + generatorSignature);
}
LayerGeneratorKey key = new LayerGeneratorKey(rdata, engine, generatorSeed);
CNG generator = layerGenerators.computeIfAbsent(key,
ignored -> style.create(new RNG(generatorSeed), rdata, engine));
if (generator != null) {
recentLayerGenerator.set(new CachedLayerGenerator(key, generator));
}
return generator;
public CNG createLayerGenerator(long seed, PackRuntime runtime) {
return style.createNoCache(new RNG(seed), runtime);
}
public IrisMaterialPalette qclear() {
@@ -166,49 +146,4 @@ public class IrisMaterialPalette implements StructurePalette {
palette.clear();
return this;
}
private static final class LayerGeneratorKey {
private final IrisData data;
private final EngineRef engine;
private final long seed;
private LayerGeneratorKey(IrisData data, Engine engine, long seed) {
this.data = data;
this.engine = EngineRef.of(engine);
this.seed = seed;
}
private boolean matches(IrisData data, Engine engine, long seed) {
return this.data == data && this.engine.refersTo(engine) && this.seed == seed;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (!(object instanceof LayerGeneratorKey other)) {
return false;
}
return data == other.data && engine.equals(other.engine) && seed == other.seed;
}
@Override
public int hashCode() {
int result = System.identityHashCode(data);
result = 31 * result + engine.hashCode();
result = 31 * result + Long.hashCode(seed);
return result;
}
}
private static final class CachedLayerGenerator {
private final LayerGeneratorKey key;
private final CNG generator;
private CachedLayerGenerator(LayerGeneratorKey key, CNG generator) {
this.key = key;
this.generator = generator;
}
}
}
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.terrain;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.cave.IrisCaveProfile;
import art.arcane.iris.generation.decoration.IrisDepositGenerator;
@@ -176,17 +177,17 @@ public class IrisRegion extends IrisRegistrant implements Rarity {
@ArrayType(type = IrisOreGenerator.class, min = 1)
private KList<IrisOreGenerator> ores = new KList<>();
public NativeBlockState generateOres(int x, int y, int z, RNG rng, IrisData data, boolean surface) {
public NativeBlockState generateOres(int x, int y, int z, RNG rng, PackRuntime runtime, boolean surface) {
KList<IrisOreGenerator> localOres = surface ? getSurfaceOres() : getUndergroundOres();
return generateOres(localOres, x, y, z, rng, data);
return generateOres(localOres, x, y, z, rng, runtime);
}
public NativeBlockState generateSurfaceOres(int x, int y, int z, RNG rng, IrisData data) {
return generateOres(getSurfaceOres(), x, y, z, rng, data);
public NativeBlockState generateSurfaceOres(int x, int y, int z, RNG rng, PackRuntime runtime) {
return generateOres(getSurfaceOres(), x, y, z, rng, runtime);
}
public NativeBlockState generateUndergroundOres(int x, int y, int z, RNG rng, IrisData data) {
return generateOres(getUndergroundOres(), x, y, z, rng, data);
public NativeBlockState generateUndergroundOres(int x, int y, int z, RNG rng, PackRuntime runtime) {
return generateOres(getUndergroundOres(), x, y, z, rng, runtime);
}
public boolean hasSurfaceOres() {
@@ -197,7 +198,7 @@ public class IrisRegion extends IrisRegistrant implements Rarity {
return !getUndergroundOres().isEmpty();
}
private NativeBlockState generateOres(KList<IrisOreGenerator> localOres, int x, int y, int z, RNG rng, IrisData data) {
private NativeBlockState generateOres(KList<IrisOreGenerator> localOres, int x, int y, int z, RNG rng, PackRuntime runtime) {
if (localOres.isEmpty()) {
return null;
}
@@ -205,7 +206,7 @@ public class IrisRegion extends IrisRegistrant implements Rarity {
int oreCount = localOres.size();
for (int oreIndex = 0; oreIndex < oreCount; oreIndex++) {
IrisOreGenerator oreGenerator = localOres.get(oreIndex);
NativeBlockState ore = oreGenerator.generate(x, y, z, rng, data);
NativeBlockState ore = oreGenerator.generate(x, y, z, rng, runtime);
if (ore != null) {
return ore;
}
@@ -53,7 +53,7 @@ public final class RegionSelection {
}
}
return select(new Options(dimension, data,
dimension.getRegionStyle().create(new RNG(snapshot.complexSeed()).nextParallelRNG(883), data)
dimension.getRegionStyle().create(new RNG(snapshot.complexSeed()).nextParallelRNG(883), data.standalonePackRuntime())
.stream().zoom(dimension.getRegionZoom()),
IrisImageMapRuntime.compile(data, dimension, dimension.getMinHeight()), focused));
}
@@ -1,7 +1,8 @@
package art.arcane.iris.generation.terrain;
import art.arcane.iris.generation.runtime.ThreadSlots;
import art.arcane.iris.generation.cache.ConcurrentClockCache;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.volmlib.util.noise.CNG;
@@ -33,12 +34,12 @@ public final class Terrain3DRuntime {
private final Terrain3DFragmentFilter fragments;
private final Object profileLock = new Object();
private volatile Map<IrisTerrain3D, CompiledProfile> profiles = new IdentityHashMap<>();
private final ThreadLocal<ColumnMemo> localColumn = ThreadLocal.withInitial(ColumnMemo::new);
private final ThreadSlots<ColumnMemo> localColumn = new ThreadSlots<>(ColumnMemo::new);
private volatile Object cacheGeneration = new Object();
public Terrain3DRuntime(Sources sources, Options options) {
this(sources, options, (style, seed) -> {
CNG noise = style.createNoCache(new RNG(seed), options.data());
CNG noise = style.createNoCache(new RNG(seed), options.runtime());
return noise::noiseFastSigned3D;
});
}
@@ -317,7 +318,7 @@ public final class Terrain3DRuntime {
}
}
public record Options(long seed, int height, double fluidHeight, IrisData data,
public record Options(long seed, int height, double fluidHeight, PackRuntime runtime,
boolean enabled, int maximumColumns) {
public Options {
if (height < 2 || height > 4096 || !Double.isFinite(fluidHeight)
@@ -58,11 +58,11 @@ public final class SelectorCompiler {
IrisGeneratorStyle exported = exportable(key.style());
RNG seed = new RNG(CALIBRATION_SEED).nextParallelRNG(key.salt());
if (key.scaled()) {
CNG iris = exported.createScaledGenerator(seed, data, key.factor());
CNG iris = exported.createScaledGenerator(seed, data.standalonePackRuntime(), key.factor());
IrisGeneratorStyle compiled = scaledCopy(exported, key.factor());
return compile(compiled, key.salt(), iris::noiseFast2D, COHERENT_BLOCKS * compiled.getZoom());
}
CNG iris = exported.create(seed, data);
CNG iris = exported.create(seed, data.standalonePackRuntime());
double zoom = key.factor();
IrisGeneratorStyle compiled = copy(exported);
compiled.setZoom(exported.getZoom() * zoom);
@@ -30,7 +30,7 @@ final class DecoratorCoverage {
}
static Coverage measure(IrisGeneratorStyle style, double chance, IrisData data) {
CNG generator = style.createNoCache(new RNG(STYLE_SEED), data);
CNG generator = style.createNoCache(new RNG(STYLE_SEED), data.standalonePackRuntime());
double zoom = style.getZoom();
return measure((x, z) -> generator.fitDouble(0.0, 1.0, x / zoom, z / zoom) <= chance);
}
@@ -1,5 +1,6 @@
package art.arcane.iris.pack.datapack.export.compile.noise;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.noise.IrisGenerator;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.IrisNoiseGenerator;
@@ -38,6 +39,7 @@ public final class NoiseStyleCompiler implements StyleCompiler {
private final StyleCompiler selectors;
private final Map<LeafKey, LeafNoiseFit.FittedLeaf> leaves = new ConcurrentHashMap<>();
private final Map<LevelKey, WarpFit.LevelFit> levels = new ConcurrentHashMap<>();
private final PackRuntime runtime = PackRuntime.standalone(null);
public NoiseStyleCompiler(CellularStyleLowering cellular) {
this.cellular = Objects.requireNonNull(cellular, "cellular");
@@ -56,7 +58,7 @@ public final class NoiseStyleCompiler implements StyleCompiler {
}
public static CNG generator(IrisGeneratorStyle style) {
return build(prepared(Objects.requireNonNull(style, "style"), 1.0), 1);
return build(prepared(Objects.requireNonNull(style, "style"), 1.0), 1, PackRuntime.standalone(null));
}
@Override
@@ -182,7 +184,7 @@ public final class NoiseStyleCompiler implements StyleCompiler {
private Field style(IrisGeneratorStyle style, int octaveMultiplier, Domain domain, Emit emit, String path) {
IrisGeneratorStyle prepared = prepared(Objects.requireNonNull(style, "noise style"), domain.zoom());
String stylePath = path + "/" + styleName(style);
CNG root = build(prepared, octaveMultiplier);
CNG root = build(prepared, octaveMultiplier, runtime);
if (cellular(prepared, root)) {
if (domain.warpX() != null || domain.warpZ() != null) {
throw new IllegalArgumentException("Cellular noise style " + styleName(style) + " cannot be exported under a layer fracture warp");
@@ -393,8 +395,8 @@ public final class NoiseStyleCompiler implements StyleCompiler {
}
}
private static CNG build(IrisGeneratorStyle style, int octaveMultiplier) {
return style.createForLayer(new RNG(BUILD_SEED), null, octaveMultiplier);
private static CNG build(IrisGeneratorStyle style, int octaveMultiplier, PackRuntime runtime) {
return style.createForLayer(new RNG(BUILD_SEED), runtime, octaveMultiplier);
}
private static IrisGeneratorStyle prepared(IrisGeneratorStyle style, double zoom) {
@@ -184,7 +184,7 @@ final class VariantPlanner {
return warps;
}
String key = ContentIds.hash(GSON.toJson(style));
CNG generator = style.create(new RNG(ContentIds.seed(key)), data);
CNG generator = style.create(new RNG(ContentIds.seed(key)), data.standalonePackRuntime());
double half = style.getMultiplier() / 2;
WarpField field = (x, y, z) -> generator.fitDouble(-half, half, x, y, z);
for (int index = 0; index < WARP_VARIANTS; index++) {
@@ -1,5 +1,6 @@
package art.arcane.iris.pack.datapack.export.compile.subterrain;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.subterrain.IrisSubterrainFeature;
import art.arcane.iris.generation.subterrain.SubterrainBounds;
@@ -47,6 +48,7 @@ public final class SubterrainBaker {
private final long seed;
private final IrisData data;
private final PackRuntime runtime;
private final IrisDimension dimension;
private final BlockStateResolver blocks;
private final List<ExportDiagnostic> diagnostics;
@@ -57,6 +59,7 @@ public final class SubterrainBaker {
public SubterrainBaker(PackCompileContext context, long seed) {
this.seed = seed;
data = context.data();
runtime = data.standalonePackRuntime();
dimension = context.dimension();
blocks = BlockStateResolver.forContext(context);
diagnostics = context.diagnostics();
@@ -135,9 +138,9 @@ public final class SubterrainBaker {
}
int height = y - dimension.getMinHeight();
NativeBlockState candidate = switch (surface) {
case WALL -> biome.getWall().get(random, x, height, z, data);
case FLOOR -> first(biome.generateLayersWithSlope(dimension, x, z, random, 1, height + 1, data, FLAT_SLOPE));
case CEILING -> first(biome.generateCeilingLayers(dimension, x, z, random, 1, height - 1, data, null));
case WALL -> biome.getWall().get(random, x, height, z, runtime);
case FLOOR -> first(biome.generateLayersWithSlope(dimension, x, z, random, 1, height + 1, runtime, FLAT_SLOPE));
case CEILING -> first(biome.generateCeilingLayers(dimension, x, z, random, 1, height - 1, runtime, null));
case INTERIOR -> null;
};
return SubterrainRasterizer.isRetainedSolid(candidate) ? candidate : null;
@@ -171,7 +174,7 @@ public final class SubterrainBaker {
this.random = random;
this.resource = resource;
plans = List.of(plan);
surfaces = new SubterrainSurfaceMaterials(planner, plans, dimension, null, data, random, dimension.getMinHeight());
surfaces = new SubterrainSurfaceMaterials(planner, plans, dimension, null, runtime, random, dimension.getMinHeight());
}
private BakedRoom room() {
Loaded 100 of 241 files, more files were not shown because too many files have changed in this diff. Show more