Compare commits

..
Author SHA1 Message Date
piexel 48391475d1 Merge master
# Conflicts:
#	core/src/main/java/art/arcane/iris/generation/mantle/MantleObjectComponent.java
#	core/src/test/java/art/arcane/iris/pack/schema/SchemaBuilderIdentityTest.java
2026-11-28 18:14:05 +01:00
Brian Fopiano 512ea0b0d7 Allow empty sea and shore lists
- Keep the column biome when a region lists no shore biomes
- Keep the column biome when a region lists no sea biomes
- Pick continental sea from land in regions without sea biomes
- Fail complex compile when a region has no usable land biome
- Report regions without landBiomes as blocking validation errors
- Report regions whose land biomes are all version-excluded
- Use the region-aware base type in studio map noise views
- Handle missing sea biomes in studio sea layer views
2026-11-28 09:58:37 -05:00
Brian Fopiano 9425e802dc Skip retired continuation slices
- Add retired slice id list with TreeCanopy
- Skip unregistered retired slices by size prefix and warn once
- Split unknown and duplicate slice type errors
- Reject slice ids that overrun their size prefix
- Test retired skip, unknown id and duplicate failures
2026-11-28 09:58:22 -05:00
Brian Fopiano 95395cbc87 Cache saved terrain status
- Add per-slot terrain status cache under the iris folder
- Reuse a bit only when header location and timestamp match
- Decode again when timestamps fall near the previous scan time
- Never reuse bits for chunks stored in external mcc files
- Skip reading region files when every pending chunk is cached
- Use the cache only for the startup recovery scan
- Ignore unreadable or mismatched cache files and rescan fully
- Cover warm hits, invalidation and corrupt cache in tests
2026-11-28 09:58:21 -05:00
Brian Fopiano c71feb62e0 Fix bed rule for no-sleep dimensions
- Write destroy_on_use instead of the unknown explodes key
- Test bed rules for overworld, nether and end bases
2026-11-28 08:18:44 -05:00
Brian Fopiano 77969617d8 Fix Bukkit jar build
- Keep TomlSegments and ConfigComments in the shaded config classes
- Update the Mac noise hash after the fracture fix
2026-11-27 20:36:20 -05:00
Piexel ac5788ef02 Warn once for repeated pack warnings (#1262)
- Scope resource, loot and placement warnings to the pack
- Forget a pack's warn-once keys on reload and hotload
- Show read failure stack traces only the first time
- Drop least recently seen once-key past the cap
- Walk the caller stack only for stated warnings
2026-11-27 15:52:26 -05:00
Piexel d7c5526eab Add style seed and generator exponent (#1268)
- Add seed to noise styles, rolled from the world seed
- Read seeded styles flat in child, palette and decorator lookups
- Add exponent curve to generators on scalar and batch paths
- Reject generator exponents at or below zero
- Warn in datapack export when seed or exponent is dropped
2026-11-27 13:44:03 -05:00
Piexel 4c90095361 Warn on imported feature height (#1274)
- Warn when importedFeatures runs outside -64..320
- Point at disabled and disabledSteps to remove ores
- Stay silent when imported features are off
2026-11-27 12:58:04 -05:00
Piexel 25c612b3c3 Add requireAllContent (#1281)
- Add requireAllContent dimension setting, off by default
- Fail pack validation when flagged dimension loses reached content
- Skip content the dimension never references
- Keep declared fallbacks from failing the pack
- Name missing keys with up to three uses each
2026-11-27 11:58:38 -05:00
piexel 1e0645fc9e Update schema digest for object separation 2026-11-14 21:06:20 +01:00
piexel 2d727be4bc Space surface objects apart
- Add separation to object placements
- Add chanceStyle noise to placement chance
2026-11-14 15:17:37 +01:00
57 changed files with 3118 additions and 250 deletions

No files matched your search

@@ -30,6 +30,7 @@ import art.arcane.iris.world.loot.IrisLootTable;
import art.arcane.iris.structure.object.IrisObjectLoot;
import art.arcane.iris.structure.object.IrisObjectPlacement;
import art.arcane.iris.structure.object.IrisObjectVanillaLoot;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
@@ -40,6 +41,9 @@ import java.util.ArrayList;
import java.util.List;
public final class ModdedLootApplier {
private static final String LOOT_TABLE_KEY_KIND = "missing-loot-table";
private static final String VANILLA_LOOT_TABLE_KEY_KIND = "missing-vanilla-loot-table";
private ModdedLootApplier() {
}
@@ -117,7 +121,8 @@ public final class ModdedLootApplier {
}
IrisLootTable table = engine.getData().getLootLoader().load(loot.getName());
if (table == null) {
IrisLogging.warn("Couldn't find loot table " + loot.getName());
IrisLogging.warnOnce(IrisData.onceKey(engine.getData(), LOOT_TABLE_KEY_KIND, loot.getName()),
"Couldn't find loot table " + loot.getName());
continue;
}
bucket(engine, loot, new Candidate(new IrisLootSource(table), loot.getWeight()), access, exact, basic, global);
@@ -129,7 +134,8 @@ public final class ModdedLootApplier {
}
NativeContainerLoot.Table table = access.table(loot.getName());
if (table == null) {
IrisLogging.warn("Couldn't find vanilla loot table " + loot.getName());
IrisLogging.warnOnce(IrisData.onceKey(engine.getData(), VANILLA_LOOT_TABLE_KEY_KIND, loot.getName()),
"Couldn't find vanilla loot table " + loot.getName());
continue;
}
bucket(engine, loot, new Candidate(new NativeLootSource(table), loot.getWeight()), access, exact, basic, global);
+1 -1
View File
@@ -482,7 +482,7 @@ List<String> dependencyBuildMetadata = [
'META-INF/versions/*/OSGI-INF/**'
]
String languageTomlSupportClassPattern = 'art/arcane/volmlib/util/config/(?:TomlCodec|ConfigJson|ConfigExposePolicy|ConfigDoc|ConfigDescription|ConfigDocumentation)(?:\\$[^/]+)?\\.class'
String languageTomlSupportClassPattern = 'art/arcane/volmlib/util/config/(?:TomlCodec|TomlSegments|ConfigComments|ConfigJson|ConfigExposePolicy|ConfigDoc|ConfigDescription|ConfigDocumentation)(?:\\$[^/]+)?\\.class'
tasks.named('shadowJar', ShadowJar).configure {
inputs.property('languageTomlSupportClassPattern', languageTomlSupportClassPattern)
@@ -478,7 +478,8 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
}
public CNG getChildrenGenerator(PackRuntime runtime, long seed, double scale) {
return runtime.biome(this).childrenGenerator(seed, scale);
double childScale = getChildStyle().isSeeded() ? 1 : scale;
return runtime.biome(this).childrenGenerator(seed, childScale);
}
CNG createChildrenGenerator(long seed, double scale, PackRuntime runtime) {
@@ -231,10 +231,10 @@ final class IrisBiomeLayerGenerator {
int layerIndex = findLayer(boundaries, position);
IrisBiomePaletteLayer layer = layers.get(layerIndex);
int offset = position - boundaries[layerIndex];
double zoom = layer.getZoom();
double blocksPerSample = layer.blocksPerSample();
try {
data.add(layer.get(random, layerIndex + offset,
(wx + offset) / zoom, offset, (wz - offset) / zoom, biomeRuntime.surfaceLayer(layerIndex)));
(wx + offset) / blocksPerSample, offset, (wz - offset) / blocksPerSample, biomeRuntime.surfaceLayer(layerIndex)));
} catch (Throwable error) {
GenerationFailures.skipPlacement(error, "surface layer", "block", (int) wx, height - depth, (int) wz, biome.getLoadKey());
}
@@ -337,11 +337,11 @@ final class IrisBiomeLayerGenerator {
private static void appendLayer(KList<NativeBlockState> blocks, IrisBiomePaletteLayer layer,
PaletteLayerRuntime layerRuntime, int layerIndex, int thickness, double x, double z,
RNG random, int maxDepth) {
double zoom = layer.getZoom();
double blocksPerSample = layer.blocksPerSample();
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, layerRuntime));
(x + offset) / blocksPerSample, offset, (z - offset) / blocksPerSample, layerRuntime));
} catch (Throwable error) {
GenerationFailures.skipPlacement(error, "surface layer", "block", (int) x, -1, (int) z, "none");
}
@@ -112,11 +112,19 @@ public class IrisBiomePaletteLayer {
private NativeBlockState fit(KList<NativeBlockState> localBlockData, PaletteLayerRuntime layerRuntime,
RNG parent, int signature, double x, double y, double z) {
double localZoom = zoom;
CNG generator = layerRuntime.layerGenerator(layerGeneratorSeed(parent, signature, localBlockData.size()));
if (style.isSeeded()) {
return generator.fit(localBlockData, x, z);
}
double localZoom = zoom;
return generator.fit(localBlockData, x / localZoom, y / localZoom, z / localZoom);
}
/** How many blocks one step of the layer's block noise spans: its zoom, or 1 for a seeded style, which is read flat. */
public double blocksPerSample() {
return style.isSeeded() ? 1 : zoom;
}
public CNG getLayerGenerator(RNG rng, PackRuntime runtime) {
return getLayerGenerator(rng, 0, runtime);
}
@@ -169,11 +169,17 @@ public class IrisDecorator {
if (getBlockData(decoratorRuntime.packRuntime().data()).isEmpty()) {
return false;
}
double xx = x / style.getZoom();
double zz = z / style.getZoom();
double blocksPerSample = chanceBlocksPerSample();
double xx = x / blocksPerSample;
double zz = z / blocksPerSample;
return decoratorRuntime.layerGenerator(rng.getSeed()).fitDouble(0D, 1D, xx, zz) <= chance;
}
/** A style without a seed divides by its zoom here on top of its own scale; a seeded one is read in plain blocks. */
private double chanceBlocksPerSample() {
return style.isSeeded() ? 1 : style.getZoom();
}
public NativeBlockState getBlockData(IrisBiome b, RNG rng, double x, double z, PackRuntime runtime) {
if (!passesChanceGate(rng, x, z, runtime)) {
return null;
@@ -204,8 +210,9 @@ public class IrisDecorator {
return getBlockData100(b, rng, x, y, z, runtime);
}
double xx = x / style.getZoom();
double zz = z / style.getZoom();
double blocksPerSample = chanceBlocksPerSample();
double xx = x / blocksPerSample;
double zz = z / blocksPerSample;
if (getGenerator(rng, runtime).fitDouble(0D, 1D, xx, zz) <= chance) { //Exclude y from here
if (topPalette.size() == 1) {
@@ -35,6 +35,7 @@ import art.arcane.iris.structure.object.IrisAxisRotationClamp;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.cave.IrisCaveAnchorMode;
import art.arcane.iris.generation.cave.IrisCaveProfile;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.structure.object.IrisObject;
import art.arcane.iris.structure.object.IrisObjectPlacement;
@@ -70,8 +71,11 @@ import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import art.arcane.iris.generation.block.DataProvider;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.EnumSet;
import java.util.HashMap;
@@ -85,9 +89,10 @@ import java.util.function.BiConsumer;
public class MantleObjectComponent extends IrisMantleComponent {
private static final long CAVE_REJECT_LOG_THROTTLE_MS = 5000L;
private static final int BEDROCK_CLEARANCE = 6;
private static final long OBJECT_SEPARATION_SEED_SALT = 0x5E9A2A7E0B1EC75L;
static final byte LIQUID_FORCED_AIR = 3;
private static final Map<String, CaveRejectLogState> CAVE_REJECT_LOG_STATE = new ConcurrentHashMap<>();
private static final Set<String> MISSING_LOAD_KEY_WARNED = ConcurrentHashMap.newKeySet();
private static final String MISSING_LOAD_KEY_KIND = "marker-missing-load-key";
private static final long SOURCE_PLAN_STATS_INTERVAL_MS = 30_000L;
private static final int MAXIMUM_TREE_MATERIALS = 8192;
private static final Map<NativeBlockState, TreeBlockMaterial> TREE_MATERIALS = new ConcurrentHashMap<>();
@@ -105,21 +110,29 @@ public class MantleObjectComponent extends IrisMantleComponent {
this.collisionRuleState = -1;
}
private static String placementMarker(IrisObject object, int id, String context) {
static String placementMarker(IrisObject object, int id, String context) {
String key = object == null ? null : object.getLoadKey();
if (key == null || key.isEmpty() || key.equals("null")) {
String fingerprint = context + "|" + (object == null ? "<null>" : object.getClass().getSimpleName());
if (MISSING_LOAD_KEY_WARNED.add(fingerprint)) {
java.io.File file = object == null ? null : object.getLoadFile();
IrisLogging.warn("Skipping placement marker write: IrisObject has no loadKey (context=" + context
+ ", file=" + (file == null ? "<unknown>" : file.getPath()) + "). "
+ "This would previously produce 'Couldn't find Object: null' warnings on chunk reload.");
}
warnMissingLoadKeyOnce(object, context);
return null;
}
return key + "@" + id;
}
/**
* Keyed by call-site context and object class only: the file path and coordinates stay in the message,
* never in the key, so the key space is bounded.
*/
private static void warnMissingLoadKeyOnce(IrisObject object, String context) {
String fingerprint = context + "|" + (object == null ? "<null>" : object.getClass().getSimpleName());
IrisData pack = object == null ? null : object.getLoader();
java.io.File file = object == null ? null : object.getLoadFile();
IrisLogging.warnOnce(IrisData.onceKey(pack, MISSING_LOAD_KEY_KIND, fingerprint),
"Skipping placement marker write: IrisObject has no loadKey (context=" + context
+ ", file=" + (file == null ? "<unknown>" : file.getPath()) + "). "
+ "This would previously produce 'Couldn't find Object: null' warnings on chunk reload.");
}
private static boolean isTreePlacement(IrisObject object, IrisObjectPlacement placement) {
String key = object == null ? null : object.getLoadKey();
return (key != null && key.startsWith("trees/"))
@@ -480,29 +493,17 @@ public class MantleObjectComponent extends IrisMantleComponent {
for (IrisObjectPlacement i : surfaceBiome.getSurfaceObjects()) {
biomeSurfaceChecked++;
boolean chance = rng.chance(i.getChance() + rng.d(-0.005, 0.005)) && !i.isCompatExcluded(getData());
if (traceRegen) {
IrisLogging.debug("Regen object placer chance: chunk=" + x + "," + z
+ " scope=biome-surface"
+ " chanceResult=" + chance
+ " chanceBase=" + i.getChance()
+ " densityMid=" + i.getDensity()
+ " objects=" + i.getPlace().size());
}
if (chance) {
biomeSurfaceTriggered++;
try {
ObjectPlacementResult result = placeObject(writer, rng, x << 4, z << 4, i, complex, traceRegen, x, z, "biome-surface");
attempts += result.attempts();
placed += result.placed();
rejected += result.rejected();
nullObjects += result.nullObjects();
errors += result.errors();
} catch (Throwable e) {
GenerationFailures.skipPlacement(e, "object", i.getPlace().toString(", "), x << 4, -1, z << 4, surfaceBiome.getLoadKey());
errors++;
}
Optional<ObjectPlacementResult> triggered = placeSurfacePlacement(writer, rng, x, z, i, complex, traceRegen, "biome-surface", surfaceBiome.getLoadKey());
if (triggered.isEmpty()) {
continue;
}
biomeSurfaceTriggered++;
ObjectPlacementResult result = triggered.get();
attempts += result.attempts();
placed += result.placed();
rejected += result.rejected();
nullObjects += result.nullObjects();
errors += result.errors();
}
for (IrisObjectPlacement i : caveBiome.getCarvingObjects()) {
@@ -537,29 +538,17 @@ public class MantleObjectComponent extends IrisMantleComponent {
for (IrisObjectPlacement i : region.getSurfaceObjects()) {
regionSurfaceChecked++;
boolean chance = rng.chance(i.getChance() + rng.d(-0.005, 0.005)) && !i.isCompatExcluded(getData());
if (traceRegen) {
IrisLogging.debug("Regen object placer chance: chunk=" + x + "," + z
+ " scope=region-surface"
+ " chanceResult=" + chance
+ " chanceBase=" + i.getChance()
+ " densityMid=" + i.getDensity()
+ " objects=" + i.getPlace().size());
}
if (chance) {
regionSurfaceTriggered++;
try {
ObjectPlacementResult result = placeObject(writer, rng, x << 4, z << 4, i, complex, traceRegen, x, z, "region-surface");
attempts += result.attempts();
placed += result.placed();
rejected += result.rejected();
nullObjects += result.nullObjects();
errors += result.errors();
} catch (Throwable e) {
GenerationFailures.skipPlacement(e, "object", i.getPlace().toString(", "), x << 4, -1, z << 4, region.getLoadKey());
errors++;
}
Optional<ObjectPlacementResult> triggered = placeSurfacePlacement(writer, rng, x, z, i, complex, traceRegen, "region-surface", region.getLoadKey());
if (triggered.isEmpty()) {
continue;
}
regionSurfaceTriggered++;
ObjectPlacementResult result = triggered.get();
attempts += result.attempts();
placed += result.placed();
rejected += result.rejected();
nullObjects += result.nullObjects();
errors += result.errors();
}
for (IrisObjectPlacement i : region.getCarvingObjects()) {
@@ -968,86 +957,194 @@ public class MantleObjectComponent extends IrisMantleComponent {
IrisObject v = objectPlacement.scaleObject(rng, objectPlacement.getObject(complex, rng), getDimension());
if (v == null) {
nullObjects++;
if (traceRegen) {
IrisLogging.debug("Regen object placement null object: chunk=" + chunkX + "," + chunkZ
+ " scope=" + scope
+ " densityIndex=" + i
+ " density=" + density
+ " placementKeys=" + objectPlacement.getPlace().toString(","));
}
traceNullObject(traceRegen, chunkX, chunkZ, scope, i, density, objectPlacement);
continue;
}
int xx = rng.i(x, x + 16);
int zz = rng.i(z, z + 16);
IrisObjectPlacement effectivePlacement = resolveEffectivePlacement(objectPlacement, v);
if (!allowsObjectPlacement(complex, v, effectivePlacement, xx, zz)) {
rejected++;
continue;
}
boolean treePlacement = isTreePlacement(v, effectivePlacement);
int id = rng.i(0, Integer.MAX_VALUE);
IObjectPlacer placePlacer = golden ? new GoldenDebugObjectPlacer(writer, scope + "/" + v.getLoadKey()) : writer;
if (golden) {
IrisLogging.debug("Goldendebug object attempt: chunk=" + chunkX + "," + chunkZ
+ " scope=" + scope
+ " object=" + v.getLoadKey()
+ " densityIndex=" + i
+ " xx=" + xx
+ " zz=" + zz
+ " mode=" + effectivePlacement.getMode());
}
try {
String marker = placementMarker(v, id, "surface");
int continuation = writer.beginObjectPlacement(effectivePlacement.waterRule());
int result = v.place(xx, zz, placePlacer, effectivePlacement, rng, (b, data) -> {
if (marker != null) {
writer.setData(b.getX(), b.getY(), b.getZ(), marker);
}
if (treePlacement && marker != null) {
writeTreeMaterial(writer, b.getX(), b.getY(), b.getZ(), data);
}
if (effectivePlacement.isDolphinTarget() && effectivePlacement.isUnderwater() && B.isStorageChest(data)) {
writer.setData(b.getX(), b.getY(), b.getZ(), MatterStructurePOI.BURIED_TREASURE);
}
}, null, getData());
if (result >= 0) {
writer.recordObjectPlacement(continuation);
placed++;
} else {
rejected++;
}
if (golden) {
IrisLogging.debug("Goldendebug object result: chunk=" + chunkX + "," + chunkZ
+ " scope=" + scope
+ " object=" + v.getLoadKey()
+ " resultY=" + result
+ " fallback=surface");
}
if (traceRegen) {
IrisLogging.debug("Regen object placement result: chunk=" + chunkX + "," + chunkZ
+ " scope=" + scope
+ " object=" + v.getLoadKey()
+ " resultY=" + result
+ " px=" + xx
+ " pz=" + zz
+ " fallback=surface"
+ " densityIndex=" + i
+ " density=" + density);
}
} catch (Throwable e) {
GenerationFailures.skipPlacement(e, "object", v.getLoadKey(), chunkX << 4, -1, chunkZ << 4, scope);
errors++;
} finally {
writer.endObjectPlacement();
}
ObjectPlacementResult result = placeObjectAt(writer, rng, v, xx, zz, objectPlacement, complex, traceRegen, chunkX, chunkZ, scope, i, density);
placed += result.placed();
rejected += result.rejected();
errors += result.errors();
}
return new ObjectPlacementResult(attempts, placed, rejected, nullObjects, errors);
}
private void traceNullObject(boolean traceRegen, int chunkX, int chunkZ, String scope, int densityIndex, int density, IrisObjectPlacement objectPlacement) {
if (!traceRegen) {
return;
}
IrisLogging.debug("Regen object placement null object: chunk=" + chunkX + "," + chunkZ
+ " scope=" + scope
+ " densityIndex=" + densityIndex
+ " density=" + density
+ " placementKeys=" + objectPlacement.getPlace().toString(","));
}
@BlockCoordinates
private ObjectPlacementResult placeObjectAt(
ObjectPassPlacer writer,
RNG rng,
IrisObject v,
int xx,
int zz,
IrisObjectPlacement objectPlacement,
IrisComplex complex,
boolean traceRegen,
int chunkX,
int chunkZ,
String scope,
int densityIndex,
int density
) {
IrisObjectPlacement effectivePlacement = resolveEffectivePlacement(objectPlacement, v);
if (!allowsObjectPlacement(complex, v, effectivePlacement, xx, zz)) {
return new ObjectPlacementResult(0, 0, 1, 0, 0);
}
boolean golden = GoldenDebugObjectPlacer.isGoldenDebugChunk(chunkX, chunkZ);
boolean treePlacement = isTreePlacement(v, effectivePlacement);
int id = rng.i(0, Integer.MAX_VALUE);
IObjectPlacer placePlacer = golden ? new GoldenDebugObjectPlacer(writer, scope + "/" + v.getLoadKey()) : writer;
if (golden) {
IrisLogging.debug("Goldendebug object attempt: chunk=" + chunkX + "," + chunkZ
+ " scope=" + scope
+ " object=" + v.getLoadKey()
+ " densityIndex=" + densityIndex
+ " xx=" + xx
+ " zz=" + zz
+ " mode=" + effectivePlacement.getMode());
}
try {
String marker = placementMarker(v, id, "surface");
int continuation = writer.beginObjectPlacement(effectivePlacement.waterRule());
int result = v.place(xx, zz, placePlacer, effectivePlacement, rng, (b, data) -> {
if (marker != null) {
writer.setData(b.getX(), b.getY(), b.getZ(), marker);
}
if (treePlacement && marker != null) {
writeTreeMaterial(writer, b.getX(), b.getY(), b.getZ(), data);
}
if (effectivePlacement.isDolphinTarget() && effectivePlacement.isUnderwater() && B.isStorageChest(data)) {
writer.setData(b.getX(), b.getY(), b.getZ(), MatterStructurePOI.BURIED_TREASURE);
}
}, null, getData());
if (result >= 0) {
writer.recordObjectPlacement(continuation);
}
if (golden) {
IrisLogging.debug("Goldendebug object result: chunk=" + chunkX + "," + chunkZ
+ " scope=" + scope
+ " object=" + v.getLoadKey()
+ " resultY=" + result
+ " fallback=surface");
}
if (traceRegen) {
IrisLogging.debug("Regen object placement result: chunk=" + chunkX + "," + chunkZ
+ " scope=" + scope
+ " object=" + v.getLoadKey()
+ " resultY=" + result
+ " px=" + xx
+ " pz=" + zz
+ " fallback=surface"
+ " densityIndex=" + densityIndex
+ " density=" + density);
}
return result >= 0 ? new ObjectPlacementResult(0, 1, 0, 0, 0) : new ObjectPlacementResult(0, 0, 1, 0, 0);
} catch (Throwable e) {
GenerationFailures.skipPlacement(e, "object", v.getLoadKey(), chunkX << 4, -1, chunkZ << 4, scope);
return new ObjectPlacementResult(0, 0, 0, 0, 1);
} finally {
writer.endObjectPlacement();
}
}
private Optional<ObjectPlacementResult> placeSurfacePlacement(
ObjectPassPlacer writer,
RNG rng,
int chunkX,
int chunkZ,
IrisObjectPlacement placement,
IrisComplex complex,
boolean traceRegen,
String scope,
String ownerKey
) {
try {
if (placement.isSeparated()) {
return placeSeparatedObject(writer, chunkX, chunkZ, placement, complex, traceRegen, scope);
}
double chance = objectSeparation().chanceAt(placement, (chunkX << 4) + 8, (chunkZ << 4) + 8);
boolean passes = rng.chance(chance + rng.d(-0.005, 0.005)) && !placement.isCompatExcluded(getData());
traceSurfaceChance(traceRegen, chunkX, chunkZ, scope, passes, placement);
if (!passes) {
return Optional.empty();
}
return Optional.of(placeObject(writer, rng, chunkX << 4, chunkZ << 4, placement, complex, traceRegen, chunkX, chunkZ, scope));
} catch (Throwable e) {
GenerationFailures.skipPlacement(e, "object", placement.getPlace().toString(", "), chunkX << 4, -1, chunkZ << 4, ownerKey);
return Optional.of(new ObjectPlacementResult(0, 0, 0, 0, 1));
}
}
private void traceSurfaceChance(boolean traceRegen, int chunkX, int chunkZ, String scope, boolean passes, IrisObjectPlacement placement) {
if (!traceRegen) {
return;
}
IrisLogging.debug("Regen object placer chance: chunk=" + chunkX + "," + chunkZ
+ " scope=" + scope
+ " chanceResult=" + passes
+ " chanceBase=" + placement.getChance()
+ " densityMid=" + placement.getDensity()
+ " objects=" + placement.getPlace().size());
}
private Optional<ObjectPlacementResult> placeSeparatedObject(
ObjectPassPlacer writer,
int chunkX,
int chunkZ,
IrisObjectPlacement placement,
IrisComplex complex,
boolean traceRegen,
String scope
) {
Optional<ObjectSeparation.Candidate> kept = placement.isCompatExcluded(getData())
? Optional.empty()
: objectSeparation().keptCandidate(chunkX, chunkZ, placement);
traceSurfaceChance(traceRegen, chunkX, chunkZ, scope, kept.isPresent(), placement);
if (kept.isEmpty()) {
return Optional.empty();
}
ObjectSeparation.Candidate candidate = kept.get();
IrisObject object = placement.scaleObject(candidate.rng(), placement.getObject(complex, candidate.rng()), getDimension());
if (object == null) {
traceNullObject(traceRegen, chunkX, chunkZ, scope, 0, 1, placement);
return Optional.of(new ObjectPlacementResult(1, 0, 0, 1, 0));
}
ObjectPlacementResult result = placeObjectAt(writer, candidate.rng(), object, candidate.x(), candidate.z(), placement, complex, traceRegen, chunkX, chunkZ, scope, 0, 1);
return Optional.of(new ObjectPlacementResult(1, result.placed(), result.rejected(), 0, result.errors()));
}
private ObjectSeparation objectSeparation() {
return new ObjectSeparation(seed() + OBJECT_SEPARATION_SEED_SALT, PackRuntime.of(getEngineMantle().getEngine(), getData()), this::surfacePlacementsAt);
}
private List<IrisObjectPlacement> surfacePlacementsAt(int chunkX, int chunkZ) {
IrisComplex complex = getComplex();
if (!complex.allowsNewGenerationChunk(chunkX, chunkZ)) {
return List.of();
}
int blockX = (chunkX << 4) + 8;
int blockZ = (chunkZ << 4) + 8;
List<IrisObjectPlacement> placements = new ArrayList<>(complex.getTrueBiomeStream().get(blockX, blockZ).getSurfaceObjects());
placements.addAll(complex.getRegionStream().get(blockX, blockZ).getSurfaceObjects());
placements.removeIf(placement -> placement.isCompatExcluded(getData()));
return placements;
}
@ChunkCoordinates
private boolean caveAnchorBiomeConflicts(int x, int y, int z, String expectedCaveBiomeKey) {
if (expectedCaveBiomeKey == null) {
@@ -1755,21 +1852,34 @@ public class MantleObjectComponent extends IrisMantleComponent {
IrisBiome biome = getComplex().getTrueBiomeStream().get(blockX, blockZ);
IrisRegion region = getComplex().getRegionStream().get(blockX, blockZ);
Set<String> v = new KSet<>();
for (IrisObjectPlacement i : biome.getSurfaceObjects()) {
if (rng.chance(i.getChance() + rng.d(-0.005, 0.005)) && !i.isCompatExcluded(getData())) {
v.addAll(guessPlacedKeys(rng, x, z, i));
}
}
for (IrisObjectPlacement i : region.getSurfaceObjects()) {
if (rng.chance(i.getChance() + rng.d(-0.005, 0.005)) && !i.isCompatExcluded(getData())) {
v.addAll(guessPlacedKeys(rng, x, z, i));
}
}
guessSurfaceKeys(rng, x, z, biome.getSurfaceObjects(), v);
guessSurfaceKeys(rng, x, z, region.getSurfaceObjects(), v);
return v;
}
private void guessSurfaceKeys(RNG rng, int x, int z, List<IrisObjectPlacement> placements, Set<String> keys) {
ObjectSeparation separation = objectSeparation();
for (IrisObjectPlacement i : placements) {
if (i.isSeparated()) {
guessSeparatedKey(separation, x, z, i).ifPresent(keys::add);
continue;
}
double chance = separation.chanceAt(i, (x << 4) + 8, (z << 4) + 8);
if (rng.chance(chance + rng.d(-0.005, 0.005)) && !i.isCompatExcluded(getData())) {
keys.addAll(guessPlacedKeys(rng, x, z, i));
}
}
}
private Optional<String> guessSeparatedKey(ObjectSeparation separation, int x, int z, IrisObjectPlacement placement) {
if (placement.isCompatExcluded(getData())) {
return Optional.empty();
}
return separation.keptCandidate(x, z, placement)
.map(candidate -> placement.scaleObject(candidate.rng(), placement.getObject(getComplex(), candidate.rng()), getDimension()))
.map(IrisObject::getLoadKey);
}
protected int computeRadius() {
KSet<String> warnedLargeObjects = new KSet<>();
PlacementReach reach = new ReachScan(getDimension(), this::getData, warnedLargeObjects).dimension();
@@ -8,11 +8,14 @@ import art.arcane.volmlib.util.io.CountingDataInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UncheckedIOException;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.world.storage.matter.IrisMatterSupport;
import art.arcane.iris.world.storage.matter.RetiredMatterSlices;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;
@@ -147,6 +150,7 @@ public record ObjectContinuationBundle(List<Fragment> fragments) {
Matter matter = new IrisMatter(width, height, depth);
int sliceCount = input.readUnsignedByte();
matter.getHeader().read(input);
HashSet<String> skippedRetired = new HashSet<>();
for (int index = 0; index < sliceCount; index++) {
int size = input.readInt();
long end = input.count() + size;
@@ -154,9 +158,24 @@ public record ObjectContinuationBundle(List<Fragment> fragments) {
throw new IOException("Invalid object continuation slice size");
}
String identifier = input.readUTF();
if (input.count() > end) {
throw new IOException("Object continuation slice size mismatch: " + identifier);
}
Class<?> type = IrisMatter.getSliceType(identifier);
if (type == null || matter.hasSlice(type)) {
throw new IOException("Unavailable or duplicate object continuation slice: " + identifier);
if (type == null) {
if (!RetiredMatterSlices.isRetired(identifier)) {
throw new IOException("Unknown object continuation slice type: " + identifier);
}
if (!skippedRetired.add(identifier)) {
throw new IOException("Duplicate object continuation slice type: " + identifier);
}
input.skipTo(end);
IrisLogging.warnOnce("object-continuation:retired-slice:" + identifier,
"Skipping retired object continuation slice %s written by an older Iris version", identifier);
continue;
}
if (matter.hasSlice(type)) {
throw new IOException("Duplicate object continuation slice type: " + identifier);
}
MatterSlice<?> slice = matter.createSlice(type, matter);
if (slice == null) {
@@ -0,0 +1,137 @@
/*
* 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.mantle;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.structure.object.IrisObjectPlacement;
import art.arcane.volmlib.util.math.RNG;
import java.util.List;
import java.util.Optional;
/**
* The chance and spacing of surface object placements.
*
* <p>A separated placement rolls one candidate spot per chunk. The candidate stands only when no candidate of a lower rank,
* from a placement with the same objects, lies closer than the separation. Spots and ranks come from the seed, the chunk
* and the objects alone, so every chunk agrees on them across chunk, biome and region borders, and objects never stand
* closer than the separation, whatever order chunks generate in.
*/
final class ObjectSeparation {
private static final int CHUNK_WIDTH_BLOCKS = 16;
private static final int CHUNK_SHIFT = 4;
private final long seed;
private final PackRuntime runtime;
private final SurfacePlacements surfacePlacements;
ObjectSeparation(long seed, PackRuntime runtime, SurfacePlacements surfacePlacements) {
this.seed = seed;
this.runtime = runtime;
this.surfacePlacements = surfacePlacements;
}
/** The placements a chunk places on the surface, in placing order. A chunk places the biome's before the region's. */
@FunctionalInterface
interface SurfacePlacements {
List<IrisObjectPlacement> at(int chunkX, int chunkZ);
}
/** Where a chunk would place, in block coordinates, with the random that picks and places the object there. */
record Candidate(int x, int z, long rank, RNG rng) {
boolean isCloserThan(Candidate other, int blocks) {
long dx = x - other.x;
long dz = z - other.z;
return dx * dx + dz * dz < (long) blocks * blocks;
}
}
/** The chance to place at the block column: the placement's chance, multiplied by its chance noise when it has one. */
double chanceAt(IrisObjectPlacement placement, double x, double z) {
IrisGeneratorStyle style = placement.getChanceStyle();
if (style == null) {
return placement.getChance();
}
return placement.getChance() * style.create(seed, runtime).fitDouble(0D, 1D, x, z);
}
/**
* The candidate the chunk places for the separated placement; empty when it rolled none or a lower ranked one is too
* close.
*/
Optional<Candidate> keptCandidate(int chunkX, int chunkZ, IrisObjectPlacement placement) {
Optional<Candidate> own = candidateOf(chunkX, chunkZ, placement);
if (own.isEmpty() || isOutranked(own.get(), chunkX, chunkZ, placement)) {
return Optional.empty();
}
return own;
}
private boolean isOutranked(Candidate own, int chunkX, int chunkZ, IrisObjectPlacement placement) {
int reach = placement.getSeparation();
int minimumChunkX = Math.floorDiv(own.x() - reach, CHUNK_WIDTH_BLOCKS);
int maximumChunkX = Math.floorDiv(own.x() + reach, CHUNK_WIDTH_BLOCKS);
int minimumChunkZ = Math.floorDiv(own.z() - reach, CHUNK_WIDTH_BLOCKS);
int maximumChunkZ = Math.floorDiv(own.z() + reach, CHUNK_WIDTH_BLOCKS);
for (int x = minimumChunkX; x <= maximumChunkX; x++) {
for (int z = minimumChunkZ; z <= maximumChunkZ; z++) {
if ((x != chunkX || z != chunkZ) && isOutrankedBy(x, z, own, placement)) {
return true;
}
}
}
return false;
}
private boolean isOutrankedBy(int rivalChunkX, int rivalChunkZ, Candidate own, IrisObjectPlacement placement) {
Optional<Candidate> rival = placementOfSameObjectsAt(rivalChunkX, rivalChunkZ, placement)
.flatMap(other -> candidateOf(rivalChunkX, rivalChunkZ, other));
return rival.isPresent() && rival.get().rank() < own.rank() && rival.get().isCloserThan(own, placement.getSeparation());
}
private Optional<IrisObjectPlacement> placementOfSameObjectsAt(int chunkX, int chunkZ, IrisObjectPlacement placement) {
return surfacePlacements.at(chunkX, chunkZ).stream()
.filter(other -> other.isSeparated() && other.getPlace().equals(placement.getPlace()))
.findFirst();
}
private Optional<Candidate> candidateOf(int chunkX, int chunkZ, IrisObjectPlacement placement) {
RNG rng = new RNG(chunkSeed(chunkX, chunkZ, placement.getPlace().hashCode()));
int x = (chunkX << CHUNK_SHIFT) + rng.nextInt(CHUNK_WIDTH_BLOCKS);
int z = (chunkZ << CHUNK_SHIFT) + rng.nextInt(CHUNK_WIDTH_BLOCKS);
if (!rng.chance(chanceAt(placement, x, z))) {
return Optional.empty();
}
return Optional.of(new Candidate(x, z, rng.nextLong(), rng));
}
// Each input is mixed in after the previous one: XORing scaled coordinates gave chunk x,z and -x,-z the same seed
// whenever both were odd.
private long chunkSeed(int chunkX, int chunkZ, int objectsHash) {
return splitMix(splitMix(splitMix(seed + objectsHash) + chunkX) + chunkZ);
}
private static long splitMix(long value) {
long mixed = value + 0x9E3779B97F4A7C15L;
mixed = (mixed ^ (mixed >>> 30)) * 0xBF58476D1CE4E5B9L;
mixed = (mixed ^ (mixed >>> 27)) * 0x94D049BB133111EBL;
return mixed ^ (mixed >>> 31);
}
}
@@ -15,6 +15,7 @@ public final class GeneratorProgram {
private final NoiseLayerProgram cliffs;
private final boolean multiplicitive;
private final double opacity;
private final double exponent;
private final double offsetX;
private final double offsetZ;
private final double zoom;
@@ -36,6 +37,7 @@ public final class GeneratorProgram {
this.cliffs = cliffs;
this.multiplicitive = generator.isMultiplicitive();
this.opacity = generator.getOpacity();
this.exponent = generator.getExponent();
this.offsetX = generator.getOffsetX();
this.offsetZ = generator.getOffsetZ();
this.zoom = generator.getZoom();
@@ -122,7 +124,8 @@ public final class GeneratorProgram {
double noise = layer.sample(scratch, sampleX, sampleZ);
value = multiplicitive ? value * noise : value + noise;
}
value = multiplicitive ? value * opacity : (value / totalOpacity) * opacity;
double combined = multiplicitive ? value : value / totalOpacity;
value = IrisGenerator.applyExponent(combined, exponent) * opacity;
if (Double.isNaN(value)) {
value = 0D;
}
@@ -302,7 +305,8 @@ public final class GeneratorProgram {
}
}
for (int index = 0; index < count; index++) {
double value = multiplicitive ? out[index] * opacity : (out[index] / totalOpacity) * opacity;
double combined = multiplicitive ? out[index] : out[index] / totalOpacity;
double value = IrisGenerator.applyExponent(combined, exponent) * opacity;
out[index] = Double.isNaN(value) ? 0D : value;
}
if (cliffs != null) {
@@ -62,6 +62,9 @@ public class IrisGenerator extends IrisRegistrant {
@Description("Multiply the compsites instead of adding them")
private boolean multiplicitive = false;
@MinNumber(0.001)
@Description("Curves the combined composite value (0-1) as value^exponent before opacity. Above 1 flattens lows and sharpens peaks, below 1 does the opposite. Unlike the exponent on a single noise generator, this acts on the combined result of all composites.")
private double exponent = 1;
@MinNumber(0.001)
@Description("The size of the cell fractures")
private double cellFractureZoom = 1D;
@MinNumber(0)
@@ -178,6 +181,7 @@ public class IrisGenerator extends IrisRegistrant {
if (!Double.isFinite(surfaceDetail) || surfaceDetail < 0D || surfaceDetail > 1D) {
throw new IllegalArgumentException("Generator surfaceDetail must be finite and between 0 and 1");
}
requireValidExponent();
if (composite.isEmpty()) {
return 0D;
}
@@ -204,6 +208,7 @@ public class IrisGenerator extends IrisRegistrant {
if (!Double.isFinite(surfaceDetail) || surfaceDetail < 0D || surfaceDetail > 1D) {
throw new IllegalArgumentException("Generator surfaceDetail must be finite and between 0 and 1");
}
requireValidExponent();
if (!supportsBatch()) {
throw new IllegalStateException("Generator " + getLoadKey() + " cannot be compiled into a batch program");
}
@@ -298,7 +303,8 @@ public class IrisGenerator extends IrisRegistrant {
}
}
double v = multiplicitive ? h * opacity : (h / tp) * opacity;
double combined = multiplicitive ? h : h / tp;
double v = applyExponent(combined, exponent) * opacity;
if (Double.isNaN(v)) {
v = 0;
@@ -310,6 +316,20 @@ public class IrisGenerator extends IrisRegistrant {
return v;
}
static double applyExponent(double value, double exponent) {
if (exponent == 1) {
return value;
}
return value < 0 ? -Math.pow(-value, exponent) : Math.pow(value, exponent);
}
private void requireValidExponent() {
if (!Double.isFinite(exponent) || exponent <= 0D) {
throw new IllegalArgumentException("Generator exponent must be finite and above 0");
}
}
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, runtime);
@@ -83,6 +83,8 @@ public class IrisGeneratorStyle {
@MaxNumber(8192)
@Description("If the cache size is set above 0, this generator will be cached")
private int cacheSize = 0;
@Description("Rolls this noise from the world seed and this number, so every style with the same seed shares one noise. Child biomes, palettes and decorator placement read a seeded style flat in blocks: zoom is its only scale, so a layer's zoom, childShrinkFactor and the decorator's extra zoom don't apply.")
private Long seed = null;
public IrisGeneratorStyle(NoiseStyle s) {
this.style = s;
@@ -119,7 +121,34 @@ public class IrisGeneratorStyle {
}
private int hash() {
return Objects.hash(expression, imageMapHash(), multiplier, fracture != null ? fracture.hash() : 0, exponent, cacheSize, zoom, cellularZoom, cellularFrequency, style == null ? null : style.name());
int unseededHash = Objects.hash(expression, imageMapHash(), multiplier, fracture != null ? fracture.hash() : 0, exponent, cacheSize, zoom, cellularZoom, cellularFrequency, style == null ? null : style.name());
return isSeeded() ? Objects.hash(unseededHash, seed) : unseededHash;
}
public boolean isSeeded() {
return seed != null;
}
/** The random a style is built from: the caller's, or for a seeded style one rolled from its seed and the world seed. */
public RNG rollFor(RNG callerRandom, Engine engine) {
if (!isSeeded()) {
return callerRandom;
}
return new RNG(rolledSeed(engine));
}
private long rolledSeed(Engine engine) {
long worldSeed = engine == null ? 0L : engine.getSeedManager().getSeed();
return splitMix(worldSeed ^ splitMix(seed));
}
// Spreads nearby seed numbers far apart; Iris's own seed forking only adds.
private static long splitMix(long value) {
long mixed = value + 0x9E3779B97F4A7C15L;
mixed = (mixed ^ (mixed >>> 30)) * 0xBF58476D1CE4E5B9L;
mixed = (mixed ^ (mixed >>> 27)) * 0x94D049BB133111EBL;
return mixed ^ (mixed >>> 31);
}
public int prebakeSignature() {
@@ -163,10 +192,11 @@ public class IrisGeneratorStyle {
}
}
private CNG createNoCache(RNG rng, PackRuntime runtime, int octaveMultiplier, int fallbackCacheSize,
private CNG createNoCache(RNG callerRandom, PackRuntime runtime, int octaveMultiplier, int fallbackCacheSize,
boolean quietCacheLog) {
IrisData data = runtime.data();
Engine engine = runtime.engine();
RNG rng = rollFor(callerRandom, engine);
requirePositiveFinite("zoom", zoom);
requirePositiveFinite("exponent", exponent);
if (!Double.isFinite(cellularFrequency) || cellularFrequency < 0D) {
@@ -231,8 +261,8 @@ public class IrisGeneratorStyle {
return create(rng.getSeed(), runtime);
}
public CNG create(long seed, PackRuntime runtime) {
return runtime.styleGenerator(this, seed);
public CNG create(long callerSeed, PackRuntime runtime) {
return runtime.styleGenerator(this, isSeeded() ? rolledSeed(runtime.engine()) : callerSeed);
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
@@ -269,9 +269,13 @@ public final class DimensionTerrainContext implements DataProvider {
Interpolated.of(value -> 0D, value -> focusBiome.getInferredType())
);
boolean sealessRegions = IrisComplex.lacks(preparedBiomeStreams, InferredType.SEA);
ProceduralStream<IrisBiome> proceduralBaseBiomeStream = focusBiome == null
? bridgeStream
.convertAware2D((type, x, z) -> {
.convertAware2D((continent, x, z) -> {
InferredType type = sealessRegions
? IrisComplex.baseType(preparedBiomeStreams, regionStream.get(x, z), continent)
: continent;
ProceduralStream<IrisBiome> stream = inferredStreams.get(type);
return stream != null
? stream.get(x, z)
@@ -536,13 +540,17 @@ public final class DimensionTerrainContext implements DataProvider {
IrisRegion region,
InferredType type
) {
if ((type == InferredType.SEA || type == InferredType.SHORE) && loadInferredBiomes(runtime.data(), biomeKeys(region, type), type).isEmpty()) {
return IrisComplex.NO_BIOMES;
}
return switch (type) {
case LAND -> dimension.getLandBiomeStyle()
.create(rng.nextParallelRNG(InferredType.LAND.ordinal()), runtime).stream()
.zoom(dimension.getBiomeZoom())
.zoom(dimension.getLandZoom())
.zoom(region.getLandBiomeZoom())
.selectRarity(loadInferredBiomes(runtime.data(), region.getLandBiomes(), InferredType.LAND));
.selectRarity(IrisComplex.requireLandBiomes(region,
loadInferredBiomes(runtime.data(), region.getLandBiomes(), InferredType.LAND)));
case SEA -> dimension.getSeaBiomeStyle()
.create(rng.nextParallelRNG(InferredType.SEA.ordinal()), runtime).stream()
.zoom(dimension.getBiomeZoom())
@@ -558,6 +566,10 @@ public final class DimensionTerrainContext implements DataProvider {
};
}
private static KList<String> biomeKeys(IrisRegion region, InferredType type) {
return type == InferredType.SEA ? region.getSeaBiomes() : region.getShoreBiomes();
}
private static KList<IrisBiome> loadInferredBiomes(
IrisData data,
KList<String> keys,
@@ -154,6 +154,12 @@ public class IrisComplex implements DataProvider {
InferredType.SEA,
InferredType.SHORE
};
/**
* The biome stream of a sea or shore list a region leaves empty. It answers null everywhere, which tells the
* surface resolution to keep the column's own biome instead of converting it.
*/
static final ProceduralStream<IrisBiome> NO_BIOMES = ProceduralStream.of((x, z) -> null,
Interpolated.of(value -> 0D, value -> null));
@Getter(AccessLevel.NONE)
private final transient ThreadSlots<GridBoundsCache> gridBoundsCache = new ThreadSlots<>(GridBoundsCache::new);
@Getter(AccessLevel.NONE)
@@ -206,6 +212,8 @@ public class IrisComplex implements DataProvider {
private ProceduralStream<Double> regionStyleStream;
private ProceduralStream<Double> regionIdentityStream;
private ProceduralStream<InferredType> bridgeStream;
@Getter(AccessLevel.NONE)
private ProceduralStream<InferredType> baseTypeStream;
private ProceduralStream<IrisBiome> landBiomeStream;
private ProceduralStream<IrisBiome> caveBiomeStream;
private ProceduralStream<IrisBiome> seaBiomeStream;
@@ -455,9 +463,15 @@ public class IrisComplex implements DataProvider {
bridgeStream = focusedBiomes != null ? focusedBiomes.convert(IrisBiome::getInferredType) :
ContinentGenerator.create(engine.getDimension(), rng, packRuntime).stream()
.convert((v) -> v >= engine.getDimension().getLandChance() ? InferredType.SEA : InferredType.LAND);
// A region without sea biomes picks its continental sea from its land biomes.
baseTypeStream = focusedBiomes != null || !lacks(inferredBiomeStreams, InferredType.SEA) ? bridgeStream
: ProceduralStream.of(
(x, z) -> baseType(inferredBiomeStreams, contextRegionStream.get(x, z), bridgeStream.get(x, z)),
(x, y, z) -> baseType(inferredBiomeStreams, contextRegionStream.get(x, z), bridgeStream.get(x, y, z)),
Interpolated.of(value -> 0D, value -> null));
ProceduralStream<IrisBiome> proceduralBaseBiomeStream = focusedBiomes != null ? focusedBiomes
: ProceduralStream.of(this::proceduralBaseBiome,
(x, y, z) -> implode(inferredByType.get(bridgeStream.get(x, y, z)).get(x, z), x, z),
(x, y, z) -> implode(inferredByType.get(baseTypeStream.get(x, y, z)).get(x, z), x, z),
Interpolated.of(value -> 0D, value -> null));
baseBiomeSource = focusedBiomes != null || !imageMapRuntime.has(IrisImageMapApplication.BIOME)
? proceduralBaseBiomeStream : ProceduralStream.of((x, z) -> {
@@ -1067,7 +1081,7 @@ public class IrisComplex implements DataProvider {
}
private IrisBiome proceduralBaseBiome(double x, double z) {
return implode(inferredByType.get(bridgeStream.get(x, z)).get(x, z), x, z);
return implode(inferredByType.get(baseTypeStream.get(x, z)).get(x, z), x, z);
}
private final class BakeSource implements PlaneSource {
@@ -1168,9 +1182,53 @@ public class IrisComplex implements DataProvider {
InferredType inferredType,
IrisBiome emptyBiome
) {
ProceduralStream<IrisBiome> picked = new RarityStream<>(biomePickNoiseStream(engine.getDimension(), region, inferredType),
loadInferredBiomes(biomeKeys(region, inferredType), inferredType));
return inferredType == InferredType.CAVE ? picked.onNull(emptyBiome) : picked;
ProceduralStream<Double> noise = biomePickNoiseStream(engine.getDimension(), region, inferredType);
KList<IrisBiome> biomes = loadInferredBiomes(biomeKeys(region, inferredType), inferredType);
return switch (inferredType) {
case CAVE -> new RarityStream<>(noise, biomes).onNull(emptyBiome);
case LAND -> new RarityStream<>(noise, requireLandBiomes(region, biomes));
case SEA, SHORE -> biomes.isEmpty() ? NO_BIOMES : new RarityStream<>(noise, biomes);
};
}
/**
* Every region needs a land biome: the surface falls back to land wherever it leaves sea or shore, and a region
* without sea biomes picks its continental sea from land too.
*/
static KList<IrisBiome> requireLandBiomes(IrisRegion region, KList<IrisBiome> landBiomes) {
if (!landBiomes.isEmpty()) {
return landBiomes;
}
String regionKey = region.getLoadKey() == null || region.getLoadKey().isBlank() ? "<unkeyed>" : region.getLoadKey();
throw new IllegalStateException(region.getLandBiomes().isEmpty()
? "Region '" + regionKey + "' has no landBiomes; every region needs at least one land biome."
: "Region '" + regionKey + "' has no landBiomes this Minecraft version can generate; every listed land biome is excluded.");
}
/** Whether any prepared region left the given biome list empty. */
static boolean lacks(Map<IrisRegion, Map<InferredType, ProceduralStream<IrisBiome>>> streams, InferredType inferredType) {
for (Map<InferredType, ProceduralStream<IrisBiome>> regionStreams : streams.values()) {
if (regionStreams.get(inferredType) == NO_BIOMES) {
return true;
}
}
return false;
}
/** The biome list a spot's base biome comes from: the continent's choice, or land where the region has no sea. */
static InferredType baseType(
Map<IrisRegion, Map<InferredType, ProceduralStream<IrisBiome>>> streams,
IrisRegion region,
InferredType continent
) {
return continent == InferredType.SEA && preparedInferredBiomeStream(streams, region, InferredType.SEA) == NO_BIOMES
? InferredType.LAND
: continent;
}
/** The biome list the given region picks this spot's base biome from. */
public InferredType baseTypeIn(IrisRegion region, double x, double z) {
return baseTypeStream == bridgeStream ? bridgeStream.get(x, z) : baseType(inferredBiomeStreams, region, bridgeStream.get(x, z));
}
private ProceduralStream<Double> biomePickNoiseStream(IrisDimension dimension, IrisRegion region, InferredType inferredType) {
@@ -1252,7 +1310,7 @@ public class IrisComplex implements DataProvider {
if (focusBiome != null) {
return new BiomePick(focusBiome, focusBiome.getInferredType());
}
InferredType type = bridgeStream.get(x, z);
InferredType type = baseTypeIn(region, x, z);
return new BiomePick(implode(createInferredBiomeStream(region, type).get(x, z), x, z), type);
}
@@ -1924,7 +1982,7 @@ public class IrisComplex implements DataProvider {
if (height >= fluidHeight - 1 && !biome.isShore()) {
if (!aboveShoreBand(height, region, x, z, fluidHeight, shoreSlopes)) {
return shoreBiomes.get(x, z);
return convertedOrKept(shoreBiomes.get(x, z), biome);
}
if (!biome.isLand()) {
return landBiomes.get(x, z);
@@ -1934,16 +1992,21 @@ public class IrisComplex implements DataProvider {
}
if (height < fluidHeight && !biome.isAquatic()) {
return seaBiomes.get(x, z);
return convertedOrKept(seaBiomes.get(x, z), biome);
}
if (height == fluidHeight && !biome.isShore()) {
return shoreBiomes.get(x, z);
return convertedOrKept(shoreBiomes.get(x, z), biome);
}
return biome;
}
// A null conversion comes from NO_BIOMES: the region lists no biomes of that type, so the column keeps its own.
private static IrisBiome convertedOrKept(IrisBiome converted, IrisBiome biome) {
return converted == null ? biome : converted;
}
private double interpolateGenerators(Engine engine, IrisInterpolator interpolator, int interpolatorIndex, IrisGenerator[] generators, double x, double z, long seed) {
if (generators.length == 0) {
return 0;
@@ -2536,7 +2599,7 @@ public class IrisComplex implements DataProvider {
private List<IrisBiome> childLineage(IrisBiome biome, int x, int z) {
IrisBiome[] rootFirst = new IrisBiome[IrisBiome.CHILD_HOPS + 1];
IrisBiome current = inferredByType.get(bridgeStream.get(x, z)).get(x, z);
IrisBiome current = inferredByType.get(baseTypeStream.get(x, z)).get(x, z);
rootFirst[0] = current;
int size = 1;
for (int hop = 0; hop < IrisBiome.CHILD_HOPS && !current.getChildren().isEmpty(); hop++) {
@@ -2885,7 +2948,7 @@ public class IrisComplex implements DataProvider {
if (constant != null) {
return constant;
}
InferredType type = pick != null ? pick.type() : complex.bridgeStream.get(x, z);
InferredType type = pick != null ? pick.type() : complex.baseTypeIn(region, x, z);
constant = constants == null ? null : constants.typed(type, group);
if (constant != null) {
return constant;
@@ -102,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(), runtime));
generated.add(layer.get(random.nextParallelRNG(i + j), (wx + j) / layer.blocksPerSample(), j, (wz - j) / layer.blocksPerSample(), runtime));
} catch (Throwable e) {
GenerationFailures.skipPlacement(e, "surface layer", "block", (int) wx, -1, (int) wz, "floating");
}
@@ -85,7 +85,7 @@ public class IrisDimensionCarvingEntry {
}
public CNG createChildrenGenerator(long childrenGeneratorSeed, PackRuntime runtime) {
return getChildStyle().createScaledGenerator(deriveChildStyleSeed(childrenGeneratorSeed), runtime, childShrinkFactor());
return getChildStyle().createScaledGenerator(deriveChildStyleSeed(childrenGeneratorSeed), runtime, childScale());
}
long deriveChildrenGeneratorSeed(long worldSeed) {
@@ -96,7 +96,11 @@ public class IrisDimensionCarvingEntry {
return new RNG(childrenGeneratorSeed).nextParallelRNG(CHILDREN_SEED_SALT);
}
private double childShrinkFactor() {
private double childScale() {
if (getChildStyle().isSeeded()) {
return 1;
}
return Math.max(MINIMUM_CHILD_SHRINK_FACTOR, getChildShrinkFactor());
}
@@ -85,10 +85,15 @@ public class IrisMaterialPalette implements StructurePalette {
return localBlockData.get(0);
}
CNG generator = getLayerGenerator(rng, runtime);
if (style.isSeeded()) {
return generator.fit(localBlockData, x, z);
}
double scaledX = x / zoom;
double scaledY = y / zoom;
double scaledZ = z / zoom;
return getLayerGenerator(rng, runtime).fit(localBlockData, scaledX, scaledY, scaledZ);
return generator.fit(localBlockData, scaledX, scaledY, scaledZ);
}
public Optional<TileData> getTile(RNG rng, double x, double y, double z, IrisData rdata) {
@@ -39,6 +39,8 @@ final class PackDimensionValidator {
private static final String STYLE_SNIPPET_TYPE = "style";
private static final String RANGE_SNIPPET_TYPE = "range";
private static final Pattern RESOURCE_KEY = Pattern.compile("[a-z0-9_.-]+:[a-z0-9/._-]+");
private static final int VANILLA_OVERWORLD_MIN_Y = -64;
private static final int VANILLA_OVERWORLD_MAX_Y = 320;
private PackDimensionValidator() {
}
@@ -63,6 +65,7 @@ final class PackDimensionValidator {
}
validateImportedStructurePolicy(dimensionKey, dimJson, blockingErrors, warnings);
validateImportedFeatureHeight(packFolder, dimensionKey, dimJson, warnings);
validateDimensionHeights(packFolder, dimensionKey, dimJson, blockingErrors);
validateBorrowedDimensionType(dimensionKey, dimJson, borrowedDimensionTypesSupported(), blockingErrors);
validateSamplingStep(dimensionKey, dimJson, "terrainSamplingStep", 1, blockingErrors);
@@ -101,12 +104,13 @@ final class PackDimensionValidator {
continue;
}
int anyBiome = countBiomeRefs(regionJson, "landBiomes", biomesFolder, regionKey, warnings)
+ countBiomeRefs(regionJson, "seaBiomes", biomesFolder, regionKey, warnings)
+ countBiomeRefs(regionJson, "shoreBiomes", biomesFolder, regionKey, warnings)
+ countBiomeRefs(regionJson, "caveBiomes", biomesFolder, regionKey, warnings);
if (anyBiome == 0) {
blockingErrors.add("Region '" + regionKey + "' has no resolvable biomes.");
// Sea, shore and cave lists may be empty; land is what every other list falls back to.
int landBiomes = countBiomeRefs(regionJson, "landBiomes", biomesFolder, regionKey, warnings);
countBiomeRefs(regionJson, "seaBiomes", biomesFolder, regionKey, warnings);
countBiomeRefs(regionJson, "shoreBiomes", biomesFolder, regionKey, warnings);
countBiomeRefs(regionJson, "caveBiomes", biomesFolder, regionKey, warnings);
if (landBiomes == 0) {
blockingErrors.add("Region '" + regionKey + "' has no landBiomes; every region needs at least one land biome.");
}
resolvedRegions++;
}
@@ -278,6 +282,24 @@ final class PackDimensionValidator {
}
}
static void validateImportedFeatureHeight(File packFolder, String dimensionKey, JSONObject dimension,
List<String> warnings) {
JSONObject importedFeatures = dimension.optJSONObject("importedFeatures");
if (importedFeatures == null || !importedFeatures.optBoolean("enabled", false)) {
return;
}
JSONObject height = resolveDimensionHeight(packFolder, dimension);
int minY = height == null ? VANILLA_OVERWORLD_MIN_Y : (int) height.optDouble("min", 16D);
int maxY = height == null ? VANILLA_OVERWORLD_MAX_Y : (int) height.optDouble("max", 32D);
// Vanilla anchors ore bands to the world bottom and top, so any height other than -64..320 moves them.
if (minY == VANILLA_OVERWORLD_MIN_Y && maxY == VANILLA_OVERWORLD_MAX_Y) {
return;
}
warnings.add("Dimension '" + dimensionKey + "' runs importedFeatures in a " + minY + ".." + maxY
+ " world. Vanilla ores shift with the height; remove them with importedFeatures.disabled"
+ " (minecraft:ore) or disabledSteps (UNDERGROUND_ORES).");
}
static void validateStaticObjects(File packFolder, String dimensionKey, JSONObject dimension,
List<String> blockingErrors) {
if (!dimension.has("staticObjects")) {
@@ -211,6 +211,7 @@ public final class PackValidator {
applyCompatFindings(minecraftVersion, dimensions.anyExcluded(), findings, blockingErrors, warnings);
applyRequireAllContent(packFolder.getName(), dimensions.reachedByRequiringDimension(),
minecraftVersion, findings, blockingErrors);
addDistinct(blockingErrors, excludedLandErrors(data, dimensions.regionKeys(), minecraftVersion));
return findings;
} catch (Throwable e) {
IrisLogging.reportError("Version-content gating failed for pack '" + packFolder.getName() + "'", e);
@@ -239,6 +240,7 @@ public final class PackValidator {
private static GatedDimensions loadEverything(File packFolder, IrisData data, File[] dimensionFiles) {
boolean dimensionExcluded = false;
Map<String, Set<String>> reachedByRequiringDimension = new LinkedHashMap<>();
Set<String> regionKeys = new LinkedHashSet<>();
List<String> folders = data.getLoaders().values().stream().map(ResourceLoader::getFolderName).toList();
File dimensionsFolder = new File(packFolder, DIMENSIONS_FOLDER);
for (File dimensionFile : dimensionFiles) {
@@ -249,6 +251,8 @@ public final class PackValidator {
}
if (dimension.isCompatExcluded()) {
dimensionExcluded = true;
} else {
regionKeys.addAll(dimension.getRegions());
}
if (dimension.isRequireAllContent()) {
reachedByRequiringDimension.put(dimension.getLoadKey(), PackContentReach.referencedFrom(
@@ -271,10 +275,31 @@ public final class PackValidator {
for (IrisObjectPlacement placement : placements) {
placement.evaluateCompat(data);
}
return new GatedDimensions(dimensionExcluded, reachedByRequiringDimension);
return new GatedDimensions(dimensionExcluded, reachedByRequiringDimension, regionKeys);
}
private record GatedDimensions(boolean anyExcluded, Map<String, Set<String>> reachedByRequiringDimension) {
private record GatedDimensions(boolean anyExcluded, Map<String, Set<String>> reachedByRequiringDimension,
Set<String> regionKeys) {
}
/**
* A region whose land biomes the version-content gate excluded cannot generate. Regions that list no land biome
* at all are already reported by {@link PackDimensionValidator}.
*/
private static List<String> excludedLandErrors(IrisData data, Collection<String> regionKeys, String minecraftVersion) {
List<String> errors = new ArrayList<>();
for (String regionKey : regionKeys) {
IrisRegion region = data.getRegionLoader().load(regionKey, false);
if (region == null || region.isCompatExcluded()) {
continue;
}
List<IrisBiome> land = data.getBiomeLoader().loadAll(region.getLandBiomes());
if (!land.isEmpty() && land.stream().allMatch(IrisBiome::isCompatExcluded)) {
errors.add("Region '" + regionKey + "' has no landBiomes Minecraft " + versionOrUnknown(minecraftVersion)
+ " can generate; every listed land biome is excluded.");
}
}
return errors;
}
private static void collectPlacements(IrisRegistrant registrant, Set<IrisObjectPlacement> out) {
@@ -8,6 +8,7 @@ import art.arcane.iris.generation.noise.IrisStyledRange;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ir.CostClass;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.NoiseDef;
import art.arcane.iris.pack.datapack.export.lower.ExportCapabilities;
@@ -23,6 +24,7 @@ import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
@@ -37,6 +39,8 @@ public final class NoiseStyleCompiler implements StyleCompiler {
private final CellularStyleLowering cellular;
private final StyleCompiler selectors;
private final List<ExportDiagnostic> diagnostics;
private final Set<String> reportedSeeds = ConcurrentHashMap.newKeySet();
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);
@@ -44,17 +48,20 @@ public final class NoiseStyleCompiler implements StyleCompiler {
public NoiseStyleCompiler(CellularStyleLowering cellular) {
this.cellular = Objects.requireNonNull(cellular, "cellular");
this.selectors = this;
this.diagnostics = null;
}
private NoiseStyleCompiler(Function<StyleCompiler, CellularStyleLowering> cellular, StyleCompiler selectors) {
private NoiseStyleCompiler(Function<StyleCompiler, CellularStyleLowering> cellular, StyleCompiler selectors,
List<ExportDiagnostic> diagnostics) {
this.cellular = Objects.requireNonNull(cellular.apply(this), "cellular");
this.selectors = selectors == null ? this : selectors;
this.diagnostics = diagnostics;
}
public static NoiseStyleCompiler create(List<ExportDiagnostic> diagnostics) {
Objects.requireNonNull(diagnostics, "diagnostics");
NoiseStyleCompiler selectors = new NoiseStyleCompiler(nested -> new DefaultCellularStyleLowering(diagnostics, nested::compile, CellularMode.QUADRANT_2X2), null);
return new NoiseStyleCompiler(nested -> new DefaultCellularStyleLowering(diagnostics, nested::compile, CellularMode.GRID_3X3), selectors);
NoiseStyleCompiler selectors = new NoiseStyleCompiler(nested -> new DefaultCellularStyleLowering(diagnostics, nested::compile, CellularMode.QUADRANT_2X2), null, diagnostics);
return new NoiseStyleCompiler(nested -> new DefaultCellularStyleLowering(diagnostics, nested::compile, CellularMode.GRID_3X3), selectors, diagnostics);
}
public static CNG generator(IrisGeneratorStyle style) {
@@ -67,6 +74,14 @@ public final class NoiseStyleCompiler implements StyleCompiler {
return style(Objects.requireNonNull(style, "style"), 1, Domain.IDENTITY, emit, "s");
}
private void reportSeed(IrisGeneratorStyle style) {
if (diagnostics == null || style == null || !style.isSeeded() || !reportedSeeds.add(String.valueOf(style.getSeed()))) {
return;
}
diagnostics.add(new ExportDiagnostic(ExportDiagnostic.Severity.WARNING, ExportLimit.NOISE_STYLE, "",
"Noise style seed " + style.getSeed() + " is not exported; the style uses its exported salt instead"));
}
@Override
public StyleCompiler selectors() {
return selectors;
@@ -182,6 +197,7 @@ public final class NoiseStyleCompiler implements StyleCompiler {
}
private Field style(IrisGeneratorStyle style, int octaveMultiplier, Domain domain, Emit emit, String path) {
reportSeed(style);
IrisGeneratorStyle prepared = prepared(Objects.requireNonNull(style, "noise style"), domain.zoom());
String stylePath = path + "/" + styleName(style);
CNG root = build(prepared, octaveMultiplier, runtime);
@@ -101,6 +101,9 @@ public final class GeneratorCompiler {
}
public Field style(IrisGeneratorStyle style, double zoom, String path) {
if (style != null && style.isSeeded()) {
report(path, "Noise style seed " + style.getSeed() + " is not exported; the style uses its exported salt instead");
}
return styles.compile(zoomed(style, zoom), salt(path), registry, capabilities);
}
@@ -119,6 +122,9 @@ public final class GeneratorCompiler {
if (generator.hasCliffs()) {
value = new Field.Round(Field.RoundMode.ROUND, value, cliffStep(generator, root, path, resource, name));
}
if (generator.getExponent() != 1.0) {
report(resource, "Generator exponent " + generator.getExponent() + " is not exported; the uncurved height is used");
}
if (generator.getCellFractureHeight() != 0.0) {
report(resource, "Generator cell fracture is not exported; the unfractured height is used");
}
@@ -143,7 +143,7 @@ public class DataFixerV1217 extends DataFixerV1213 {
attributes.put("minecraft:gameplay/bed_rule", new JSONObject()
.put("can_set_spawn", "never")
.put("can_sleep", "never")
.put("explodes", true));
.put("destroy_on_use", true));
}
attributes.put("minecraft:gameplay/respawn_anchor_works", json.remove("respawn_anchor_works"));
@@ -63,14 +63,14 @@ public class ImageResourceLoader extends ResourceLoader<IrisImage> {
PrecisionStopwatch p = PrecisionStopwatch.start();
try (ImageInputStream input = ImageIO.createImageInputStream(j)) {
if (input == null) {
IrisLogging.warn("Couldn't read " + resourceTypeName + " file: " + j.getPath()
+ " (unsupported or corrupt image)");
warnReadFailureOnce(j, "Couldn't read " + resourceTypeName + " file: " + j.getPath()
+ " (unsupported or corrupt image)", null);
return null;
}
Iterator<ImageReader> readers = ImageIO.getImageReaders(input);
if (!readers.hasNext()) {
IrisLogging.warn("Couldn't read " + resourceTypeName + " file: " + j.getPath()
+ " (unsupported or corrupt image)");
warnReadFailureOnce(j, "Couldn't read " + resourceTypeName + " file: " + j.getPath()
+ " (unsupported or corrupt image)", null);
return null;
}
ImageReader reader = readers.next();
@@ -78,21 +78,21 @@ public class ImageResourceLoader extends ResourceLoader<IrisImage> {
reader.setInput(input, true, true);
String format = reader.getFormatName().toLowerCase(Locale.ROOT);
if (!"png".equals(format)) {
IrisLogging.warn("Couldn't read " + resourceTypeName + " file: " + j.getPath()
+ " (expected PNG, got " + format + ")");
warnReadFailureOnce(j, "Couldn't read " + resourceTypeName + " file: " + j.getPath()
+ " (expected PNG, got " + format + ")", null);
return null;
}
int width = reader.getWidth(0);
int height = reader.getHeight(0);
if (!supportedDimensions(width, height)) {
IrisLogging.warn("Couldn't read " + resourceTypeName + " file: " + j.getPath()
+ " (dimensions " + width + "x" + height + " exceed the supported image-map limits)");
warnReadFailureOnce(j, "Couldn't read " + resourceTypeName + " file: " + j.getPath()
+ " (dimensions " + width + "x" + height + " exceed the supported image-map limits)", null);
return null;
}
BufferedImage image = reader.read(0);
if (image == null) {
IrisLogging.warn("Couldn't read " + resourceTypeName + " file: " + j.getPath()
+ " (unsupported or corrupt image)");
warnReadFailureOnce(j, "Couldn't read " + resourceTypeName + " file: " + j.getPath()
+ " (unsupported or corrupt image)", null);
return null;
}
IrisImage loaded = new IrisImage(image, format);
@@ -107,8 +107,7 @@ public class ImageResourceLoader extends ResourceLoader<IrisImage> {
}
}
} catch (Throwable e) {
IrisLogging.reportError(e);
IrisLogging.warn("Couldn't read " + resourceTypeName + " file: " + j.getPath() + ": " + e.getMessage());
warnReadFailureOnce(j, "Couldn't read " + resourceTypeName + " file: " + j.getPath() + ": " + e.getMessage(), e);
return null;
}
}
@@ -180,7 +179,7 @@ public class ImageResourceLoader extends ResourceLoader<IrisImage> {
return null;
}
if (name.equals("null")) {
IrisLogging.warn("Refusing " + resourceTypeName + " lookup for literal string \"null\" (called by " + callerHint() + ")");
warnLiteralNullOnce("lookup");
return null;
}
@@ -190,7 +189,7 @@ public class ImageResourceLoader extends ResourceLoader<IrisImage> {
return file;
}
IrisLogging.warn("Couldn't find " + resourceTypeName + ": " + name + " (called by " + callerHint() + ")");
warnMissingOnce(name);
return null;
}
@@ -206,7 +205,7 @@ public class ImageResourceLoader extends ResourceLoader<IrisImage> {
return loadFile(file, name);
}
IrisLogging.warn("Couldn't find " + resourceTypeName + ": " + name + " (called by " + callerHint() + ")");
warnMissingOnce(name);
return null;
}
@@ -216,7 +215,7 @@ public class ImageResourceLoader extends ResourceLoader<IrisImage> {
return null;
}
if (name.equals("null") && warn) {
IrisLogging.warn("Refusing " + resourceTypeName + " load for literal string \"null\" (called by " + callerHint() + ")");
warnLiteralNullOnce("load");
return null;
}
return loadCache.get(name);
@@ -121,6 +121,8 @@ import java.util.concurrent.ConcurrentHashMap;
@Data
public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
private static final int CUSTOM_BIOME_KEY_CACHE_LIMIT = 4096;
private static final String PACK_ONCE_KEY_PREFIX = "pack|";
private static final String PACK_ONCE_KEY_SEPARATOR = "|";
private static final Map<File, IrisData> dataLoaders = new ConcurrentHashMap<>();
// Loaders (cached or detached) that currently have registered engines; see hasActiveEngines.
// Identity-keyed on purpose: Lombok's @Data hashCode over this class's mutable loader state
@@ -741,6 +743,8 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
}
public synchronized void hotloaded() {
// Studio hotload reopens or rebuilds the pack through here without ever calling clearLists().
IrisLogging.forgetOnceKeys(onceKeyPrefix());
blockDropMaterials = null;
StructureGraphCatalog.invalidate(this);
IrisObjectScale.invalidate(this);
@@ -863,7 +867,28 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
throw failure;
}
/**
* Prefix shared by every warn-once key that belongs to this pack, so {@link #clearLists()} can forget
* them together. The trailing separator keeps {@code /packs/a} from matching {@code /packs/ab}.
*/
public String onceKeyPrefix() {
return PACK_ONCE_KEY_PREFIX + dataFolder.getAbsolutePath() + PACK_ONCE_KEY_SEPARATOR;
}
public String onceKey(String kind, String detail) {
return onceKeyPrefix() + kind + PACK_ONCE_KEY_SEPARATOR + detail;
}
/**
* Key for a warning whose site may not know its pack: scoped to the pack when there is one so a
* hotload forgets it, otherwise a plain stable key.
*/
public static String onceKey(IrisData data, String kind, String detail) {
return data == null ? kind + PACK_ONCE_KEY_SEPARATOR + detail : data.onceKey(kind, detail);
}
public void clearLists() {
IrisLogging.forgetOnceKeys(onceKeyPrefix());
blockDropMaterials = null;
for (ResourceLoader<?> i : loaders.values()) {
i.clearList();
@@ -58,8 +58,7 @@ public class MatterObjectResourceLoader extends ResourceLoader<IrisMatterObject>
tlt.addAndGet(p.getMilliseconds());
return t;
} catch (Throwable e) {
IrisLogging.reportError(e);
IrisLogging.warn("Couldn't read " + resourceTypeName + " file: " + j.getPath() + ": " + e.getMessage());
warnReadFailureOnce(j, "Couldn't read " + resourceTypeName + " file: " + j.getPath() + ": " + e.getMessage(), e);
return null;
}
}
@@ -120,7 +119,7 @@ public class MatterObjectResourceLoader extends ResourceLoader<IrisMatterObject>
return null;
}
if (name.equals("null")) {
IrisLogging.warn("Refusing " + resourceTypeName + " lookup for literal string \"null\" (called by " + callerHint() + ")");
warnLiteralNullOnce("lookup");
return null;
}
@@ -130,7 +129,7 @@ public class MatterObjectResourceLoader extends ResourceLoader<IrisMatterObject>
return file;
}
IrisLogging.warn("Couldn't find " + resourceTypeName + ": " + name + " (called by " + callerHint() + ")");
warnMissingOnce(name);
return null;
}
@@ -146,7 +145,7 @@ public class MatterObjectResourceLoader extends ResourceLoader<IrisMatterObject>
return loadFile(file, name);
}
IrisLogging.warn("Couldn't find " + resourceTypeName + ": " + name + " (called by " + callerHint() + ")");
warnMissingOnce(name);
return null;
}
@@ -156,7 +155,7 @@ public class MatterObjectResourceLoader extends ResourceLoader<IrisMatterObject>
return null;
}
if (name.equals("null") && warn) {
IrisLogging.warn("Refusing " + resourceTypeName + " load for literal string \"null\" (called by " + callerHint() + ")");
warnLiteralNullOnce("load");
return null;
}
return loadCache.get(name);
@@ -60,13 +60,12 @@ public class ObjectResourceLoader extends ResourceLoader<IrisObject> {
tlt.addAndGet(p.getMilliseconds());
return t;
} catch (Throwable e) {
IrisLogging.reportError(e);
String message = e.getMessage();
String reason = e.getClass().getSimpleName();
if (message != null && !message.isBlank()) {
reason = reason + ": " + message;
}
IrisLogging.warn("Couldn't read " + resourceTypeName + " file: " + j.getPath() + " (" + reason + ")");
warnReadFailureOnce(j, "Couldn't read " + resourceTypeName + " file: " + j.getPath() + " (" + reason + ")", e);
return null;
}
}
@@ -127,7 +126,7 @@ public class ObjectResourceLoader extends ResourceLoader<IrisObject> {
return null;
}
if (name.equals("null")) {
IrisLogging.warn("Refusing " + resourceTypeName + " lookup for literal string \"null\" (called by " + callerHint() + ")");
warnLiteralNullOnce("lookup");
return null;
}
@@ -137,7 +136,7 @@ public class ObjectResourceLoader extends ResourceLoader<IrisObject> {
return file;
}
IrisLogging.warn("Couldn't find " + resourceTypeName + ": " + name + " (called by " + callerHint() + ")");
warnMissingOnce(name);
return null;
}
@@ -156,12 +155,12 @@ public class ObjectResourceLoader extends ResourceLoader<IrisObject> {
return null;
}
if (name.equals("null") && warn) {
IrisLogging.warn("Refusing " + resourceTypeName + " load for literal string \"null\" (called by " + callerHint() + ")");
warnLiteralNullOnce("load");
return null;
}
IrisObject result = loadCache.get(name);
if (result == null && warn) {
IrisLogging.warn("Couldn't find " + resourceTypeName + ": " + name + " (called by " + callerHint() + ")");
warnMissingOnce(name);
}
return result;
}
@@ -91,6 +91,9 @@ public class ResourceLoader<T extends IrisRegistrant> implements MeteredCache {
private static final int PREFETCH_ENTRY_LIMIT = 1_024;
private static final int PREFETCH_KEY_LENGTH_LIMIT = 1_024;
private static final long PREFETCH_FILE_SIZE_LIMIT = 4L * 1_024L * 1_024L;
private static final String MISSING_KEY_KIND = "missing:";
private static final String LITERAL_NULL_KEY_KIND = "literal-null:";
private static final String READ_KEY_KIND = "read:";
private static volatile ExecutorService schemaBuildExecutor;
private static final Set<String> schemaBuildQueue = ConcurrentHashMap.newKeySet();
protected final AtomicCache<KList<File>> folderCache;
@@ -217,7 +220,7 @@ public class ResourceLoader<T extends IrisRegistrant> implements MeteredCache {
return null;
}
if (name.equals("null")) {
IrisLogging.warn("Refusing " + resourceTypeName + " lookup for literal string \"null\" (called by " + callerHint() + ")");
warnLiteralNullOnce("lookup");
return null;
}
@@ -227,7 +230,7 @@ public class ResourceLoader<T extends IrisRegistrant> implements MeteredCache {
return file;
}
IrisLogging.warn("Couldn't find " + resourceTypeName + ": " + name + " (called by " + callerHint() + ")");
warnMissingOnce(name);
return null;
}
@@ -306,6 +309,27 @@ public class ResourceLoader<T extends IrisRegistrant> implements MeteredCache {
.orElse("<unknown>"));
}
protected void warnMissingOnce(String name) {
IrisLogging.warnOnce(manager.onceKey(MISSING_KEY_KIND + resourceTypeName, name),
() -> "Couldn't find " + resourceTypeName + ": " + name + " (called by " + callerHint() + ")");
}
protected void warnLiteralNullOnce(String action) {
IrisLogging.warnOnce(manager.onceKey(LITERAL_NULL_KEY_KIND + resourceTypeName, action),
() -> "Refusing " + resourceTypeName + " " + action + " for literal string \"null\" (called by " + callerHint() + ")");
}
/**
* Warns once per file; only that first warning carries the stack trace, so a file that fails on every
* lookup does not repeat it.
*/
protected void warnReadFailureOnce(File file, String message, Throwable failure) {
String key = manager.onceKey(READ_KEY_KIND + resourceTypeName, file.getPath());
if (IrisLogging.warnOnce(key, message) && failure != null) {
IrisLogging.reportError(failure);
}
}
public void logLoad(File path, T t) {
loads.getAndIncrement();
@@ -529,7 +553,7 @@ public class ResourceLoader<T extends IrisRegistrant> implements MeteredCache {
return null;
}
if (name.equals("null") && warn) {
IrisLogging.warn("Refusing " + resourceTypeName + " load for literal string \"null\" (called by " + callerHint() + ")");
warnLiteralNullOnce("load");
return null;
}
@@ -87,6 +87,7 @@ import java.util.function.Function;
@Description("Represents an iris object placer. It places objects.")
@Data
public class IrisObjectPlacement {
private static final String LOOT_TABLE_KEY_KIND = "missing-loot-table";
@RegistryListResource(IrisObject.class)
@Required
@ArrayType(min = 1, type = String.class)
@@ -111,8 +112,13 @@ public class IrisObjectPlacement {
@MaxNumber(1)
@Description("The chance for this to place in a chunk. If you need multiple per chunk, set this to 1 and use density.")
private double chance = 1;
@Description("If set, chance is multiplied by this noise (0 to 1) at the chunk, so objects gather in some areas and thin out in others.")
private IrisGeneratorStyle chanceStyle = null;
@MinNumber(0)
@Description("Keeps objects of this placement at least this many blocks apart, also across chunks and biomes that place the same objects. Each chunk then places at most one. 0 turns it off. Surface placements only.")
private int separation = 0;
@MinNumber(1)
@Description("If the chance check passes, place this many in a single chunk")
@Description("If the chance check passes, place this many in a single chunk. Ignored when separation is set.")
private int density = 1;
@Description("If the chance check passes, and you specify this, it picks a number in the range based on noise, and 'density' is ignored.")
private IrisStyledRange densityStyle = null;
@@ -337,6 +343,8 @@ public class IrisObjectPlacement {
p.setDensity(density);
p.setDensityStyle(densityStyle);
p.setChance(chance);
p.setChanceStyle(chanceStyle);
p.setSeparation(separation);
p.setSnow(snow);
p.setClamp(clamp);
p.setRotation(rotation);
@@ -402,6 +410,10 @@ public class IrisObjectPlacement {
return false;
}
public boolean isSeparated() {
return separation > 0;
}
public int getDensity() {
if (densityStyle == null) {
return density;
@@ -417,7 +429,7 @@ public class IrisObjectPlacement {
return (int) Math.round(densityStyle.get(rng, x, z, runtime));
}
private TableCache getCache(IrisData manager) {
TableCache getCache(IrisData manager) {
return cache.aquire(() -> {
TableCache cache = new TableCache();
@@ -436,7 +448,8 @@ public class IrisObjectPlacement {
continue;
IrisLootTable table = loader.apply(loot.getName());
if (table == null) {
IrisLogging.warn("Couldn't find loot table " + loot.getName());
IrisLogging.warnOnce(IrisData.onceKey(manager, LOOT_TABLE_KEY_KIND, loot.getName()),
"Couldn't find loot table " + loot.getName());
continue;
}
if (table.isCompatExcluded()) {
@@ -141,7 +141,7 @@ final class BiomeExplorer {
private void add(double x, double z) {
count++;
InferredType type = complex.getBridgeStream().get(x, z);
InferredType type = complex.baseTypeIn(region, x, z);
for (TypedSpread typed : spreads) {
if (typed.type() == type) {
typed.spread().add(noiseByType.computeIfAbsent(type, shown -> complex.biomePickNoiseStream(region, shown)).get(x, z));
@@ -19,6 +19,7 @@
package art.arcane.iris.studio.map;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.iris.studio.map.components.MapLayer;
@@ -43,7 +44,7 @@ final class PackFileOpener {
File file = switch (layer.type()) {
case BIOME, HEIGHT, RIVER, OBJECT_LOAD, DECORATOR_LOAD, LAYER_LOAD -> complex.getTrueBiomeStream().get(worldX, worldZ).openInVSCode();
case BIOME_LAND -> complex.getLandBiomeStream().get(worldX, worldZ).openInVSCode();
case BIOME_SEA -> complex.getSeaBiomeStream().get(worldX, worldZ).openInVSCode();
case BIOME_SEA -> openBiome(complex.getSeaBiomeStream().get(worldX, worldZ));
case REGION -> complex.getRegionStream().get(worldX, worldZ).openInVSCode();
case REGION_PREVIEW -> openPreviewedBiome(engine, layer.previewRegionKey(), worldX, worldZ);
case CAVE_LAND -> complex.getCaveBiomeStream().get(worldX, worldZ).openInVSCode();
@@ -51,6 +52,11 @@ final class PackFileOpener {
return Optional.ofNullable(file).map(File::getName);
}
/** A region without sea biomes has none to open. */
private static File openBiome(IrisBiome biome) {
return biome == null ? null : biome.openInVSCode();
}
private static File openPreviewedBiome(Engine engine, String regionKey, double worldX, double worldZ) {
IrisRegion region = engine.getData().getRegionLoader().load(regionKey);
return region == null ? null : engine.getComplex().surfaceBiomeAsIfIn(region, worldX, worldZ).openInVSCode();
@@ -236,12 +236,11 @@ public final class MapTileRenderer {
// The biome view shows each spot's base biome, which its own region picks from the biome list of the spot's type.
private static NoiseField baseBiomePickNoise(IrisComplex complex) {
ProceduralStream<IrisRegion> regions = complex.getRegionStream();
ProceduralStream<InferredType> types = complex.getBridgeStream();
Map<IrisRegion, Map<InferredType, ProceduralStream<Double>>> noiseByRegion = new IdentityHashMap<>();
return (gridIndex, x, z) -> {
IrisRegion region = regions.get(x, z);
return noiseByRegion.computeIfAbsent(region, subject -> new EnumMap<>(InferredType.class))
.computeIfAbsent(types.get(x, z), type -> complex.biomePickNoiseStream(region, type))
.computeIfAbsent(complex.baseTypeIn(region, x, z), type -> complex.biomePickNoiseStream(region, type))
.get(x, z);
};
}
@@ -176,6 +176,8 @@ public final class IrisRenderer {
return Math.max(1, Math.min(resolution, (int) Math.floor(16D / absoluteStep)));
}
private static final int NO_BIOME_COLOR = 0xFF000000;
private PixelShader shader(RenderType currentType) {
IrisComplex complex = renderer.getComplex();
return switch (currentType) {
@@ -193,6 +195,9 @@ public final class IrisRenderer {
IdentityHashMap<IrisBiome, Integer> colors = new IdentityHashMap<>();
return (double x, double z) -> {
IrisBiome biome = stream.get(x, z);
if (biome == null) {
return NO_BIOME_COLOR;
}
Integer color = colors.get(biome);
if (color == null) {
color = biome.getColor(renderer, currentType).getRGB();
@@ -697,7 +697,8 @@ public final class GenerationHistory {
&& !selected.contains(ownership.resolve(chunkX, chunkZ, outgoing));
WorldChunkInventory inventory;
if (startupRecovery) {
inventory = SavedTerrainRecoveryScan.scan(paths.dimensionRoot(), allocated, retained);
inventory = SavedTerrainRecoveryScan.scan(paths.dimensionRoot(), allocated, retained,
paths.irisRoot().resolve(SavedTerrainStatusCache.FILE_NAME));
} else {
try (SavedTerrainChunkReader.StatusReader reader = new SavedTerrainChunkReader.StatusReader(paths.dimensionRoot())) {
inventory = allocated.filter((chunkX, chunkZ) -> retained.test(chunkX, chunkZ)
@@ -3,6 +3,7 @@ package art.arcane.iris.world.history;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.List;
import java.util.Optional;
@@ -20,10 +21,16 @@ final class SavedTerrainRecoveryScan implements AutoCloseable {
private final int regionByteLimit;
private final SavedTerrainChunkReader.StatusReader[] readers;
private final ExecutorService executor;
private final SavedTerrainStatusCache cache;
private byte[] regionBuffer = new byte[0];
SavedTerrainRecoveryScan(Path world, Limits limits) {
this(world, limits, null);
}
SavedTerrainRecoveryScan(Path world, Limits limits, SavedTerrainStatusCache cache) {
this.world = world;
this.cache = cache;
regionByteLimit = limits.regionBytes();
readers = new SavedTerrainChunkReader.StatusReader[limits.workers()];
for (int index = 0; index < readers.length; index++) {
@@ -35,11 +42,26 @@ final class SavedTerrainRecoveryScan implements AutoCloseable {
static WorldChunkInventory scan(Path world, WorldChunkInventory inventory,
WorldChunkInventory.ChunkPredicate retained) throws IOException {
return scan(world, inventory, retained, null);
}
/**
* Scans with the status cache at {@code cacheFile}, or without a cache when it is null. The cache is
* written once, after the whole scan succeeded.
*/
static WorldChunkInventory scan(Path world, WorldChunkInventory inventory,
WorldChunkInventory.ChunkPredicate retained, Path cacheFile) throws IOException {
Runtime runtime = Runtime.getRuntime();
SavedTerrainStatusCache cache = cacheFile == null ? null : SavedTerrainStatusCache.load(cacheFile, world);
WorldChunkInventory result;
try (SavedTerrainRecoveryScan scan = new SavedTerrainRecoveryScan(world,
Limits.forRuntime(runtime.availableProcessors(), runtime.maxMemory()))) {
return scan.filter(inventory, retained);
Limits.forRuntime(runtime.availableProcessors(), runtime.maxMemory()), cache)) {
result = scan.filter(inventory, retained);
}
if (cache != null) {
cache.save();
}
return result;
}
WorldChunkInventory filter(WorldChunkInventory inventory, WorldChunkInventory.ChunkPredicate retained)
@@ -81,18 +103,39 @@ final class SavedTerrainRecoveryScan implements AutoCloseable {
}
}
if (pending.isEmpty()) {
if (cache != null) {
cache.carry(region.x(), region.z());
}
return accepted;
}
Path file = world.resolve("region/r." + region.x() + "." + region.z() + ".mca");
SavedTerrainStatusCache.Header header = cache == null ? null : readHeader(file);
SavedTerrainStatusCache.Update update = null;
if (header != null) {
update = cache.begin(region.x(), region.z(), header, pending, accepted);
if (pending.isEmpty()) {
update.commit();
return accepted;
}
}
int snapshotLimit = Math.min(regionByteLimit, pending.cardinality() * 64 * 1024);
Optional<SavedTerrainRegionSnapshot> captured = SavedTerrainRegionSnapshot.read(file, snapshotLimit, regionBuffer);
if (captured.isEmpty()) {
BitSet terrain = new BitSet(1024);
for (int slot = pending.nextSetBit(0); slot >= 0; slot = pending.nextSetBit(slot + 1)) {
requireNotInterrupted();
if (SavedTerrainChunk.hasTerrain(readers[0].readStatus(region.chunkX(slot), region.chunkZ(slot)))) {
accepted.set(slot);
terrain.set(slot);
}
}
accepted.or(terrain);
if (update != null) {
SavedTerrainStatusCache.Header after = readHeader(file);
if (after != null && header.sameHeader(after)) {
record(update, region, header, pending, terrain);
}
update.commit();
}
return accepted;
}
SavedTerrainRegionSnapshot snapshot = captured.get();
@@ -106,8 +149,9 @@ final class SavedTerrainRecoveryScan implements AutoCloseable {
pending.clear(slot);
}
}
BitSet terrain;
if (executor == null || pending.cardinality() < MIN_PARALLEL_CHUNKS) {
accepted.or(decode(new DecodeRegion(region, pending, snapshot), 0, 1));
terrain = decode(new DecodeRegion(region, pending, snapshot), 0, 1);
} else {
List<Future<BitSet>> tasks = new ArrayList<>(readers.length);
DecodeRegion input = new DecodeRegion(region, pending, snapshot);
@@ -115,12 +159,36 @@ final class SavedTerrainRecoveryScan implements AutoCloseable {
int worker = index;
tasks.add(executor.submit(() -> decode(input, worker, readers.length)));
}
accepted.or(await(tasks));
terrain = await(tasks);
}
accepted.or(terrain);
snapshot.validateUnchanged();
if (update != null) {
record(update, region, new SavedTerrainStatusCache.Header(header.fileKey(), header.size(),
Arrays.copyOf(snapshot.bytes(), SavedTerrainStatusCache.Header.BYTES)), pending, terrain);
update.commit();
}
return accepted;
}
private void record(SavedTerrainStatusCache.Update update, Region region, SavedTerrainStatusCache.Header header,
BitSet decoded, BitSet terrain) {
for (int slot = decoded.nextSetBit(0); slot >= 0; slot = decoded.nextSetBit(slot + 1)) {
if (!cache.isExternal(region.chunkX(slot), region.chunkZ(slot))) {
update.record(slot, header.location(slot), header.timestamp(slot), terrain.get(slot));
}
}
}
private static SavedTerrainStatusCache.Header readHeader(Path file) {
try {
return SavedTerrainStatusCache.Header.read(file);
} catch (IOException ignored) {
// The uncached read reports the real problem with this region.
return null;
}
}
private BitSet decode(DecodeRegion input, int worker, int stride) throws IOException {
BitSet accepted = new BitSet(1024);
int ordinal = 0;
@@ -0,0 +1,379 @@
package art.arcane.iris.world.history;
import art.arcane.iris.spi.IrisLogging;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Objects;
import java.util.zip.CRC32;
/**
* Remembers the decoded "has terrain" bit of each saved chunk between startups. A bit is reused only while the
* slot's location word and timestamp in the region header are unchanged, the timestamp is at least two seconds
* older than the scan that decoded it, and the chunk is not stored in an external .mcc file. Ownership filtering
* is never cached; callers apply it on every scan.
*/
final class SavedTerrainStatusCache {
static final String FILE_NAME = "terrain-status.cache";
private static final int MAGIC = 0x49545343;
private static final int VERSION = 1;
private static final int SLOTS = 1024;
private static final int HEADER_BYTES = 2 * 4096;
private static final long MAX_CACHE_BYTES = 1L << 30;
private final Path file;
private final Path regionDirectory;
private final long scanSeconds;
private final long previousScanSeconds;
private final Long2ObjectOpenHashMap<Region> previous;
private final Long2ObjectOpenHashMap<Region> next = new Long2ObjectOpenHashMap<>();
private LongOpenHashSet externalChunks;
private boolean externalChunksUnknown;
private SavedTerrainStatusCache(Path file, Path world, long scanSeconds, Contents contents) {
this.file = file;
regionDirectory = world.toAbsolutePath().normalize().resolve(GenerationHistoryPaths.REGION_DIRECTORY_NAME);
this.scanSeconds = scanSeconds;
previousScanSeconds = contents.scanSeconds();
previous = contents.regions();
}
static SavedTerrainStatusCache load(Path file, Path world) {
Objects.requireNonNull(file, "file");
Objects.requireNonNull(world, "world");
long now = System.currentTimeMillis() / 1000L;
return new SavedTerrainStatusCache(file, world, now, readContents(file));
}
/**
* Starts the cache update for one region and moves every pending slot whose cached bit is still valid out of
* {@code pending}, setting it in {@code accepted} when the chunk has terrain.
*/
Update begin(int regionX, int regionZ, Header header, BitSet pending, BitSet accepted) {
Update update = new Update(regionX, regionZ, header);
Region cached = previous.get(ChunkGenerationOwnership.packChunk(regionX, regionZ));
if (cached == null || !cached.matches(header)) {
return update;
}
for (int entry = 0; entry < cached.slots().length; entry++) {
int slot = cached.slots()[entry];
if (header.location(slot) != cached.locations()[entry]
|| header.timestamp(slot) != cached.timestamps()[entry]
|| !reusable(cached.locations()[entry], cached.timestamps()[entry], previousScanSeconds)
|| isExternal(regionX * 32 + (slot & 31), regionZ * 32 + (slot >> 5))) {
continue;
}
boolean terrain = cached.terrain().get(entry);
update.keep(slot, cached.locations()[entry], cached.timestamps()[entry], terrain);
if (pending.get(slot)) {
pending.clear(slot);
if (terrain) {
accepted.set(slot);
}
}
}
return update;
}
/**
* Keeps a region's cached entries as they are, for a region the scan did not need to read.
*/
void carry(int regionX, int regionZ) {
long key = ChunkGenerationOwnership.packChunk(regionX, regionZ);
Region cached = previous.get(key);
if (cached != null) {
next.put(key, cached);
}
}
/**
* True when the chunk has an external .mcc payload, or when the region directory could not be listed.
*/
boolean isExternal(int chunkX, int chunkZ) {
if (externalChunks == null && !externalChunksUnknown) {
try {
externalChunks = listExternalChunks(regionDirectory);
} catch (IOException | RuntimeException failure) {
externalChunksUnknown = true;
IrisLogging.warnOnce("saved-terrain-cache-external", () -> "Not using the saved terrain status cache"
+ " because " + regionDirectory + " could not be listed: " + failure);
}
}
return externalChunksUnknown
|| externalChunks.contains(ChunkGenerationOwnership.packChunk(chunkX, chunkZ));
}
/**
* Writes the cache with the regions visited by this scan. Regions that were not visited are dropped. Failures
* are logged and never reach the caller.
*/
void save() {
try {
byte[] encoded = encode(scanSeconds, next);
Path directory = file.toAbsolutePath().getParent();
Files.createDirectories(directory);
Path temporary = Files.createTempFile(directory, "." + file.getFileName() + "-", ".tmp");
try {
Files.write(temporary, encoded);
Files.move(temporary, file, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
} finally {
Files.deleteIfExists(temporary);
}
} catch (IOException | RuntimeException failure) {
IrisLogging.warnOnce("saved-terrain-cache-write", () -> "Could not write the saved terrain status cache "
+ file + ": " + failure);
}
}
private boolean reusable(int location, int timestamp, long decodedAt) {
return location != 0 && Integer.toUnsignedLong(timestamp) < decodedAt - 1L;
}
private static LongOpenHashSet listExternalChunks(Path regionDirectory) throws IOException {
LongOpenHashSet chunks = new LongOpenHashSet();
try (DirectoryStream<Path> entries = Files.newDirectoryStream(regionDirectory, "c.*.*.mcc")) {
for (Path entry : entries) {
String[] parts = entry.getFileName().toString().split("\\.");
if (parts.length != 4) {
continue;
}
try {
chunks.add(ChunkGenerationOwnership.packChunk(Integer.parseInt(parts[1]),
Integer.parseInt(parts[2])));
} catch (NumberFormatException ignored) {
// Not a chunk payload name; the region reader ignores it too.
}
}
} catch (NoSuchFileException ignored) {
return chunks;
}
return chunks;
}
private static Contents readContents(Path file) {
try {
if (!Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) {
return Contents.EMPTY;
}
if (Files.size(file) > MAX_CACHE_BYTES) {
throw new IOException("cache file is too large");
}
return decode(Files.readAllBytes(file));
} catch (IOException | RuntimeException failure) {
IrisLogging.warnOnce("saved-terrain-cache-read", () -> "Ignoring the saved terrain status cache "
+ file + ": " + failure.getMessage());
return Contents.EMPTY;
}
}
private static byte[] encode(long scanSeconds, Long2ObjectOpenHashMap<Region> regions) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try (DataOutputStream output = new DataOutputStream(buffer)) {
output.writeInt(MAGIC);
output.writeInt(VERSION);
output.writeLong(scanSeconds);
output.writeInt(regions.size());
for (Region region : regions.values()) {
output.writeInt(region.x());
output.writeInt(region.z());
output.writeLong(region.size());
output.writeUTF(region.fileKey());
output.writeShort(region.slots().length);
for (int entry = 0; entry < region.slots().length; entry++) {
output.writeShort(region.slots()[entry]);
output.writeInt(region.locations()[entry]);
output.writeInt(region.timestamps()[entry]);
output.writeBoolean(region.terrain().get(entry));
}
}
CRC32 checksum = new CRC32();
checksum.update(buffer.toByteArray());
output.writeLong(checksum.getValue());
}
return buffer.toByteArray();
}
private static Contents decode(byte[] bytes) throws IOException {
if (bytes.length < Long.BYTES) {
throw new IOException("cache file is truncated");
}
CRC32 checksum = new CRC32();
checksum.update(bytes, 0, bytes.length - Long.BYTES);
if (ByteBuffer.wrap(bytes, bytes.length - Long.BYTES, Long.BYTES).getLong() != checksum.getValue()) {
throw new IOException("cache checksum does not match");
}
DataInputStream input = new DataInputStream(new ByteArrayInputStream(bytes, 0, bytes.length - Long.BYTES));
if (input.readInt() != MAGIC) {
throw new IOException("not a saved terrain status cache");
}
int version = input.readInt();
if (version != VERSION) {
throw new IOException("unsupported cache version " + version);
}
long scanSeconds = input.readLong();
int regionCount = input.readInt();
if (regionCount < 0) {
throw new IOException("invalid region count");
}
Long2ObjectOpenHashMap<Region> regions = new Long2ObjectOpenHashMap<>(Math.min(regionCount, 65536));
for (int index = 0; index < regionCount; index++) {
int x = input.readInt();
int z = input.readInt();
long size = input.readLong();
String fileKey = input.readUTF();
int count = input.readUnsignedShort();
if (size < HEADER_BYTES || count > SLOTS) {
throw new IOException("invalid region entry");
}
int[] slots = new int[count];
int[] locations = new int[count];
int[] timestamps = new int[count];
BitSet terrain = new BitSet(count);
int previousSlot = -1;
for (int entry = 0; entry < count; entry++) {
int slot = input.readUnsignedShort();
if (slot >= SLOTS || slot <= previousSlot) {
throw new IOException("invalid chunk slot");
}
previousSlot = slot;
slots[entry] = slot;
locations[entry] = input.readInt();
timestamps[entry] = input.readInt();
terrain.set(entry, input.readBoolean());
}
if (regions.put(ChunkGenerationOwnership.packChunk(x, z),
new Region(x, z, size, fileKey, slots, locations, timestamps, terrain)) != null) {
throw new IOException("duplicate region entry");
}
}
if (input.available() != 0) {
throw new IOException("unexpected trailing data");
}
return new Contents(scanSeconds, regions);
}
final class Update {
private final int regionX;
private final int regionZ;
private final Header header;
private final int[] locations = new int[SLOTS];
private final int[] timestamps = new int[SLOTS];
private final BitSet known = new BitSet(SLOTS);
private final BitSet terrain = new BitSet(SLOTS);
private Update(int regionX, int regionZ, Header header) {
this.regionX = regionX;
this.regionZ = regionZ;
this.header = header;
}
/**
* Records a freshly decoded bit. Call only after the region was confirmed unchanged during decoding.
*/
void record(int slot, int location, int timestamp, boolean hasTerrain) {
if (reusable(location, timestamp, scanSeconds)) {
keep(slot, location, timestamp, hasTerrain);
} else {
known.clear(slot);
}
}
void commit() {
int count = known.cardinality();
int[] slots = new int[count];
int[] storedLocations = new int[count];
int[] storedTimestamps = new int[count];
BitSet storedTerrain = new BitSet(count);
int entry = 0;
for (int slot = known.nextSetBit(0); slot >= 0; slot = known.nextSetBit(slot + 1)) {
slots[entry] = slot;
storedLocations[entry] = locations[slot];
storedTimestamps[entry] = timestamps[slot];
storedTerrain.set(entry, terrain.get(slot));
entry++;
}
next.put(ChunkGenerationOwnership.packChunk(regionX, regionZ), new Region(regionX, regionZ,
header.size(), header.fileKey(), slots, storedLocations, storedTimestamps, storedTerrain));
}
private void keep(int slot, int location, int timestamp, boolean hasTerrain) {
locations[slot] = location;
timestamps[slot] = timestamp;
known.set(slot);
terrain.set(slot, hasTerrain);
}
}
/**
* The 8 KiB header of a region file together with the identity of the file it came from.
*/
record Header(String fileKey, long size, byte[] bytes) {
static final int BYTES = HEADER_BYTES;
static Header read(Path file) throws IOException {
Path normalized = file.toAbsolutePath().normalize();
BasicFileAttributes attributes = Files.readAttributes(normalized, BasicFileAttributes.class,
LinkOption.NOFOLLOW_LINKS);
if (!attributes.isRegularFile() || attributes.size() < HEADER_BYTES) {
throw new IOException("Saved chunk region header is unavailable: " + normalized);
}
byte[] bytes = new byte[HEADER_BYTES];
try (FileChannel input = FileChannel.open(normalized, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) {
ByteBuffer buffer = ByteBuffer.wrap(bytes);
while (buffer.hasRemaining()) {
if (input.read(buffer) < 0) {
throw new IOException("Truncated saved chunk region: " + normalized);
}
}
}
Object key = attributes.fileKey();
return new Header(key == null ? "" : key.toString(), attributes.size(), bytes);
}
int location(int slot) {
return word(slot * Integer.BYTES);
}
int timestamp(int slot) {
return word(4096 + slot * Integer.BYTES);
}
boolean sameHeader(Header other) {
return fileKey.equals(other.fileKey) && Arrays.equals(bytes, other.bytes);
}
private int word(int offset) {
return (bytes[offset] & 255) << 24 | (bytes[offset + 1] & 255) << 16
| (bytes[offset + 2] & 255) << 8 | bytes[offset + 3] & 255;
}
}
record Region(int x, int z, long size, String fileKey, int[] slots, int[] locations, int[] timestamps,
BitSet terrain) {
boolean matches(Header header) {
return fileKey.equals(header.fileKey()) && header.size() >= size;
}
}
private record Contents(long scanSeconds, Long2ObjectOpenHashMap<Region> regions) {
static final Contents EMPTY = new Contents(0L, new Long2ObjectOpenHashMap<>());
}
}
@@ -36,6 +36,7 @@ import art.arcane.iris.pack.schema.annotation.RegistryListItemType;
import art.arcane.iris.pack.schema.annotation.Required;
import art.arcane.iris.pack.schema.annotation.Snippet;
import art.arcane.iris.platform.bukkit.BukkitPlatform;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.collection.KMap;
@@ -72,6 +73,7 @@ import java.util.Optional;
@ToString(doNotUseGetters = true)
public class IrisLoot {
public static final int MAX_AMOUNT = 64;
private static final String UNKNOWN_MATERIAL_KEY_KIND = "unknown-loot-material";
private final transient AtomicCache<DyeColor> dyeColorResolved = new AtomicCache<>();
@Description("The target inventory slot types to fill this loot with. World generation only ever fills STORAGE; the other values are inert during worldgen.")
@@ -173,7 +175,7 @@ public class IrisLoot {
public ItemStack get(boolean debug, RNG rng) {
try {
ItemStack is = getItemStack(rng);
ItemStack is = getItemStack(rng, null);
if (is == null)
return new ItemStack(Material.AIR);
is.setItemMeta(applyProperties(is, rng, debug, null));
@@ -191,7 +193,7 @@ public class IrisLoot {
}
try {
ItemStack is = getItemStack(rng);
ItemStack is = getItemStack(rng, table);
if (is == null)
return null;
is.setItemMeta(applyProperties(is, rng, debug, table));
@@ -204,11 +206,12 @@ public class IrisLoot {
}
// TODO Better Third Party Item Acquisition
private ItemStack getItemStack(RNG rng) {
private ItemStack getItemStack(RNG rng, IrisLootTable table) {
if (!type.startsWith("minecraft:") && type.contains(":")) {
Optional<ItemStack> opt = IrisServices.get(ExternalDataSVC.class).getItemStack(Identifier.fromString(type), customNbt);
if (opt.isEmpty()) {
IrisLogging.warn("Unknown Material: " + type);
IrisData pack = table == null ? null : table.getLoader();
IrisLogging.warnOnce(IrisData.onceKey(pack, UNKNOWN_MATERIAL_KEY_KIND, type), "Unknown Material: " + type);
return new ItemStack(Material.AIR);
}
ItemStack is = opt.get();
@@ -0,0 +1,20 @@
package art.arcane.iris.world.storage.matter;
import java.util.Set;
/**
* Slice ids that older Iris releases wrote into saved matter and that a newer jar may no longer register.
* A reader skips these instead of failing; every other unknown id stays a hard error.
*/
public final class RetiredMatterSlices {
public static final String TREE_CANOPY = "art.arcane.iris.generation.mantle.TreeCanopy";
private static final Set<String> IDS = Set.of(TREE_CANOPY);
private RetiredMatterSlices() {
}
public static boolean isRetired(String id) {
return IDS.contains(id);
}
}
@@ -65,6 +65,7 @@ public final class IrisBiomeLayerSlopeSourceTest {
when(complex.terrainSurfaceSlope(12, 32, -8)).thenReturn(0D);
when(complex.terrainSurfaceSlope(12, 96, -8)).thenReturn(5D);
when(grass.getZoom()).thenReturn(1D);
when(grass.blocksPerSample()).thenReturn(1D);
when(grass.getMinHeight()).thenReturn(1);
when(grass.getMaxHeight()).thenReturn(1);
when(grass.getSlopeCondition()).thenReturn(new IrisSlopeClip(0D, 2.6D));
@@ -106,6 +107,7 @@ public final class IrisBiomeLayerSlopeSourceTest {
when(hostSlope.getDouble(12D, -8D)).thenReturn(0D);
when(sourceSlope.getDouble(12D, -8D)).thenReturn(5D);
when(paletteLayer.getZoom()).thenReturn(1D);
when(paletteLayer.blocksPerSample()).thenReturn(1D);
when(paletteLayer.getMinHeight()).thenReturn(1);
when(paletteLayer.getMaxHeight()).thenReturn(1);
when(paletteLayer.getSlopeCondition()).thenReturn(new IrisSlopeClip(5D, 5D));
@@ -34,6 +34,7 @@ public final class IrisSurfaceLayerFallbackTest {
private IrisBiome biome() {
when(layer.getZoom()).thenReturn(1D);
when(layer.blocksPerSample()).thenReturn(1D);
when(layer.getMinHeight()).thenReturn(1);
when(layer.getMaxHeight()).thenReturn(2);
when(layer.getHeightGenerator(any(RNG.class), MockPackData.runtimeOf(data))).thenReturn(heightGenerator);
@@ -0,0 +1,153 @@
package art.arcane.iris.generation.mantle;
import art.arcane.iris.world.storage.matter.IrisMatterSupport;
import art.arcane.iris.world.storage.matter.RetiredMatterSlices;
import art.arcane.volmlib.util.matter.IrisMatter;
import art.arcane.volmlib.util.matter.Matter;
import art.arcane.volmlib.util.matter.MatterHeader;
import art.arcane.volmlib.util.matter.MatterSlice;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class ObjectContinuationRetiredSliceTest {
@Test
public void retiredUnregisteredSliceIsSkippedAndRestDecodes() throws Exception {
IrisMatterSupport.ensureRegistered();
byte[] canopy = sliceBytes(TreeCanopy.class, TreeCanopy.INSTANCE);
byte[] number = sliceBytes(Integer.class, 42);
byte[] payload = payload(List.of(canopy, number));
Object registered = unregister(RetiredMatterSlices.TREE_CANOPY);
try {
assertEquals(null, IrisMatter.getSliceType(RetiredMatterSlices.TREE_CANOPY));
Matter decoded = fragment(payload).decode();
assertFalse(decoded.hasSlice(TreeCanopy.class));
assertEquals(Integer.valueOf(42), decoded.getSlice(Integer.class).get(1, 2, 3));
} finally {
restore(registered);
}
}
@Test
public void duplicateRetiredUnregisteredSliceFails() throws Exception {
IrisMatterSupport.ensureRegistered();
byte[] canopy = sliceBytes(TreeCanopy.class, TreeCanopy.INSTANCE);
byte[] payload = payload(List.of(canopy, canopy));
Object registered = unregister(RetiredMatterSlices.TREE_CANOPY);
try {
IOException failure = assertThrows(IOException.class, () -> fragment(payload).decode());
assertTrue(failure.getMessage(), failure.getMessage().startsWith("Duplicate object continuation slice type"));
} finally {
restore(registered);
}
}
@Test
public void unknownSliceStillFails() throws Exception {
IrisMatterSupport.ensureRegistered();
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
DataOutputStream output = new DataOutputStream(bytes);
output.writeUTF("art.arcane.iris.test.NeverRegistered");
output.writeInt(7);
byte[] payload = payload(List.of(bytes.toByteArray(), sliceBytes(Integer.class, 42)));
IOException failure = assertThrows(IOException.class, () -> fragment(payload).decode());
assertEquals("Unknown object continuation slice type: art.arcane.iris.test.NeverRegistered", failure.getMessage());
}
@Test
public void duplicateRegisteredSliceFails() throws Exception {
IrisMatterSupport.ensureRegistered();
byte[] number = sliceBytes(Integer.class, 42);
byte[] payload = payload(List.of(number, number));
IOException failure = assertThrows(IOException.class, () -> fragment(payload).decode());
assertEquals("Duplicate object continuation slice type: " + IrisMatter.getSliceId(Integer.class), failure.getMessage());
}
@Test
public void registeredRetiredSliceStillDecodes() throws Exception {
IrisMatterSupport.ensureRegistered();
byte[] payload = payload(List.of(sliceBytes(TreeCanopy.class, TreeCanopy.INSTANCE)));
Matter decoded = fragment(payload).decode();
assertEquals(TreeCanopy.INSTANCE, decoded.getSlice(TreeCanopy.class).get(1, 2, 3));
}
private static <T> byte[] sliceBytes(Class<T> type, T value) throws IOException {
Matter matter = new IrisMatter(16, 16, 16);
MatterSlice<T> slice = matter.slice(type);
slice.set(1, 2, 3, value);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
slice.write(new DataOutputStream(bytes));
return bytes.toByteArray();
}
private static byte[] payload(List<byte[]> slices) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
DataOutputStream output = new DataOutputStream(bytes);
output.writeInt(16);
output.writeInt(16);
output.writeInt(16);
output.writeByte(slices.size());
new MatterHeader().write(output);
for (byte[] slice : slices) {
output.writeInt(slice.length);
output.write(slice);
}
return bytes.toByteArray();
}
private static ObjectContinuationBundle.Fragment fragment(byte[] payload) {
return new ObjectContinuationBundle.Fragment(
new ObjectContinuationBundle.PlacementKey(ObjectContinuationBundle.Kind.STATIC, 0, 0, 0),
new ObjectContinuationBundle.Bounds(0, 0, 16, 0),
List.of(new ObjectContinuationBundle.ChunkPosition(0, 0), new ObjectContinuationBundle.ChunkPosition(1, 0)),
payload);
}
private static Field registryField() throws ReflectiveOperationException {
Field field = IrisMatter.class.getDeclaredField("sliceRegistry");
field.setAccessible(true);
return field;
}
@SuppressWarnings("unchecked")
private static Object unregister(String id) throws ReflectiveOperationException {
Field field = registryField();
Object registry = field.get(null);
Class<?> registryType = registry.getClass();
Method byTypeAccessor = registryType.getDeclaredMethod("byType");
Method byIdAccessor = registryType.getDeclaredMethod("byId");
byTypeAccessor.setAccessible(true);
byIdAccessor.setAccessible(true);
Map<Class<?>, Object> byType = new HashMap<>((Map<Class<?>, Object>) byTypeAccessor.invoke(registry));
Map<String, Object> byId = new HashMap<>((Map<String, Object>) byIdAccessor.invoke(registry));
Class<?> type = IrisMatter.getSliceType(id);
byType.remove(type);
byId.remove(id);
Constructor<?> constructor = registryType.getDeclaredConstructor(Map.class, Map.class);
constructor.setAccessible(true);
field.set(null, constructor.newInstance(Map.copyOf(byType), Map.copyOf(byId)));
return registry;
}
private static void restore(Object registry) throws ReflectiveOperationException {
registryField().set(null, registry);
}
}
@@ -0,0 +1,141 @@
package art.arcane.iris.generation.mantle;
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.structure.object.IrisObjectPlacement;
import art.arcane.volmlib.util.collection.KList;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ObjectSeparationTest {
private static final long SEED = 1337L;
private static final int SEPARATION_BLOCKS = 40;
private static final int GRID_HALF_WIDTH_CHUNKS = 24;
@Test
public void keptObjectsStayApartAcrossBiomeBorders() {
IrisObjectPlacement westBiome = separated(1, SEPARATION_BLOCKS, "tree");
IrisObjectPlacement eastBiome = separated(1, SEPARATION_BLOCKS, "tree");
ObjectSeparation separation = separation(
(chunkX, chunkZ) -> List.of(chunkX < 0 ? westBiome : eastBiome));
List<ObjectSeparation.Candidate> kept = keptOnGrid(separation, (chunkX, chunkZ) -> chunkX < 0 ? westBiome : eastBiome);
assertTrue(kept.size() > 10);
for (int first = 0; first < kept.size(); first++) {
for (int second = first + 1; second < kept.size(); second++) {
assertFalse(kept.get(first).isCloserThan(kept.get(second), SEPARATION_BLOCKS));
}
}
}
@Test
public void keptObjectsDoNotDependOnQueryOrder() {
IrisObjectPlacement placement = separated(1, SEPARATION_BLOCKS, "tree");
ObjectSeparation separation = separation((chunkX, chunkZ) -> List.of(placement));
List<ObjectSeparation.Candidate> forward = keptOnGrid(separation, (chunkX, chunkZ) -> placement);
List<Long> reversedRanks = new ArrayList<>();
for (int chunkX = GRID_HALF_WIDTH_CHUNKS; chunkX >= -GRID_HALF_WIDTH_CHUNKS; chunkX--) {
for (int chunkZ = GRID_HALF_WIDTH_CHUNKS; chunkZ >= -GRID_HALF_WIDTH_CHUNKS; chunkZ--) {
separation.keptCandidate(chunkX, chunkZ, placement).ifPresent(candidate -> reversedRanks.add(candidate.rank()));
}
}
List<Long> forwardRanks = forward.stream().map(ObjectSeparation.Candidate::rank).sorted().toList();
assertEquals(forwardRanks, reversedRanks.stream().sorted().toList());
}
@Test
public void placementsWithOtherObjectsDoNotKeepEachOtherApart() {
IrisObjectPlacement trees = separated(1, SEPARATION_BLOCKS, "tree");
IrisObjectPlacement rocks = separated(1, SEPARATION_BLOCKS, "rock");
ObjectSeparation treesOnly = separation((chunkX, chunkZ) -> List.of(trees));
ObjectSeparation both = separation((chunkX, chunkZ) -> List.of(trees, rocks));
assertEquals(
keptOnGrid(treesOnly, (chunkX, chunkZ) -> trees).size(),
keptOnGrid(both, (chunkX, chunkZ) -> trees).size());
}
@Test
public void zeroChanceKeepsNothing() {
IrisObjectPlacement placement = separated(0, SEPARATION_BLOCKS, "tree");
ObjectSeparation separation = separation((chunkX, chunkZ) -> List.of(placement));
assertTrue(keptOnGrid(separation, (chunkX, chunkZ) -> placement).isEmpty());
}
@Test
public void wideSeparationThinsObjectsOut() {
IrisObjectPlacement narrow = separated(1, 8, "tree");
IrisObjectPlacement wide = separated(1, 96, "tree");
int narrowCount = keptOnGrid(separation((chunkX, chunkZ) -> List.of(narrow)), (chunkX, chunkZ) -> narrow).size();
int wideCount = keptOnGrid(separation((chunkX, chunkZ) -> List.of(wide)), (chunkX, chunkZ) -> wide).size();
assertTrue(narrowCount > wideCount * 2);
}
@Test
public void placementsStayUnchangedByDefault() {
IrisObjectPlacement placement = new IrisObjectPlacement();
placement.setChance(0.35);
assertFalse(placement.isSeparated());
assertEquals(0.35, separation((chunkX, chunkZ) -> List.of()).chanceAt(placement, 12, -40), 0D);
}
@Test
public void chanceStyleScalesChanceWithoutRaisingIt() {
IrisObjectPlacement placement = new IrisObjectPlacement();
placement.setChance(0.5);
placement.setChanceStyle(new IrisGeneratorStyle(NoiseStyle.STATIC));
ObjectSeparation separation = separation((chunkX, chunkZ) -> List.of());
Optional<Double> lowest = Optional.empty();
Optional<Double> highest = Optional.empty();
for (int x = 0; x < 200; x += 7) {
double chance = separation.chanceAt(placement, x, x * 3);
assertTrue(chance >= 0D && chance <= 0.5);
lowest = Optional.of(Math.min(chance, lowest.orElse(chance)));
highest = Optional.of(Math.max(chance, highest.orElse(chance)));
}
assertTrue(highest.get() - lowest.get() > 0.1);
}
private static List<ObjectSeparation.Candidate> keptOnGrid(ObjectSeparation separation, PlacementAt placementAt) {
List<ObjectSeparation.Candidate> kept = new ArrayList<>();
for (int chunkX = -GRID_HALF_WIDTH_CHUNKS; chunkX <= GRID_HALF_WIDTH_CHUNKS; chunkX++) {
for (int chunkZ = -GRID_HALF_WIDTH_CHUNKS; chunkZ <= GRID_HALF_WIDTH_CHUNKS; chunkZ++) {
separation.keptCandidate(chunkX, chunkZ, placementAt.at(chunkX, chunkZ)).ifPresent(kept::add);
}
}
return kept;
}
private static ObjectSeparation separation(ObjectSeparation.SurfacePlacements surfacePlacements) {
return new ObjectSeparation(SEED, PackRuntime.standalone(null), surfacePlacements);
}
private static IrisObjectPlacement separated(double chance, int separationBlocks, String... objects) {
IrisObjectPlacement placement = new IrisObjectPlacement();
placement.setPlace(new KList<>(objects));
placement.setChance(chance);
placement.setSeparation(separationBlocks);
return placement;
}
@FunctionalInterface
private interface PlacementAt {
IrisObjectPlacement at(int chunkX, int chunkZ);
}
}
@@ -0,0 +1,62 @@
package art.arcane.iris.generation.mantle;
import art.arcane.iris.structure.object.IrisObject;
import art.arcane.iris.testsupport.CapturedLog;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class PlacementMarkerOnceWarningTest {
private static final String SKIPPED = "Skipping placement marker write";
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
private CapturedLog log;
@Before
public void captureLog() {
log = CapturedLog.bind();
}
@After
public void releaseLog() {
log.close();
}
@Test
public void anObjectWithoutALoadKeyWarnsOncePerContextNoMatterTheId() {
IrisObject object = new IrisObject(0, 0, 0);
assertNull(MantleObjectComponent.placementMarker(object, 1, "surface"));
assertNull(MantleObjectComponent.placementMarker(object, 2, "surface"));
assertNull(MantleObjectComponent.placementMarker(new IrisObject(0, 0, 0), 3, "surface"));
assertEquals(1, log.warnings(SKIPPED).size());
}
@Test
public void aDifferentContextWarnsSeparately() {
IrisObject object = new IrisObject(0, 0, 0);
MantleObjectComponent.placementMarker(object, 1, "surface");
MantleObjectComponent.placementMarker(object, 1, "procedural");
assertEquals(2, log.warnings(SKIPPED).size());
}
@Test
public void aLoadKeyedObjectNeverWarns() {
IrisObject object = new IrisObject(0, 0, 0);
object.setLoadKey("trees/oak");
assertEquals("trees/oak@7", MantleObjectComponent.placementMarker(object, 7, "surface"));
assertEquals(0, log.warnings(SKIPPED).size());
}
}
@@ -0,0 +1,133 @@
package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.volmlib.util.collection.KList;
import com.google.gson.Gson;
import org.junit.Test;
import java.util.SplittableRandom;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class IrisGeneratorExponentTest {
private static final PackRuntime RUNTIME = PackRuntime.standalone(null);
private static final long SUPER_SEED = 4242L;
private static final double OPACITY = 0.8D;
private static final double TOLERANCE = 1e-12D;
private static final int POINT_COUNT = 400;
private final double[] xs = new double[POINT_COUNT];
private final double[] zs = new double[POINT_COUNT];
public IrisGeneratorExponentTest() {
SplittableRandom random = new SplittableRandom(0xE590L);
for (int index = 0; index < POINT_COUNT; index++) {
xs[index] = random.nextDouble(-3000D, 3000D);
zs[index] = random.nextDouble(-3000D, 3000D);
}
}
@Test
public void exponentDefaultsToOne() {
assertEquals(1D, new IrisGenerator().getExponent(), 0D);
}
@Test
public void exponentOfOneKeepsOriginalValuesBitForBit() {
for (boolean multiplicitive : new boolean[]{false, true}) {
IrisGenerator unset = generator(multiplicitive, OPACITY);
IrisGenerator explicit = generator(multiplicitive, OPACITY).setExponent(1D);
IrisGenerator unitOpacity = generator(multiplicitive, 1D);
double[] fromUnset = batch(unset);
double[] fromExplicit = batch(explicit);
for (int index = 0; index < POINT_COUNT; index++) {
double original = unitOpacity.getHeight(RUNTIME, xs[index], zs[index], SUPER_SEED) * OPACITY;
assertBits(original, unset.getHeight(RUNTIME, xs[index], zs[index], SUPER_SEED));
assertBits(original, explicit.getHeight(RUNTIME, xs[index], zs[index], SUPER_SEED));
assertBits(original, fromUnset[index]);
assertBits(original, fromExplicit[index]);
}
}
}
@Test
public void scalarProgramAndBatchPathsApplySignedPowerBeforeOpacity() {
for (double exponent : new double[]{3D, 0.5D}) {
for (boolean multiplicitive : new boolean[]{false, true}) {
IrisGenerator combined = generator(multiplicitive, 1D);
IrisGenerator curved = generator(multiplicitive, OPACITY).setExponent(exponent);
GeneratorProgram program = curved.compileProgram(RUNTIME, SUPER_SEED);
TerrainBatchScratch scratch = new TerrainBatchScratch();
double[] batched = batch(curved);
for (int index = 0; index < POINT_COUNT; index++) {
double expected = signedPow(combined.getHeight(RUNTIME, xs[index], zs[index], SUPER_SEED), exponent) * OPACITY;
String point = "exponent " + exponent + " multiplicitive " + multiplicitive + " point " + index;
assertEquals(point + " scalar", expected, curved.getHeight(RUNTIME, xs[index], zs[index], SUPER_SEED), TOLERANCE);
assertEquals(point + " program", expected, program.height(scratch, xs[index], zs[index]), TOLERANCE);
assertEquals(point + " batch", expected, batched[index], TOLERANCE);
}
}
}
}
@Test
public void exponentChangesTheOutput() {
IrisGenerator flat = generator(false, 1D);
IrisGenerator curved = generator(false, 1D).setExponent(3D);
boolean anyDifference = false;
for (int index = 0; index < POINT_COUNT; index++) {
anyDifference |= flat.getHeight(RUNTIME, xs[index], zs[index], SUPER_SEED) != curved.getHeight(RUNTIME, xs[index], zs[index], SUPER_SEED);
}
assertTrue(anyDifference);
}
@Test
public void applyExponentKeepsTheSignOfNegativeValues() {
assertEquals(-8D, IrisGenerator.applyExponent(-2D, 3D), TOLERANCE);
assertEquals(-Math.sqrt(2D), IrisGenerator.applyExponent(-2D, 0.5D), TOLERANCE);
assertEquals(-0.3D, IrisGenerator.applyExponent(-0.3D, 1D), 0D);
}
@Test
public void exponentAtOrBelowZeroIsRejectedOnEveryPath() {
for (double exponent : new double[]{0D, -1D, Double.NaN, Double.POSITIVE_INFINITY}) {
IrisGenerator broken = generator(false, OPACITY).setExponent(exponent);
assertThrows(IllegalArgumentException.class, () -> broken.getHeight(RUNTIME, 1D, 1D, SUPER_SEED));
assertThrows(IllegalArgumentException.class, () -> broken.compileProgram(RUNTIME, SUPER_SEED));
}
}
@Test
public void jsonExponentDeserializesIntoTheField() {
IrisGenerator generator = new Gson().fromJson("{\"exponent\":3}", IrisGenerator.class);
assertEquals(3D, generator.getExponent(), 0D);
assertEquals(1D, new Gson().fromJson("{}", IrisGenerator.class).getExponent(), 0D);
}
private double[] batch(IrisGenerator generator) {
double[] out = new double[POINT_COUNT];
generator.compileProgram(RUNTIME, SUPER_SEED).heights(new TerrainBatchScratch(), xs, zs, POINT_COUNT, out);
return out;
}
private static IrisGenerator generator(boolean multiplicitive, double opacity) {
KList<IrisNoiseGenerator> composite = new KList<>();
composite.add(new IrisNoiseGenerator().setStyle(NoiseStyle.SIMPLEX.style()).setSeed(11L).setZoom(1.3D).setOpacity(0.7D));
composite.add(new IrisNoiseGenerator().setStyle(NoiseStyle.PERLIN.style()).setSeed(23L).setZoom(2.1D).setOpacity(1.4D));
return new IrisGenerator().setComposite(composite)
.setMultiplicitive(multiplicitive)
.setSeed(5L)
.setZoom(37D)
.setOpacity(opacity);
}
private static double signedPow(double value, double exponent) {
return value < 0 ? -Math.pow(-value, exponent) : Math.pow(value, exponent);
}
private static void assertBits(double expected, double actual) {
assertEquals(Double.doubleToRawLongBits(expected), Double.doubleToRawLongBits(actual));
}
}
@@ -0,0 +1,288 @@
package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.SeedManager;
import art.arcane.iris.generation.terrain.IrisDimensionCarvingEntry;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG;
import com.google.gson.Gson;
import org.junit.Test;
import java.util.Objects;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class IrisGeneratorStyleSeedTest {
private static final long WORLD_SEED = 7_777_123L;
private static final long OTHER_WORLD_SEED = -90_210L;
private static final long STYLE_SEED = 510L;
private static final long FRACTURE_SEED = 77L;
private static final long CALLER_SEED = 4242L;
private static final int GRID_SIZE = 36;
private static final double GRID_STEP_BLOCKS = 53.7D;
@Test
public void seededStyleIgnoresTheCallerRandom() {
PackRuntime data = dataOfWorld(WORLD_SEED);
IrisGeneratorStyle style = seededSimplex(STYLE_SEED);
assertArrayEquals(samples(style.createNoCache(new RNG(1L), data)), samples(style.createNoCache(new RNG(2L), data)), 0D);
assertSame(style.create(new RNG(1L), data), style.create(new RNG(2L), data));
assertSame(style.create(1L, data), style.create(new RNG(3L), data));
}
@Test
public void separateStyleInstancesWithTheSameSeedShareOneNoise() {
PackRuntime data = dataOfWorld(WORLD_SEED);
CNG first = seededSimplex(STYLE_SEED).setZoom(2.5D).createNoCache(new RNG(1L), data);
CNG second = seededSimplex(STYLE_SEED).setZoom(2.5D).createNoCache(new RNG(2L), data);
CNG otherSeed = seededSimplex(STYLE_SEED + 1).setZoom(2.5D).createNoCache(new RNG(1L), data);
assertArrayEquals(samples(first), samples(second), 0D);
assertFalse(java.util.Arrays.equals(samples(first), samples(otherSeed)));
}
@Test
public void seededStyleFollowsTheWorldSeed() {
IrisGeneratorStyle style = seededSimplex(STYLE_SEED);
double[] world = samples(style.createNoCache(new RNG(1L), dataOfWorld(WORLD_SEED)));
double[] otherWorld = samples(style.createNoCache(new RNG(1L), dataOfWorld(OTHER_WORLD_SEED)));
assertFalse(java.util.Arrays.equals(world, otherWorld));
}
@Test
public void generatorCacheNeverHandsBackAnotherWorldsNoise() {
IrisGeneratorStyle style = seededSimplex(STYLE_SEED);
PackRuntime world = dataOfWorld(WORLD_SEED);
PackRuntime otherWorld = dataOfWorld(OTHER_WORLD_SEED);
CNG first = style.create(new RNG(1L), world);
CNG second = style.create(new RNG(1L), otherWorld);
assertFalse(java.util.Arrays.equals(samples(first), samples(second)));
assertSame(first, style.create(new RNG(1L), world));
}
@Test
public void seededStyleEqualsTheUnseededCopyBuiltWithTheRolledRandom() {
for (PackRuntime data : new PackRuntime[]{dataOfWorld(WORLD_SEED), dataWithoutEngine()}) {
long worldSeed = worldSeedOf(data);
IrisGeneratorStyle seeded = seededSimplex(STYLE_SEED).setZoom(3D).setExponent(1.5D);
IrisGeneratorStyle unseeded = simplex().setZoom(3D).setExponent(1.5D);
CNG expected = unseeded.createNoCache(new RNG(rolled(worldSeed, STYLE_SEED)), data);
assertArrayEquals(samples(expected), samples(seeded.createNoCache(new RNG(CALLER_SEED), data)), 0D);
assertArrayEquals(samples(expected), samples(seeded.create(new RNG(CALLER_SEED), data)), 0D);
assertArrayEquals(samples(expected), samples(seeded.createForLayer(new RNG(CALLER_SEED), data, 1)), 0D);
}
}
@Test
public void seededStyleWithPlainFractureEqualsTheUnseededCopy() {
for (PackRuntime data : new PackRuntime[]{dataOfWorld(WORLD_SEED), dataWithoutEngine()}) {
long worldSeed = worldSeedOf(data);
IrisGeneratorStyle seeded = seededSimplex(STYLE_SEED).setFracture(plainFracture());
IrisGeneratorStyle unseeded = simplex().setFracture(plainFracture());
CNG expected = unseeded.createNoCache(new RNG(rolled(worldSeed, STYLE_SEED)), data);
assertArrayEquals(samples(expected), samples(seeded.createNoCache(new RNG(CALLER_SEED), data)), 0D);
}
}
@Test
public void seededFractureRollsOnItsOwnUnderAnUnseededParent() {
for (PackRuntime data : new PackRuntime[]{dataOfWorld(WORLD_SEED), dataWithoutEngine()}) {
long worldSeed = worldSeedOf(data);
IrisGeneratorStyle seededFracture = plainFracture().setSeed(FRACTURE_SEED);
IrisGeneratorStyle actual = simplex().setFracture(seededFracture);
CNG expected = simplex().createNoCache(new RNG(CALLER_SEED), data);
expected.fractureWith(plainFracture().createNoCache(new RNG(rolled(worldSeed, FRACTURE_SEED)), data), seededFracture.getMultiplier());
assertArrayEquals(samples(expected), samples(actual.createNoCache(new RNG(CALLER_SEED), data)), 0D);
assertArrayEquals(samples(actual.createNoCache(new RNG(1L), data)), samples(actual.createNoCache(new RNG(1L), data)), 0D);
}
}
@Test
public void seededFractureInsideASeededStyleRollsFromItsOwnSeed() {
for (PackRuntime data : new PackRuntime[]{dataOfWorld(WORLD_SEED), dataWithoutEngine()}) {
long worldSeed = worldSeedOf(data);
IrisGeneratorStyle seededFracture = plainFracture().setSeed(FRACTURE_SEED);
IrisGeneratorStyle actual = seededSimplex(STYLE_SEED).setFracture(seededFracture);
CNG expected = simplex().createNoCache(new RNG(rolled(worldSeed, STYLE_SEED)), data);
expected.fractureWith(plainFracture().createNoCache(new RNG(rolled(worldSeed, FRACTURE_SEED)), data), seededFracture.getMultiplier());
assertArrayEquals(samples(expected), samples(actual.createNoCache(new RNG(CALLER_SEED), data)), 0D);
assertArrayEquals(samples(expected), samples(actual.create(new RNG(CALLER_SEED), data)), 0D);
}
}
@Test
public void rollForPinsTheRolledRandomSeed() {
IrisGeneratorStyle style = seededSimplex(510L);
assertEquals(1582317604285492835L, style.rollFor(new RNG(1L), engineOfWorld(0L)).getSeed());
assertEquals(1582317604285492835L, style.rollFor(new RNG(2L), null).getSeed());
IrisGeneratorStyle negativeSeed = seededSimplex(-7L);
assertEquals(-8111716878092126206L, negativeSeed.rollFor(new RNG(1L), engineOfWorld(123456789L)).getSeed());
}
@Test
public void rollForKeepsTheCallerRandomOfAnUnseededStyle() {
RNG caller = new RNG(CALLER_SEED);
assertSame(caller, simplex().rollFor(caller, engineOfWorld(WORLD_SEED)));
assertSame(caller, simplex().rollFor(caller, null));
assertFalse(simplex().isSeeded());
assertTrue(seededSimplex(0L).isSeeded());
}
@Test
public void unseededStylesHashExactlyAsBeforeTheSeedField() {
int simplexHash = Objects.hash((Object) null, 0, 1D, 0, 1D, 0, 1D, 1D, 0D, "SIMPLEX");
int fractureHash = Objects.hash((Object) null, 0, 1D, 0, 1D, 0, 1D, 1D, 0D, "STATIC");
assertEquals(simplexHash, simplex().prebakeSignature());
assertEquals(Objects.hash((Object) null, 0, 1D, fractureHash, 1D, 0, 1D, 1D, 0D, "SIMPLEX"),
simplex().setFracture(new IrisGeneratorStyle(NoiseStyle.STATIC)).prebakeSignature());
assertEquals(Objects.hash("expr", 0, 2D, 0, 3D, 8, 4D, 5D, 0.5D, null),
new IrisGeneratorStyle().setStyle(null).setExpression("expr").setMultiplier(2D).setExponent(3D)
.setCacheSize(8).setZoom(4D).setCellularZoom(5D).setCellularFrequency(0.5D).prebakeSignature());
}
@Test
public void seedChangesTheSignatureOnlyWhenSet() {
int unseeded = simplex().prebakeSignature();
assertNotEquals(unseeded, seededSimplex(STYLE_SEED).prebakeSignature());
assertNotEquals(seededSimplex(STYLE_SEED).prebakeSignature(), seededSimplex(STYLE_SEED + 1).prebakeSignature());
assertEquals(seededSimplex(STYLE_SEED).prebakeSignature(), seededSimplex(STYLE_SEED).prebakeSignature());
assertNotEquals(unseeded, simplex().setFracture(plainFracture().setSeed(FRACTURE_SEED)).prebakeSignature());
}
@Test
public void seedReadsFromJsonAndDefaultsToNull() {
Gson gson = new Gson();
assertEquals(Long.valueOf(510L), gson.fromJson("{\"seed\": 510}", IrisGeneratorStyle.class).getSeed());
assertEquals(Long.valueOf(-9_007_199_254_740_993L), gson.fromJson("{\"seed\": -9007199254740993}", IrisGeneratorStyle.class).getSeed());
assertNull(gson.fromJson("{\"zoom\": 2}", IrisGeneratorStyle.class).getSeed());
assertNull(new IrisGeneratorStyle().getSeed());
}
@Test
public void seededChildStyleIgnoresTheChildScale() {
PackRuntime runtime = dataOfWorld(WORLD_SEED);
IrisBiome biome = biomeWithChildStyle(seededSimplex(STYLE_SEED));
double[] unscaled = samples(biome.getChildrenGenerator(runtime, CALLER_SEED, 1D));
assertArrayEquals(unscaled, samples(biome.getChildrenGenerator(runtime, CALLER_SEED, 4D)), 0D);
assertArrayEquals(unscaled, samples(biome.getChildrenGenerator(runtime, CALLER_SEED, 0.25D)), 0D);
assertArrayEquals(unscaled, samples(biome.getChildrenGenerator(runtime, new RNG(5L), 123, 9D)), 0D);
}
@Test
public void unseededChildStyleStillScales() {
PackRuntime runtime = dataOfWorld(WORLD_SEED);
IrisBiome biome = biomeWithChildStyle(simplex());
double[] unscaled = samples(biome.getChildrenGenerator(runtime, CALLER_SEED, 1D));
double[] scaled = samples(biome.getChildrenGenerator(runtime, CALLER_SEED, 4D));
assertFalse(java.util.Arrays.equals(unscaled, scaled));
}
@Test
public void seededCarvingChildStyleIgnoresTheShrinkFactor() {
PackRuntime data = dataOfWorld(WORLD_SEED);
double[] unscaled = samples(carvingEntry(seededSimplex(STYLE_SEED), 1D).getChildrenGenerator(CALLER_SEED, data));
assertArrayEquals(unscaled, samples(carvingEntry(seededSimplex(STYLE_SEED), 4D).getChildrenGenerator(CALLER_SEED, data)), 0D);
assertFalse(java.util.Arrays.equals(
samples(carvingEntry(simplex(), 1D).getChildrenGenerator(CALLER_SEED, data)),
samples(carvingEntry(simplex(), 4D).getChildrenGenerator(CALLER_SEED, data))));
}
private static IrisDimensionCarvingEntry carvingEntry(IrisGeneratorStyle childStyle, double shrinkFactor) {
return new IrisDimensionCarvingEntry().setId("deep-caves").setChildStyle(childStyle).setChildShrinkFactor(shrinkFactor);
}
private static IrisBiome biomeWithChildStyle(IrisGeneratorStyle childStyle) {
return new IrisBiome().setChildStyle(childStyle);
}
private static IrisGeneratorStyle simplex() {
return new IrisGeneratorStyle(NoiseStyle.SIMPLEX);
}
private static IrisGeneratorStyle seededSimplex(long seed) {
return simplex().setSeed(seed);
}
private static IrisGeneratorStyle plainFracture() {
return new IrisGeneratorStyle(NoiseStyle.SIMPLEX).setZoom(2D).setMultiplier(30D);
}
private static Engine engineOfWorld(long worldSeed) {
Engine engine = mock(Engine.class);
when(engine.getSeedManager()).thenReturn(new SeedManager(worldSeed));
return engine;
}
private static PackRuntime dataOfWorld(long worldSeed) {
return PackRuntime.forEngine(engineOfWorld(worldSeed), mock(IrisData.class));
}
private static PackRuntime dataWithoutEngine() {
return PackRuntime.standalone(mock(IrisData.class));
}
private static long worldSeedOf(PackRuntime data) {
Engine engine = data.engine();
return engine == null ? 0L : engine.getSeedManager().getSeed();
}
private static long rolled(long worldSeed, long styleSeed) {
return mix(worldSeed ^ mix(styleSeed));
}
private static long mix(long value) {
long mixed = value + 0x9E3779B97F4A7C15L;
mixed = (mixed ^ (mixed >>> 30)) * 0xBF58476D1CE4E5B9L;
mixed = (mixed ^ (mixed >>> 27)) * 0x94D049BB133111EBL;
return mixed ^ (mixed >>> 31);
}
private static double[] samples(CNG generator) {
double[] sampled = new double[GRID_SIZE * GRID_SIZE * 2];
int cursor = 0;
for (int xIndex = 0; xIndex < GRID_SIZE; xIndex++) {
for (int zIndex = 0; zIndex < GRID_SIZE; zIndex++) {
double x = (xIndex - GRID_SIZE / 2) * GRID_STEP_BLOCKS + 0.31D;
double z = (zIndex - GRID_SIZE / 2) * GRID_STEP_BLOCKS - 0.77D;
sampled[cursor++] = generator.noise(x, z);
sampled[cursor++] = generator.noise(x, 41.5D, z);
}
}
return sampled;
}
}
@@ -20,7 +20,7 @@ public class NoiseSeedCohesionTest {
private static final double[] COORDINATES = {-29_999_983.25D, -513D, -64D, -1D, 0D, 0.125D, 17D, 64D, 8192D, 29_999_983.25D};
private static final double PINNED_SAMPLE_SCALE = 1.0E9D;
private static final long PINNED_HASH_WINDOWS = 6074446696529759284L;
private static final long PINNED_HASH_MAC = -602781966673993721L;
private static final long PINNED_HASH_MAC = 2357650562814976004L;
@Test
public void allStylesRetainPinnedSamples() {
@@ -339,6 +339,96 @@ public class IrisComplexSurfaceBiomeTest {
assertSame(shore, resolved);
}
@Test
public void shorelineWithoutShoreBiomesKeepsTheBaseBiome() {
IrisBiome base = mock(IrisBiome.class);
IrisRegion region = mock(IrisRegion.class);
doReturn(false).when(base).isShore();
doReturn(3D).when(region).getShoreHeight(12D, 18D);
doReturn(1D).when(region).getShoreHeightMin();
doReturn(5D).when(region).getShoreHeightMax();
IrisBiome resolved = IrisComplex.resolveSurfaceBiome(
63D,
base,
region,
12D,
18D,
63D,
constant(base),
constant(base),
IrisComplex.NO_BIOMES,
constantSlope(0D)
);
assertSame(base, resolved);
}
@Test
public void belowFluidWithoutSeaBiomesKeepsTheBaseBiome() {
IrisBiome base = mock(IrisBiome.class);
IrisRegion region = mock(IrisRegion.class);
doReturn(false).when(base).isShore();
doReturn(true).when(base).isLand();
doReturn(false).when(base).isAquatic();
doReturn(3D).when(region).getShoreHeight(12D, 18D);
doReturn(1D).when(region).getShoreHeightMin();
doReturn(5D).when(region).getShoreHeightMax();
IrisBiome resolved = IrisComplex.resolveSurfaceBiome(
50D,
base,
region,
12D,
18D,
63D,
constant(base),
IrisComplex.NO_BIOMES,
IrisComplex.NO_BIOMES,
constantSlope(0D)
);
assertSame(base, resolved);
}
@Test
public void continentSeaInARegionWithoutSeaBiomesPicksFromLand() {
IrisRegion sealess = mock(IrisRegion.class);
IrisRegion coastal = mock(IrisRegion.class);
IrisBiome sea = mock(IrisBiome.class);
java.util.Map<IrisRegion, java.util.Map<InferredType, ProceduralStream<IrisBiome>>> streams =
IrisComplex.compileInferredBiomeStreams(List.of(sealess, coastal),
(IrisRegion region, InferredType type) -> region == sealess && type == InferredType.SEA
? IrisComplex.NO_BIOMES : constant(sea));
assertEquals(InferredType.LAND, IrisComplex.baseType(streams, sealess, InferredType.SEA));
assertEquals(InferredType.LAND, IrisComplex.baseType(streams, sealess, InferredType.LAND));
assertEquals(InferredType.SEA, IrisComplex.baseType(streams, coastal, InferredType.SEA));
assertTrue(IrisComplex.lacks(streams, InferredType.SEA));
assertFalse(IrisComplex.lacks(IrisComplex.compileInferredBiomeStreams(List.of(coastal),
(IrisRegion region, InferredType type) -> constant(sea)), InferredType.SEA));
}
@Test
public void regionWithoutUsableLandBiomesFailsNamingIt() {
IrisRegion listed = new IrisRegion();
listed.setLoadKey("void");
listed.setLandBiomes(new KList<>("gone"));
IrisRegion unlisted = new IrisRegion();
unlisted.setLoadKey("bare");
IllegalStateException excluded = assertThrows(IllegalStateException.class,
() -> IrisComplex.requireLandBiomes(listed, new KList<>()));
IllegalStateException empty = assertThrows(IllegalStateException.class,
() -> IrisComplex.requireLandBiomes(unlisted, new KList<>()));
KList<IrisBiome> land = new KList<>(new IrisBiome());
assertTrue(excluded.getMessage(), excluded.getMessage().contains("Region 'void'"));
assertTrue(excluded.getMessage(), excluded.getMessage().contains("Minecraft version"));
assertTrue(empty.getMessage(), empty.getMessage().contains("Region 'bare'"));
assertSame(land, IrisComplex.requireLandBiomes(unlisted, land));
}
@Test
public void raisedAquaticBiomeReturnsToLand() {
IrisBiome aquatic = mock(IrisBiome.class);
@@ -0,0 +1,68 @@
package art.arcane.iris.pack;
import art.arcane.volmlib.util.json.JSONObject;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class PackValidatorImportedFeatureHeightTest {
@Rule
public TemporaryFolder pack = new TemporaryFolder();
@Test
public void deeperWorldWithFeaturesEnabledWarns() {
List<String> warnings = validate(featuresEnabled(true).put("dimensionHeight", height(-256, 512)));
assertEquals(1, warnings.size());
assertTrue(warnings.get(0), warnings.get(0).contains("Dimension 'overworld' runs importedFeatures in a -256..512 world"));
}
@Test
public void vanillaOverworldHeightStaysSilent() {
assertTrue(validate(featuresEnabled(true).put("dimensionHeight", height(-64, 320))).isEmpty());
assertTrue(validate(featuresEnabled(true)).isEmpty());
}
@Test
public void shorterWorldInsideVanillaBoundsWarns() {
List<String> warnings = validate(featuresEnabled(true).put("dimensionHeight", height(0, 256)));
assertEquals(1, warnings.size());
assertTrue(warnings.get(0), warnings.get(0).contains("in a 0..256 world"));
}
@Test
public void warningPointsAtTheSettingsThatRemoveOres() {
String warning = validate(featuresEnabled(true).put("dimensionHeight", height(-256, 512))).get(0);
assertTrue(warning, warning.contains("importedFeatures.disabled"));
assertTrue(warning, warning.contains("disabledSteps"));
assertTrue(warning, !warning.contains("importedFeatures.steps"));
}
@Test
public void disabledOrAbsentFeaturesStaySilent() {
assertTrue(validate(featuresEnabled(false).put("dimensionHeight", height(-256, 512))).isEmpty());
assertTrue(validate(new JSONObject().put("dimensionHeight", height(-256, 512))).isEmpty());
}
private List<String> validate(JSONObject dimension) {
List<String> warnings = new ArrayList<>();
PackDimensionValidator.validateImportedFeatureHeight(pack.getRoot(), "overworld", dimension, warnings);
return warnings;
}
private static JSONObject featuresEnabled(boolean enabled) {
return new JSONObject().put("importedFeatures", new JSONObject().put("enabled", enabled));
}
private static JSONObject height(int min, int max) {
return new JSONObject().put("min", min).put("max", max);
}
}
@@ -0,0 +1,55 @@
package art.arcane.iris.pack;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class PackValidatorRegionLandBiomesTest {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Test
public void regionWithoutLandBiomesIsBlockingAndNamesTheRegion() throws IOException {
List<String> errors = validate("{\"seaBiomes\":[\"ocean\"],\"shoreBiomes\":[\"ocean\"]}");
assertEquals(List.of("Region 'island' has no landBiomes; every region needs at least one land biome."), errors);
}
@Test
public void regionWithOnlyMissingLandBiomesIsBlocking() throws IOException {
List<String> errors = validate("{\"landBiomes\":[\"absent\"],\"seaBiomes\":[\"ocean\"]}");
assertEquals(List.of("Region 'island' has no landBiomes; every region needs at least one land biome."), errors);
}
@Test
public void regionWithLandButNoSeaOrShoreBiomesIsValid() throws IOException {
List<String> errors = validate("{\"landBiomes\":[\"ocean\"]}");
assertTrue(errors.toString(), errors.isEmpty());
}
private List<String> validate(String region) throws IOException {
File pack = temporaryFolder.newFolder();
File dimensions = new File(pack, PackValidator.DIMENSIONS_FOLDER);
File regions = new File(pack, "regions");
File biomes = new File(pack, "biomes");
assertTrue(dimensions.mkdirs() && regions.mkdirs() && biomes.mkdirs());
File dimension = new File(dimensions, "main.json");
Files.writeString(dimension.toPath(), "{\"regions\":[\"island\"]}");
Files.writeString(new File(regions, "island.json").toPath(), region);
Files.writeString(new File(biomes, "ocean.json").toPath(), "{}");
List<String> errors = new ArrayList<>();
PackDimensionValidator.validateDimensions(pack, new File[]{dimension}, errors, new ArrayList<>());
return errors;
}
}
@@ -0,0 +1,45 @@
package art.arcane.iris.pack.datapack.v1217;
import art.arcane.iris.pack.datapack.IDataFixer.Dimension;
import art.arcane.volmlib.util.json.JSONObject;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class DataFixerV1217BedRuleTest {
private final DataFixerV1217 fixer = new DataFixerV1217();
@Test
public void overworldBedsSleepWhenDark() {
JSONObject rule = bedRule(Dimension.OVERWORLD);
assertEquals("when_dark", rule.getString("can_sleep"));
assertEquals("always", rule.getString("can_set_spawn"));
assertTrue(rule.has("error_message"));
}
@Test
public void netherBedsAreDestroyedOnUse() {
assertDestroyedOnUse(bedRule(Dimension.NETHER));
}
@Test
public void endBedsAreDestroyedOnUse() {
assertDestroyedOnUse(bedRule(Dimension.END));
}
private JSONObject bedRule(Dimension dimension) {
return fixer.createDimension(dimension, -64, 384, 384, null)
.getJSONObject("attributes")
.getJSONObject("minecraft:gameplay/bed_rule");
}
private static void assertDestroyedOnUse(JSONObject rule) {
assertEquals("never", rule.getString("can_sleep"));
assertEquals("never", rule.getString("can_set_spawn"));
assertTrue(rule.getBoolean("destroy_on_use"));
assertFalse(rule.has("explodes"));
}
}
@@ -0,0 +1,241 @@
package art.arcane.iris.pack.loading;
import art.arcane.iris.generation.runtime.PreservationRegistry;
import art.arcane.iris.spi.IrisServices;
import art.arcane.iris.world.history.GenerationRegistryContract;
import art.arcane.iris.testsupport.CapturedLog;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.nio.file.Files;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
/**
* A pack typo is reached per chunk, so a loader miss or an unreadable file must be stated once per pack,
* resource type and key, and stated again after the pack's caches are cleared (hotload).
*/
public class ResourceLoaderOnceWarningTest {
private static final String MISSING = "Couldn't find ";
private static final String UNREADABLE = "Couldn't read ";
private static final byte[] GARBAGE = {1, 2, 3, 4, 5, 6, 7, 8, 9};
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
private CapturedLog log;
private IrisData data;
@Before
public void openPack() throws Exception {
log = CapturedLog.bind(temporaryFolder.newFolder("platform-data"));
IrisServices.register(PreservationRegistry.class, mock(PreservationRegistry.class));
data = openPack("pack");
assertNotNull(log.messages() + " " + log.reportedErrors(), data.getObjectLoader());
}
private IrisData openPack(String name) throws Exception {
IrisData opened = IrisData.openRuntime(temporaryFolder.newFolder(name));
opened.bindGenerationRegistryContract(GenerationRegistryContract.empty());
return opened;
}
@After
public void closePack() {
data.close();
IrisServices.remove(PreservationRegistry.class);
log.close();
}
@Test
public void theSameMissingKeyWarnsOnce() {
data.getObjectLoader().load("trees/typo");
data.getObjectLoader().load("trees/typo");
data.getObjectLoader().findFile("trees/typo");
assertEquals(1, log.warnings(MISSING).size());
}
@Test
public void aDifferentKeyWarnsSeparately() {
data.getObjectLoader().load("trees/typo");
data.getObjectLoader().load("trees/other-typo");
assertEquals(2, log.warnings(MISSING).size());
}
@Test
public void theSameKeyInAnotherResourceTypeWarnsSeparately() {
data.getObjectLoader().load("shared");
data.getMatterLoader().load("shared");
data.getImageLoader().load("shared");
assertEquals(3, log.warnings(MISSING).size());
}
@Test
public void theSameKeyInAnotherPackWarnsSeparately() throws Exception {
IrisData other = openPack("other-pack");
try {
data.getObjectLoader().load("shared");
other.getObjectLoader().load("shared");
assertEquals(2, log.warnings(MISSING).size());
} finally {
other.close();
}
}
@Test
public void literalNullRefusalWarnsOnce() {
data.getObjectLoader().load("null");
data.getObjectLoader().load("null");
data.getObjectLoader().findFile("null");
data.getObjectLoader().findFile("null");
assertEquals(2, log.warnings("Refusing ").size());
}
@Test
public void clearingTheListsLetsTheSameMissingKeyWarnAgain() {
data.getObjectLoader().load("trees/typo");
data.getObjectLoader().load("trees/typo");
assertEquals(1, log.warnings(MISSING).size());
data.clearLists();
data.getObjectLoader().load("trees/typo");
assertEquals(2, log.warnings(MISSING).size());
}
/** Studio hotload rebuilds the pack's loaders through hotloaded() (or reopens it) without clearLists(). */
@Test
public void rebuildingThePackLoadersLetsTheSameMissingKeyWarnAgain() {
data.getObjectLoader().load("trees/typo");
data.hotloaded();
data.getObjectLoader().load("trees/typo");
assertEquals(2, log.warnings(MISSING).size());
}
@Test
public void reopeningThePackFolderLetsTheSameMissingKeyWarnAgain() {
data.getObjectLoader().load("trees/typo");
IrisData reopened = IrisData.openRuntime(data.getDataFolder());
try {
reopened.getObjectLoader().load("trees/typo");
assertEquals(2, log.warnings(MISSING).size());
} finally {
reopened.close();
}
}
@Test
public void clearingOnePackKeepsAnotherPacksKeysClaimed() throws Exception {
IrisData other = openPack("other-pack");
try {
data.getObjectLoader().load("shared");
other.getObjectLoader().load("shared");
data.clearLists();
data.getObjectLoader().load("shared");
other.getObjectLoader().load("shared");
assertEquals(3, log.warnings(MISSING).size());
} finally {
other.close();
}
}
@Test
public void aPackWhosePathIsAPrefixOfAnotherIsNotReset() throws Exception {
IrisData longer = openPack("pack-two");
try {
longer.getObjectLoader().load("shared");
data.clearLists();
longer.getObjectLoader().load("shared");
assertEquals(1, log.warnings(MISSING).size());
} finally {
longer.close();
}
}
@Test
public void anUnreadableObjectWarnsOnceAndReportsItsStackOnce() throws Exception {
writeGarbage(data.getObjectLoader(), "broken.iob");
data.getObjectLoader().load("broken");
data.getObjectLoader().load("broken");
data.getObjectLoader().load("broken");
assertEquals(1, log.warnings(UNREADABLE).size());
assertEquals(1, log.reportedErrors().size());
}
@Test
public void anUnreadableMatterObjectWarnsOnceAndReportsItsStackOnce() throws Exception {
writeGarbage(data.getMatterLoader(), "broken.mat");
data.getMatterLoader().load("broken");
data.getMatterLoader().load("broken");
assertEquals(1, log.warnings(UNREADABLE).size());
assertEquals(1, log.reportedErrors().size());
}
@Test
public void anUnreadableImageWarnsOnce() throws Exception {
writeGarbage(data.getImageLoader(), "broken.png");
data.getImageLoader().load("broken");
data.getImageLoader().load("broken");
assertEquals(1, log.warnings(UNREADABLE).size());
}
@Test
public void aDifferentUnreadableFileWarnsSeparately() throws Exception {
writeGarbage(data.getObjectLoader(), "broken.iob");
writeGarbage(data.getObjectLoader(), "also-broken.iob");
data.getObjectLoader().load("broken");
data.getObjectLoader().load("also-broken");
assertEquals(2, log.warnings(UNREADABLE).size());
assertEquals(2, log.reportedErrors().size());
}
@Test
public void clearingTheListsReportsTheStackAgainForTheNextFirstWarning() throws Exception {
writeGarbage(data.getObjectLoader(), "broken.iob");
data.getObjectLoader().load("broken");
data.clearLists();
data.getObjectLoader().load("broken");
assertEquals(2, log.warnings(UNREADABLE).size());
assertEquals(2, log.reportedErrors().size());
}
private void writeGarbage(ResourceLoader<?> loader, String fileName) throws Exception {
File folder = new File(temporaryFolder.getRoot(), "pack/" + loader.getFolderName());
Files.createDirectories(folder.toPath());
Files.write(new File(folder, fileName).toPath(), GARBAGE);
}
}
@@ -84,7 +84,7 @@ public class SchemaBuilderIdentityTest {
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
private static final String EXPECTED_SCHEMA_DIGEST = "907c3f1d5a33281be801a23d86c4b8e1b5d933ddfc3445b179ece7898aa65d46";
private static final String EXPECTED_SCHEMA_DIGEST = "af3c848472e7de2d87d4a0aceb52f107d967249a35485d2247c1066e75ccfbd7";
private static final List<Class<?>> SCHEMA_ROOTS = List.of(
IrisDimension.class,
@@ -138,6 +138,68 @@ public class IrisLoggingTest {
assertEquals(List.of(LogLevel.WARN), levels);
}
@Test
public void forgettingAPrefixReleasesOnlyTheKeysUnderIt() {
String scope = uniqueKey() + "|";
String otherScope = uniqueKey() + "|";
assertTrue(IrisLogging.warnOnce(scope + "a", "a"));
assertTrue(IrisLogging.warnOnce(scope + "b", "b"));
assertTrue(IrisLogging.warnOnce(otherScope + "a", "other"));
levels.clear();
IrisLogging.forgetOnceKeys(scope);
assertTrue(IrisLogging.warnOnce(scope + "a", "a"));
assertTrue(IrisLogging.warnOnce(scope + "b", "b"));
assertFalse(IrisLogging.warnOnce(otherScope + "a", "other"));
assertEquals(List.of(LogLevel.WARN, LogLevel.WARN, LogLevel.DEBUG), levels);
}
@Test
public void forgettingANullOrEmptyPrefixKeepsEveryKeyClaimed() {
String key = uniqueKey();
assertTrue(IrisLogging.warnOnce(key, "claimed"));
IrisLogging.forgetOnceKeys(null);
IrisLogging.forgetOnceKeys("");
assertFalse(IrisLogging.warnOnce(key, "claimed"));
}
@Test
public void pastTheCapTheLeastRecentlySeenKeyIsDroppedAndWarnsAgain() {
String stale = uniqueKey();
String recurring = uniqueKey();
assertTrue(IrisLogging.warnOnce(stale, "stale"));
assertTrue(IrisLogging.warnOnce(recurring, "recurring"));
for (int filler = 2; filler < IrisLogging.MAX_ONCE_KEYS; filler++) {
IrisLogging.warnOnce(uniqueKey(), "filler");
}
assertFalse(IrisLogging.warnOnce(recurring, "recurring"));
String newer = uniqueKey();
levels.clear();
assertTrue(IrisLogging.warnOnce(newer, "new condition"));
assertFalse(IrisLogging.warnOnce(newer, "new condition"));
assertFalse(IrisLogging.warnOnce(recurring, "recurring"));
assertTrue(IrisLogging.warnOnce(stale, "stale"));
assertEquals(List.of(LogLevel.WARN, LogLevel.DEBUG, LogLevel.DEBUG, LogLevel.WARN), levels);
}
@Test
public void aSuppliedMessageIsOnlyBuiltWhenStated() {
String key = uniqueKey();
int[] built = {0};
assertTrue(IrisLogging.warnOnce(key, () -> "built " + ++built[0]));
assertFalse(IrisLogging.warnOnce(key, () -> "built " + ++built[0]));
assertEquals(1, built[0]);
assertEquals(List.of(LogLevel.WARN), levels);
assertEquals(List.of("built 1"), messages);
}
private void bindCapturingPlatform() {
IrisPlatform platform = mock(IrisPlatform.class);
capturingPlatform = platform;
@@ -0,0 +1,84 @@
package art.arcane.iris.structure.object;
import art.arcane.iris.generation.runtime.PreservationRegistry;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.spi.IrisServices;
import art.arcane.iris.testsupport.CapturedLog;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import art.arcane.iris.world.history.GenerationRegistryContract;
import art.arcane.volmlib.util.collection.KList;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
public class IrisObjectPlacementOnceWarningTest {
private static final String MISSING_TABLE = "Couldn't find loot table ";
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
private CapturedLog log;
private IrisData data;
@Before
public void openPack() throws Exception {
log = CapturedLog.bind(temporaryFolder.newFolder("platform-data"));
IrisServices.register(PreservationRegistry.class, mock(PreservationRegistry.class));
data = IrisData.openRuntime(temporaryFolder.newFolder("pack"));
data.bindGenerationRegistryContract(GenerationRegistryContract.empty());
}
@After
public void closePack() {
data.close();
IrisServices.remove(PreservationRegistry.class);
log.close();
}
@Test
public void aMissingLootTableWarnsOnceAcrossPlacements() {
lookUpTable(placementWithLoot("chests/typo"));
lookUpTable(placementWithLoot("chests/typo"));
assertEquals(1, log.warnings(MISSING_TABLE).size());
}
@Test
public void aDifferentMissingLootTableWarnsSeparately() {
lookUpTable(placementWithLoot("chests/typo"));
lookUpTable(placementWithLoot("chests/other-typo"));
assertEquals(2, log.warnings(MISSING_TABLE).size());
}
@Test
public void clearingThePackListsLetsTheSameMissingLootTableWarnAgain() {
lookUpTable(placementWithLoot("chests/typo"));
data.clearLists();
lookUpTable(placementWithLoot("chests/typo"));
assertEquals(2, log.warnings(MISSING_TABLE).size());
}
private static IrisObjectPlacement placementWithLoot(String tableName) {
IrisObjectLoot loot = new IrisObjectLoot();
loot.setName(tableName);
IrisObjectPlacement placement = new IrisObjectPlacement();
placement.setLoot(new KList<IrisObjectLoot>().qadd(loot));
return placement;
}
private void lookUpTable(IrisObjectPlacement placement) {
placement.getCache(data);
}
}
@@ -0,0 +1,85 @@
package art.arcane.iris.testsupport;
import art.arcane.iris.spi.IrisPlatform;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.LogLevel;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
/**
* Binds a mock platform that records every log line and reported stack trace. {@link #close()} unbinds it,
* which also clears the JVM-global warn-once keys, so tests using it do not depend on order.
*/
public final class CapturedLog implements AutoCloseable {
private final List<LogLevel> levels = new ArrayList<>();
private final List<String> messages = new ArrayList<>();
private final List<Throwable> reportedErrors = new ArrayList<>();
private CapturedLog() {
}
public static CapturedLog bind() {
return bind(null);
}
/**
* @param dataRoot where the platform keeps its data files (settings are read from there on first use);
* null for a platform that has none
*/
public static CapturedLog bind(File dataRoot) {
IrisPlatforms.unbind();
CapturedLog log = new CapturedLog();
IrisPlatform platform = mock(IrisPlatform.class);
if (dataRoot != null) {
doReturn(dataRoot).when(platform).dataFolder();
doAnswer(invocation -> {
Object[] segments = invocation.getArguments();
return new File(dataRoot, String.join(File.separator, Arrays.copyOf(segments, segments.length, String[].class)));
}).when(platform).dataFile(any(String[].class));
}
doAnswer(invocation -> {
log.levels.add(invocation.getArgument(0, LogLevel.class));
log.messages.add(invocation.getArgument(1, String.class));
return null;
}).when(platform).log(any(LogLevel.class), anyString());
doAnswer(invocation -> {
log.reportedErrors.add(invocation.getArgument(0, Throwable.class));
return null;
}).when(platform).reportError(any(Throwable.class));
IrisPlatforms.bind(platform);
return log;
}
/** Messages logged at WARN that start with {@code prefix}. */
public List<String> warnings(String prefix) {
List<String> found = new ArrayList<>();
for (int index = 0; index < messages.size(); index++) {
if (levels.get(index) == LogLevel.WARN && messages.get(index).startsWith(prefix)) {
found.add(messages.get(index));
}
}
return found;
}
public List<String> messages() {
return messages;
}
public List<Throwable> reportedErrors() {
return reportedErrors;
}
@Override
public void close() {
IrisPlatforms.unbind();
}
}
@@ -11,8 +11,10 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.zip.CRC32;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.GZIPOutputStream;
@@ -118,6 +120,215 @@ public final class SavedTerrainRecoveryScanTest {
assertFalse(Files.exists(world.resolve("region")));
}
@Test
public void warmCacheReusesStatusWithoutDecodingUnchangedChunks() throws Exception {
for (int regionBytes : new int[]{8192, 4 * 1024 * 1024}) {
Path world = temporaryFolder.newFolder().toPath();
Path cacheFile = world.resolve("iris").resolve(SavedTerrainStatusCache.FILE_NAME);
writeChunkGrid(world);
WorldChunkInventory inventory = WorldChunkInventory.scan(world);
WorldChunkInventory expected = uncachedScan(world, inventory);
assertSameChunks(inventory, expected, cachedScan(world, cacheFile, regionBytes, (x, z) -> false));
assertTrue(Files.isRegularFile(cacheFile));
corruptAll(world);
assertThrows(IOException.class, () -> uncachedScan(world, inventory));
assertSameChunks(inventory, expected, cachedScan(world, cacheFile, regionBytes, (x, z) -> false));
assertSameChunks(inventory, expected, cachedScan(world, cacheFile, regionBytes, (x, z) -> false));
}
}
@Test
public void ownershipIsAppliedOnEveryScanInsteadOfCached() throws Exception {
Path world = temporaryFolder.newFolder().toPath();
Path cacheFile = world.resolve("iris").resolve(SavedTerrainStatusCache.FILE_NAME);
write(world, new Chunk(0, 0, 2, false, encode(0, 0, "minecraft:biomes")), OLD);
write(world, new Chunk(1, 0, 2, false, encode(1, 0, "minecraft:full")), OLD);
WorldChunkInventory inventory = WorldChunkInventory.scan(world);
WorldChunkInventory first = cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> x == 0);
assertEquals(2, first.size());
WorldChunkInventory second = cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false);
assertEquals(1, second.size());
assertTrue(second.contains(1, 0));
corruptAll(world);
assertEquals(2, cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> x == 0).size());
WorldChunkInventory third = cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false);
assertEquals(1, third.size());
assertTrue(third.contains(1, 0));
assertSameChunks(inventory, second, third);
}
@Test
public void changedHeaderWordsAreDecodedAgain() throws Exception {
Path world = temporaryFolder.newFolder().toPath();
Path cacheFile = world.resolve("iris").resolve(SavedTerrainStatusCache.FILE_NAME);
writeChunkGrid(world);
cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false);
write(world, new Chunk(2, 0, 2, false, encode(2, 0, "minecraft:biomes")), OLD);
WorldChunkInventory inventory = WorldChunkInventory.scan(world);
WorldChunkInventory rewritten = cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false);
assertSameChunks(inventory, uncachedScan(world, inventory), rewritten);
assertFalse(rewritten.contains(2, 0));
cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false);
setTimestamp(world, 3, 0, OLD + 1);
corrupt(world, 3, 0);
IOException failure = assertThrows(IOException.class,
() -> cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false));
assertTrue(failure.getMessage().contains("3,0"));
}
@Test
public void chunksSavedNearTheScanTimeAreDecodedAgain() throws Exception {
Path world = temporaryFolder.newFolder().toPath();
Path cacheFile = world.resolve("iris").resolve(SavedTerrainStatusCache.FILE_NAME);
writeChunkGrid(world);
long now = System.currentTimeMillis() / 1000L;
setTimestamp(world, 4, 1, now);
setTimestamp(world, 5, 1, now + 30);
cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false);
corrupt(world, 4, 1);
assertTrue(assertThrows(IOException.class,
() -> cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false)).getMessage().contains("4,1"));
write(world, new Chunk(4, 1, 2, false, encode(4, 1, "minecraft:full")), OLD);
cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false);
corrupt(world, 5, 1);
assertTrue(assertThrows(IOException.class,
() -> cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false)).getMessage().contains("5,1"));
}
@Test
public void externalPayloadsAreDecodedOnEveryScan() throws Exception {
Path world = temporaryFolder.newFolder().toPath();
Path cacheFile = world.resolve("iris").resolve(SavedTerrainStatusCache.FILE_NAME);
writeChunkGrid(world);
write(world, new Chunk(6, 2, 2, false, encode(6, 2, "minecraft:full")), OLD);
write(world, new Chunk(7, 2, 2, true, encode(7, 2, "minecraft:full")), OLD);
for (int regionBytes : new int[]{8192, 4 * 1024 * 1024}) {
cachedScan(world, cacheFile, regionBytes, (x, z) -> false);
Path external = world.resolve("region").resolve("c.7.2.mcc");
byte[] payload = Files.readAllBytes(external);
Files.write(external, new byte[]{1, 2, 3});
assertTrue(assertThrows(IOException.class,
() -> cachedScan(world, cacheFile, regionBytes, (x, z) -> false)).getMessage().contains("7,2"));
Files.write(external, payload);
}
}
@Test
public void unreadableCacheFallsBackToAFullScan() throws Exception {
Path world = temporaryFolder.newFolder().toPath();
Path cacheFile = world.resolve("iris").resolve(SavedTerrainStatusCache.FILE_NAME);
writeChunkGrid(world);
WorldChunkInventory inventory = WorldChunkInventory.scan(world);
WorldChunkInventory expected = uncachedScan(world, inventory);
cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false);
byte[] valid = Files.readAllBytes(cacheFile);
byte[] flipped = valid.clone();
flipped[flipped.length / 2] ^= 1;
byte[] wrongVersion = valid.clone();
wrongVersion[7] = 99;
CRC32 checksum = new CRC32();
checksum.update(wrongVersion, 0, wrongVersion.length - Long.BYTES);
ByteBuffer.wrap(wrongVersion, wrongVersion.length - Long.BYTES, Long.BYTES).putLong(checksum.getValue());
for (byte[] broken : new byte[][]{flipped, wrongVersion, new byte[]{1, 2, 3}, new byte[0]}) {
Files.write(cacheFile, broken);
assertSameChunks(inventory, expected, cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false));
}
Files.write(cacheFile, flipped);
corrupt(world, 1, 1);
assertThrows(IOException.class, () -> cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false));
}
@Test
public void staticStartupScanWritesTheCacheOnlyAfterSuccess() throws Exception {
Path world = temporaryFolder.newFolder().toPath();
Path cacheFile = world.resolve("iris").resolve(SavedTerrainStatusCache.FILE_NAME);
writeChunkGrid(world);
corrupt(world, 1, 1);
assertThrows(IOException.class, () -> SavedTerrainRecoveryScan.scan(world, WorldChunkInventory.scan(world),
(x, z) -> false, cacheFile));
assertFalse(Files.exists(cacheFile));
write(world, new Chunk(1, 1, 2, false, encode(1, 1, "minecraft:full")), OLD);
WorldChunkInventory inventory = WorldChunkInventory.scan(world);
WorldChunkInventory expected = uncachedScan(world, inventory);
assertSameChunks(inventory, expected, SavedTerrainRecoveryScan.scan(world, inventory, (x, z) -> false, cacheFile));
corruptAll(world);
assertSameChunks(inventory, expected, SavedTerrainRecoveryScan.scan(world, inventory, (x, z) -> false, cacheFile));
}
private static final long OLD = 1_700_000_000L;
private static void writeChunkGrid(Path world) throws IOException {
for (int x = 0; x < 12; x++) {
for (int z = 0; z < 12; z++) {
write(world, new Chunk(x, z, 2, false,
encode(x, z, (x + z) % 3 == 0 ? "minecraft:biomes" : "minecraft:full")), OLD);
}
}
write(world, new Chunk(40, 3, 2, false, encode(40, 3, "minecraft:noise")), OLD);
}
private static WorldChunkInventory uncachedScan(Path world, WorldChunkInventory inventory) throws IOException {
try (SavedTerrainChunkReader.StatusReader reader = new SavedTerrainChunkReader.StatusReader(world)) {
return inventory.filter((x, z) -> SavedTerrainChunk.hasTerrain(reader.readStatus(x, z)));
}
}
private static WorldChunkInventory cachedScan(Path world, Path cacheFile, int regionBytes,
WorldChunkInventory.ChunkPredicate retained) throws IOException {
SavedTerrainStatusCache cache = SavedTerrainStatusCache.load(cacheFile, world);
WorldChunkInventory result;
try (SavedTerrainRecoveryScan scan = new SavedTerrainRecoveryScan(world,
new SavedTerrainRecoveryScan.Limits(2, regionBytes), cache)) {
result = scan.filter(WorldChunkInventory.scan(world), retained);
}
cache.save();
return result;
}
private static void assertSameChunks(WorldChunkInventory inventory, WorldChunkInventory expected,
WorldChunkInventory actual) throws IOException {
assertEquals(expected.size(), actual.size());
inventory.forEach((x, z) -> assertEquals(expected.contains(x, z), actual.contains(x, z)));
}
private static void corruptAll(Path world) throws IOException {
WorldChunkInventory.scan(world).forEach((x, z) -> corrupt(world, x, z));
}
private static void corrupt(Path world, int x, int z) throws IOException {
try (RandomAccessFile file = new RandomAccessFile(regionFile(world, x, z).toFile(), "rw")) {
file.seek(slot(x, z) * 4L);
int sector = file.readInt() >>> 8;
file.seek(sector * 4096L + 4);
int compression = file.readUnsignedByte();
file.seek(sector * 4096L + 4);
file.writeByte((compression & 128) | 99);
}
}
private static void setTimestamp(Path world, int x, int z, long seconds) throws IOException {
try (RandomAccessFile file = new RandomAccessFile(regionFile(world, x, z).toFile(), "rw")) {
file.seek(4096L + slot(x, z) * 4L);
file.writeInt((int) seconds);
}
}
private static Path regionFile(Path world, int x, int z) {
return world.resolve("region").resolve("r." + Math.floorDiv(x, 32) + "." + Math.floorDiv(z, 32) + ".mca");
}
private static int slot(int x, int z) {
return Math.floorMod(z, 32) * 32 + Math.floorMod(x, 32);
}
private static void write(Path world, Chunk chunk, long timestamp) throws IOException {
write(world, chunk);
setTimestamp(world, chunk.x(), chunk.z(), timestamp);
}
private static byte[] encode(int x, int z, String status) throws IOException {
CompoundTag root = new CompoundTag();
root.putInt("xPos", x);
@@ -0,0 +1,78 @@
package art.arcane.iris.world.loot;
import art.arcane.iris.integration.ExternalDataSVC;
import art.arcane.iris.spi.IrisServices;
import art.arcane.iris.testsupport.CapturedLog;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import art.arcane.volmlib.util.math.RNG;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class IrisLootOnceWarningTest {
private static final String UNKNOWN_MATERIAL = "Unknown Material: ";
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
private CapturedLog log;
@Before
public void captureLogAndRegisterEmptyProvider() {
log = CapturedLog.bind();
ExternalDataSVC external = mock(ExternalDataSVC.class);
when(external.getItemStack(any(), any())).thenReturn(Optional.empty());
IrisServices.register(ExternalDataSVC.class, external);
}
@After
public void release() {
IrisServices.remove(ExternalDataSVC.class);
log.close();
}
@Test
public void anUnknownMaterialWarnsOncePerType() {
IrisLoot loot = lootOf("mymod:ruby");
resolve(loot, 1);
resolve(loot, 2);
resolve(lootOf("mymod:ruby"), 3);
assertEquals(1, log.warnings(UNKNOWN_MATERIAL).size());
}
@Test
public void aDifferentUnknownMaterialWarnsSeparately() {
resolve(lootOf("mymod:ruby"), 1);
resolve(lootOf("mymod:sapphire"), 1);
assertEquals(2, log.warnings(UNKNOWN_MATERIAL).size());
}
private static IrisLoot lootOf(String type) {
IrisLoot loot = new IrisLoot();
loot.setType(type);
return loot;
}
/**
* The warning is logged before the AIR fallback is built, and building an ItemStack needs a Bukkit
* server this test does not have.
*/
private static void resolve(IrisLoot loot, long seed) {
try {
loot.get(false, new RNG(seed));
} catch (NullPointerException noBukkitServer) {
// expected: see above
}
}
}
@@ -18,9 +18,11 @@
package art.arcane.iris.spi;
import java.util.Collections;
import java.util.IllegalFormatException;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Supplier;
import java.util.regex.Pattern;
/**
@@ -35,8 +37,14 @@ import java.util.regex.Pattern;
* Internal to Iris; not a published integration surface.
*/
public final class IrisLogging {
private static final int MAX_ONCE_KEYS = 512;
private static final Set<String> ONCE_KEYS = ConcurrentHashMap.newKeySet();
static final int MAX_ONCE_KEYS = 512;
private static final Map<String, Boolean> ONCE_KEYS = Collections.synchronizedMap(
new LinkedHashMap<>(64, 0.75F, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<String, Boolean> eldest) {
return size() > MAX_ONCE_KEYS;
}
});
private static final Pattern LEGACY_COLOR = Pattern.compile("(?i)\\u00a7[0-9A-FK-ORX]");
private static final Pattern MINI_MESSAGE_TAG = Pattern.compile("(?i)</?(?:reset|bold|b|italic|i|underlined?|u|strikethrough|st|obfuscated?|obf|black|dark_blue|dark_green|dark_aqua|dark_red|dark_purple|gold|gray|dark_gray|blue|green|aqua|red|light_purple|yellow|white|gradient|font|hover|click|rainbow)(?::[^>\\n]{0,96})?>|<#[0-9a-f]{6}>");
@@ -88,7 +96,8 @@ public final class IrisLogging {
* Logs at {@link LogLevel#WARN} the first time {@code key} is seen and at {@link LogLevel#DEBUG} every
* time after, for a condition that is worth stating once but is reached per block, per sample or per
* chunk. Returns true when the warning was the one that got stated, so a caller can attach a stack trace
* or other one-off detail to it.
* or other one-off detail to it. At most {@link #MAX_ONCE_KEYS} keys are held; past that the least recently
* seen key is dropped and warns again the next time it comes up.
*
* @see #resetOnceKeys()
*/
@@ -96,6 +105,19 @@ public final class IrisLogging {
return once(LogLevel.WARN, key, format, args);
}
/**
* {@link #warnOnce(String, String, Object...)} for a message that is costly to build: {@code message} is
* only called when the warning is stated, and a repeat logs nothing.
*/
public static boolean warnOnce(String key, Supplier<String> message) {
if (isRepeat(key)) {
return false;
}
emit(LogLevel.WARN, message == null ? "null" : String.valueOf(message.get()));
return true;
}
/**
* {@link #warnOnce(String, String, Object...)} at {@link LogLevel#ERROR}.
*/
@@ -199,9 +221,24 @@ public final class IrisLogging {
ONCE_KEYS.clear();
}
/**
* Forgets only the once-keys that start with {@code prefix}, so one scope (a pack that was just
* hotloaded) can warn again while every other scope stays claimed. A null or empty prefix is ignored
* rather than clearing everything; {@link #resetOnceKeys()} is the global reset.
*/
public static void forgetOnceKeys(String prefix) {
if (prefix == null || prefix.isEmpty()) {
return;
}
synchronized (ONCE_KEYS) {
ONCE_KEYS.keySet().removeIf(key -> key.startsWith(prefix));
}
}
private static boolean once(LogLevel level, String key, String format, Object... args) {
String message = format(format, args);
if (!claim(key)) {
if (isRepeat(key)) {
emit(LogLevel.DEBUG, message);
return false;
}
@@ -212,14 +249,11 @@ public final class IrisLogging {
/**
* The cap is what keeps a key space nobody bounded - a block name, a biome name, a mod id - from becoming
* a leak. Past it nothing new is claimed, which drops later conditions to debug rather than growing.
* a leak. Eviction is least recently seen, so a condition that keeps recurring stays claimed while one
* that stopped makes room for new ones.
*/
private static boolean claim(String key) {
if (ONCE_KEYS.size() >= MAX_ONCE_KEYS) {
return false;
}
return ONCE_KEYS.add(key == null ? "null" : key);
private static boolean isRepeat(String key) {
return ONCE_KEYS.put(key == null ? "null" : key, Boolean.TRUE) != null;
}
private static void emit(LogLevel level, String message) {