Compare commits

...
18 Commits
Author SHA1 Message Date
Brian Fopiano e3b595a712 Size palette layer caches
- Hold every depth seed of a layer's thickness
- Widen lock-free recent slots to cover consecutive depth seeds
- Share one generator for seeded palette layer styles
- Test cached depth generators against fresh builds
2026-12-03 10:42:50 -05:00
Brian Fopiano ecc4413d19 Type expression loader explicitly
- Replace var with ResourceLoader<IrisExpression> in style check
2026-12-03 10:22:52 -05:00
_Saros_ c7a2af98a5 Share seed-free expression layer generators
- Reuse one generator for seed-independent expression layers
- Check expression variables and functions for seed use
- Test sharing, seeded nesting and cyclic references
2026-12-03 10:22:16 -05:00
Brian Fopiano 94648946d9 Drop packedCompactPayload
- Remove the line; the compact payload is the only format
2026-12-01 10:37:26 -05:00
Brian Fopiano ba9694083b Adopt packaging standard
- Ship the Bukkit runtime as a compact payload
- Drop packaging lines that now match the plugin defaults
- Verify native providers from PackedJar.readRuntime entries
- Remove the unused xz dependency from buildSrc
- Drop hand-written META-INF/maven excludes in mod builds
- Keep native boundary checks on in the mod adapters
2026-12-01 08:28:43 -05:00
Brian Fopiano 02f6379808 Import SurvivalAnswer from block
- Follow SurvivalAnswer to the VolmLib nativelib block package
2026-11-30 15:40:36 -05:00
Piexel f7084b244f Let the server decide where plants stand
- Ask the native canSurvive rule in BukkitBlockState.canPlaceOnto
- Fall back to the block table when the rule cannot answer
- Clear remembered answers on resource and CraftEngine reloads
- Drop the post stage foliage check that never saw decorations
- Test vanilla placement rules, fallbacks and concurrent lookups
2026-11-30 11:06:48 -05:00
Brian Fopiano 1bc7843a52 Move CodeMC repo to codemc.io
- Replace dead repo.codemc.org host with repo.codemc.io
- Fixes runtime download of paralithic on fresh installs
2026-11-30 08:04:09 -05:00
Brian Fopiano b0b6e54d2d Match bed rule key to version
- Write explodes for 26.1.2 and 26.2 bed rules
- Rename explodes to destroy_on_use on 26.3
- Test bed rules for both fixer versions
2026-11-29 05:06:51 -05: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
75 changed files with 3658 additions and 211 deletions

No files matched your search

@@ -0,0 +1,262 @@
package art.arcane.iris.probe;
import art.arcane.volmlib.nativelib.common.block.GroundSurvival;
import art.arcane.volmlib.nativelib.minecraft26_2.modded.ModdedBlockState;
import art.arcane.volmlib.nativelib.block.SurvivalAnswer;
import net.minecraft.core.BlockPos;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/** Both platforms ask the server's own canSurvive rule where a plant may stand, against the real block tags. */
public final class HeadlessGroundSurvivalTest {
private static final Logger NATIVE_LOG = Logger.getLogger("VolmLib-Native");
@BeforeClass
public static void bootstrap() {
HeadlessNativeBootstrap.initialize();
}
@Test
public void grassStandsOnSoilButNotOnStone() {
assertPlacement(true, Blocks.SHORT_GRASS, Blocks.GRASS_BLOCK);
assertPlacement(true, Blocks.SHORT_GRASS, Blocks.PODZOL);
assertPlacement(false, Blocks.SHORT_GRASS, Blocks.STONE);
assertPlacement(false, Blocks.POPPY, Blocks.STONE);
assertPlacement(false, Blocks.FERN, Blocks.OAK_LEAVES);
}
@Test
public void cactusNeedsSandOrCactus() {
for (Block ground : new Block[]{Blocks.CACTUS, Blocks.SAND, Blocks.RED_SAND}) {
assertPlacement(true, Blocks.CACTUS, ground);
}
assertPlacement(false, Blocks.CACTUS, Blocks.STONE);
}
@Test
public void sugarCaneNeedsItsSubstrate() {
for (Block ground : new Block[]{Blocks.SUGAR_CANE, Blocks.GRASS_BLOCK, Blocks.DIRT, Blocks.COARSE_DIRT,
Blocks.PODZOL, Blocks.MYCELIUM, Blocks.ROOTED_DIRT, Blocks.MOSS_BLOCK, Blocks.PALE_MOSS_BLOCK,
Blocks.MUD, Blocks.MUDDY_MANGROVE_ROOTS, Blocks.SAND, Blocks.RED_SAND, Blocks.SUSPICIOUS_SAND}) {
assertPlacement(true, Blocks.SUGAR_CANE, ground);
}
for (Block ground : new Block[]{Blocks.STONE, Blocks.GRAVEL, Blocks.CLAY, Blocks.DIRT_PATH,
Blocks.FARMLAND, Blocks.AIR, Blocks.WATER}) {
assertPlacement(false, Blocks.SUGAR_CANE, ground);
}
}
@Test
public void netherGroundCoverAcceptsNyliumAndSoulSoilButRejectsBarrenBlocks() {
for (Block plant : new Block[]{Blocks.CRIMSON_ROOTS, Blocks.WARPED_ROOTS, Blocks.NETHER_SPROUTS}) {
for (Block ground : new Block[]{Blocks.CRIMSON_NYLIUM, Blocks.WARPED_NYLIUM, Blocks.SOUL_SOIL}) {
assertPlacement(true, plant, ground);
}
for (Block ground : new Block[]{Blocks.NETHERRACK, Blocks.STONE, Blocks.GRAVEL, Blocks.AIR}) {
assertPlacement(false, plant, ground);
}
}
}
@Test
public void blocksThatRestOnNoGroundStillFit() {
assertPlacement(true, Blocks.WALL_TORCH, Blocks.STONE);
assertPlacement(true, Blocks.VINE, Blocks.SAND);
assertPlacement(true, Blocks.COCOA, Blocks.STONE);
}
@Test
public void deadBushStaysOffGrassAsPacksExpect() {
assertPlacement(true, Blocks.DEAD_BUSH, Blocks.SAND);
assertPlacement(false, Blocks.DEAD_BUSH, Blocks.GRASS_BLOCK);
}
@Test
public void nothingStandsOnAir() {
assertPlacement(false, Blocks.VINE, Blocks.AIR);
assertPlacement(false, Blocks.SHORT_GRASS, Blocks.CAVE_AIR);
}
@Test
public void plantsThatReadMoreOfTheLevelAreAnsweredByTheirOwnRule() {
List<LogRecord> warnings = warningsDuring(() -> {
assertPlacement(true, Blocks.BAMBOO, Blocks.GRASS_BLOCK);
assertPlacement(false, Blocks.BAMBOO, Blocks.STONE);
assertPlacement(true, Blocks.KELP, Blocks.STONE);
assertPlacement(false, Blocks.KELP, Blocks.MAGMA_BLOCK);
assertPlacement(true, Blocks.SEAGRASS, Blocks.SAND);
assertPlacement(false, Blocks.SEAGRASS, Blocks.MAGMA_BLOCK);
assertPlacement(true, Blocks.LILY_PAD, Blocks.WATER);
assertPlacement(false, Blocks.LILY_PAD, Blocks.STONE);
assertPlacement(true, Blocks.SWEET_BERRY_BUSH, Blocks.GRASS_BLOCK);
assertPlacement(false, Blocks.SWEET_BERRY_BUSH, Blocks.STONE);
assertPlacement(true, Blocks.BROWN_MUSHROOM, Blocks.STONE);
assertPlacement(true, Blocks.RED_MUSHROOM, Blocks.MYCELIUM);
assertPlacement(false, Blocks.BROWN_MUSHROOM, Blocks.GLASS);
assertPlacement(true, Blocks.CRIMSON_FUNGUS, Blocks.CRIMSON_NYLIUM);
assertPlacement(false, Blocks.WARPED_FUNGUS, Blocks.NETHERRACK);
assertPlacement(true, Blocks.WHEAT, Blocks.FARMLAND);
assertPlacement(false, Blocks.CARROTS, Blocks.DIRT);
});
assertEquals(messages(warnings), 0, warnings.size());
}
@Test
public void everyVanillaBlockIsAnsweredWithoutFailingOpen() {
GroundSurvival survival = new GroundSurvival();
List<LogRecord> warnings = warningsDuring(() -> {
for (Block plant : BuiltInRegistries.BLOCK) {
if (needsARunningPaperServer(plant)) {
continue;
}
for (Block ground : new Block[]{Blocks.GRASS_BLOCK, Blocks.STONE, Blocks.WATER}) {
survival.canSurviveOn(plant.defaultBlockState(), ground.defaultBlockState());
}
}
});
assertEquals(messages(warnings), 0, warnings.size());
}
@Test
public void aRuleThatThrowsIsLeftUnansweredAndWarnsOncePerBlock() {
BlockState firstState = throwingStateOf(Blocks.SHORT_GRASS);
BlockState secondState = throwingStateOf(Blocks.SHORT_GRASS);
GroundSurvival survival = new GroundSurvival();
List<LogRecord> warnings = warningsDuring(() -> {
for (BlockState plant : new BlockState[]{firstState, secondState}) {
for (Block ground : new Block[]{Blocks.STONE, Blocks.SAND, Blocks.GRASS_BLOCK}) {
assertEquals(SurvivalAnswer.UNANSWERED, survival.canSurviveOn(plant, ground.defaultBlockState()));
}
}
});
assertEquals(messages(warnings), 1, warnings.size());
}
@Test
public void aRuleThatThrowsFallsBackToThePlacementTable() {
ModdedBlockState grass = ModdedBlockState.deferred(throwingStateOf(Blocks.SHORT_GRASS), Map.of(), "iris:test");
warningsDuring(() -> {
assertTrue(grass.canPlaceOnto(wrap(Blocks.GRASS_BLOCK)));
assertFalse(grass.canPlaceOnto(wrap(Blocks.STONE)));
});
}
@Test
public void aRuleThatOnlyAnswersForSomeGroundsDoesNotPassAsAWallBlock() {
BlockState plant = mock(BlockState.class);
when(plant.getBlock()).thenReturn(Blocks.SHORT_GRASS);
when(plant.canSurvive(any(), any())).thenAnswer(asked -> {
LevelReader level = asked.getArgument(0);
BlockPos plantPos = asked.getArgument(1);
if (level.getBlockState(plantPos.below()).is(Blocks.STONE)) {
return false;
}
throw new IllegalStateException("custom rule failed");
});
GroundSurvival survival = new GroundSurvival();
warningsDuring(() -> assertEquals(SurvivalAnswer.UNANSWERED,
survival.canSurviveOn(plant, Blocks.STONE.defaultBlockState())));
}
@Test
public void generatorThreadsAskingAtOnceGetTheSameAnswers() {
Block[] plants = {Blocks.SHORT_GRASS, Blocks.CACTUS, Blocks.SUGAR_CANE, Blocks.VINE, Blocks.BROWN_MUSHROOM};
Block[] grounds = {Blocks.GRASS_BLOCK, Blocks.SAND, Blocks.STONE, Blocks.WATER};
GroundSurvival alone = new GroundSurvival();
GroundSurvival shared = new GroundSurvival();
List<Integer> threads = Arrays.asList(new Integer[16]);
threads.parallelStream().forEach(ignored -> {
for (Block plant : plants) {
for (Block ground : grounds) {
assertEquals(plant + " on " + ground,
alone.canSurviveOn(plant.defaultBlockState(), ground.defaultBlockState()),
shared.canSurviveOn(plant.defaultBlockState(), ground.defaultBlockState()));
}
}
});
}
// Paper's chorus plant reads Paper's global configuration, which only a running server loads.
private static boolean needsARunningPaperServer(Block plant) {
return plant == Blocks.CHORUS_PLANT;
}
private static BlockState throwingStateOf(Block block) {
BlockState state = mock(BlockState.class);
when(state.getBlock()).thenReturn(block);
when(state.isSingletonState()).thenReturn(true);
when(state.canSurvive(any(), any())).thenThrow(new IllegalStateException("custom rule failed"));
return state;
}
private static void assertPlacement(boolean expected, Block plant, Block ground) {
String pair = plant + " on " + ground;
assertEquals("modded " + pair, expected, moddedPlacement(plant, ground));
assertEquals("bukkit native " + pair, expected ? SurvivalAnswer.SURVIVES : SurvivalAnswer.FAILS,
new GroundSurvival().canSurviveOn(plant.defaultBlockState(), ground.defaultBlockState()));
}
private static boolean moddedPlacement(Block plant, Block ground) {
return wrap(plant).canPlaceOnto(wrap(ground));
}
private static ModdedBlockState wrap(Block block) {
return ModdedBlockState.deferred(block.defaultBlockState(), Map.of(), "iris:test");
}
private static List<LogRecord> warningsDuring(Runnable checks) {
List<LogRecord> warnings = new CopyOnWriteArrayList<>();
Handler capture = new Handler() {
@Override
public void publish(LogRecord record) {
if (record.getLevel().intValue() >= Level.WARNING.intValue()) {
warnings.add(record);
}
}
@Override
public void flush() {
}
@Override
public void close() {
}
};
NATIVE_LOG.addHandler(capture);
try {
checks.run();
} finally {
NATIVE_LOG.removeHandler(capture);
}
return warnings;
}
private static String messages(List<LogRecord> warnings) {
StringBuilder text = new StringBuilder();
for (LogRecord warning : warnings) {
text.append(warning.getMessage()).append(" (").append(warning.getThrown()).append(")\n");
}
return text.toString();
}
}
@@ -58,6 +58,7 @@ import art.arcane.iris.platform.agent.AttachSignal;
import art.arcane.iris.platform.bootstrap.Bindings;
import art.arcane.iris.platform.bootstrap.ServerProperties;
import art.arcane.iris.platform.bootstrap.SlimJar;
import art.arcane.iris.platform.bukkit.BlockRulesSVC;
import art.arcane.iris.platform.bukkit.BoardSVC;
import art.arcane.iris.platform.bukkit.BukkitPlatform;
import art.arcane.iris.platform.bukkit.api.IrisApiEventSVC;
@@ -681,6 +682,7 @@ public final class IrisRuntime implements IrisPluginRuntime {
new GlobalCacheSVC(),
new LogFilterSVC(),
new ExternalDataSVC(),
new BlockRulesSVC(),
new EditSVC(),
new ObjectSVC(),
new ObjectStudioSaveService(),
@@ -0,0 +1,24 @@
package art.arcane.iris.platform.bukkit;
import art.arcane.iris.platform.bukkit.nms.INMS;
import art.arcane.iris.platform.bukkit.plugin.IrisService;
import io.papermc.paper.event.server.ServerResourcesReloadedEvent;
import org.bukkit.event.EventHandler;
/** Lets the server's placement rules apply again after a resource reload, which may have changed the block tags they read. */
public class BlockRulesSVC implements IrisService {
@Override
public void onEnable() {
}
@Override
public void onDisable() {
}
@EventHandler
public void onResourcesReloaded(ServerResourcesReloadedEvent event) {
if (INMS.isBound()) {
INMS.get().forgetBlockRules();
}
}
}
+2 -2
View File
@@ -104,7 +104,7 @@ repositories {
name = 'FabricMC'
url = uri('https://maven.fabricmc.net/')
}
maven { url = uri('https://repo.codemc.org/repository/maven-public/') }
maven { url = uri('https://repo.codemc.io/repository/maven-public/') }
maven { url = uri('https://jitpack.io') }
maven { url = uri('https://hub.spigotmc.org/nexus/content/repositories/snapshots/') }
}
@@ -331,7 +331,6 @@ tasks.named('shadowJar', ShadowJar).configure {
if ((int) irisModTarget.java == 21) {
exclude(java21RuntimeExclusions)
}
exclude('META-INF/maven/**')
exclude('META-INF/proguard/**')
exclude('META-INF/*.SF')
exclude('META-INF/*.DSA')
@@ -415,6 +414,7 @@ tasks.named('assemble').configure {
}
pluginPackaging {
nativeBoundaryChecks = true
artifacts {
create('distribution') {
taskName = irisModTarget.fabricRemap ? 'remapJar' : 'shadowJar'
+2 -2
View File
@@ -121,7 +121,7 @@ repositories {
maven fg.forgeMaven
maven fg.minecraftLibsMaven
mavenCentral()
maven { url = uri('https://repo.codemc.org/repository/maven-public/') }
maven { url = uri('https://repo.codemc.io/repository/maven-public/') }
maven { url = uri('https://jitpack.io') }
maven { url = uri('https://hub.spigotmc.org/nexus/content/repositories/snapshots/') }
}
@@ -320,7 +320,6 @@ tasks.named('shadowJar', ShadowJar).configure {
if ((int) irisModTarget.java == 21) {
exclude(java21RuntimeExclusions)
}
exclude('META-INF/maven/**')
exclude('META-INF/proguard/**')
exclude('META-INF/*.SF')
exclude('META-INF/*.DSA')
@@ -377,6 +376,7 @@ tasks.named('assemble').configure {
}
pluginPackaging {
nativeBoundaryChecks = true
artifacts {
create('distribution') {
taskName = 'shadowJar'
@@ -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);
+2 -2
View File
@@ -105,7 +105,7 @@ repositories {
name = 'NeoForged'
url = uri('https://maven.neoforged.net/releases/')
}
maven { url = uri('https://repo.codemc.org/repository/maven-public/') }
maven { url = uri('https://repo.codemc.io/repository/maven-public/') }
maven { url = uri('https://jitpack.io') }
maven { url = uri('https://hub.spigotmc.org/nexus/content/repositories/snapshots/') }
}
@@ -304,7 +304,6 @@ tasks.named('shadowJar', ShadowJar).configure {
if ((int) irisModTarget.java == 21) {
exclude(java21RuntimeExclusions)
}
exclude('META-INF/maven/**')
exclude('META-INF/proguard/**')
exclude('META-INF/*.SF')
exclude('META-INF/*.DSA')
@@ -361,6 +360,7 @@ tasks.named('assemble').configure {
}
pluginPackaging {
nativeBoundaryChecks = true
artifacts {
create('distribution') {
taskName = 'shadowJar'
+7 -8
View File
@@ -1,5 +1,4 @@
import art.arcane.volmit.packaging.PackedJar
import art.arcane.volmit.packaging.PackagingMode
import art.arcane.volmit.packaging.NativeDevelopmentTargets
import io.papermc.paperweight.userdev.PaperweightUser
import io.papermc.paperweight.userdev.PaperweightUserDependenciesExtension
@@ -654,7 +653,7 @@ allprojects {
repositories {
mavenCentral()
maven { url = uri('https://repo.papermc.io/repository/maven-public/') }
maven { url = uri('https://repo.codemc.org/repository/maven-public/') }
maven { url = uri('https://repo.codemc.io/repository/maven-public/') }
maven {
url = uri('https://jitpack.io')
@@ -759,11 +758,6 @@ pluginPackaging {
packedJarAccessors = ['art/arcane/iris/platform/bukkit/plugin/VolmitPlugin#getJarFile']
packedPayloadOnlyPrefixes = ['iris-language-guides/', 'META-INF/iris/generation-kernels/abi-', 'iris/icons/views/', 'iris/datapack/']
packedMaximumBootstrapClasses = 90
stripDirectories = true
stripLocalVariables = true
releaseCompression = providers.gradleProperty('compactRelease')
.map { String value -> value.toBoolean() }
.getOrElse(!PackagingMode.resolve(providers).development())
prunePrefixes = ['art/arcane/volmlib/']
keepPrefixes = ['art/arcane/volmlib/util/matter/slices/', 'art/arcane/volmlib/nativelib/']
shrinkRules = [file('packaging/shrink.pro'), nativeRuntimeRules.get().asFile]
@@ -1010,7 +1004,12 @@ tasks.withType(PackedJar).configureEach {
dependsOn(tasks.named('verifyBukkitArtifact'), nativeRuntime)
nativeArtifacts.set(providers.provider { embeddedNatives() })
doLast { PackedJar task ->
NativeRuntimeArtifacts.verifyPacked(task.outputJar.get().asFile, nativeRuntimeModules, embeddedNatives())
File artifact = task.outputJar.get().asFile
Map<String, byte[]> outer = NativeRuntimeArtifacts.entries(artifact)
Map<String, byte[]> runtime = outer.containsKey('META-INF/volmit/runtime.properties')
? PackedJar.readRuntime(artifact.toPath()) : outer
NativeRuntimeArtifacts.verifyPacked(runtime, outer.get(NativeRuntimeArtifacts.MANIFEST), nativeRuntimeModules,
embeddedNatives())
}
}
-1
View File
@@ -35,7 +35,6 @@ dependencies {
implementation(gradleApi())
implementation('org.ow2.asm:asm:9.10.1')
implementation('org.apache.commons:commons-compress:1.28.0')
implementation('org.tukaani:xz:1.10')
implementation('io.papermc.paperweight:paperweight-userdev:2.0.0-beta.21')
testImplementation('junit:junit:4.13.2')
}
@@ -1,5 +1,4 @@
import org.gradle.api.GradleException;
import org.tukaani.xz.XZInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
@@ -28,7 +27,6 @@ import java.util.zip.ZipInputStream;
public final class NativeRuntimeArtifacts {
public static final String MANIFEST = "META-INF/iris/native-runtime.properties";
public static final String RESOURCES = "META-INF/iris/native/";
private static final String PAYLOAD = "META-INF/volmit/runtime.jar.xz";
private static final String GROUP = "com.github.VolmitSoftware.VolmLib";
private static final String NATIVE = "art/arcane/volmlib/nativelib/";
@@ -99,35 +97,20 @@ public final class NativeRuntimeArtifacts {
}
}
public static void verifyPacked(File artifact, List<String> modules, Map<String, File> natives) throws IOException {
/** Checks the native providers inside {@code runtime}, the entries the plugin runs from, against the resolved build. */
public static void verifyPacked(Map<String, byte[]> runtime, byte[] outerManifest, List<String> modules,
Map<String, File> natives) throws IOException {
requireModules(natives, modules);
Map<String, byte[]> contents;
try (JarFile jar = new JarFile(artifact)) {
JarEntry payload = jar.getJarEntry(PAYLOAD);
if (payload == null) {
contents = read(Files.newInputStream(artifact.toPath()));
} else {
try (InputStream input = new XZInputStream(jar.getInputStream(payload))) {
contents = read(new ByteArrayInputStream(input.readAllBytes()));
}
JarEntry outer = jar.getJarEntry(MANIFEST);
byte[] embedded = contents.get(MANIFEST);
if (outer != null && embedded != null) {
try (InputStream input = jar.getInputStream(outer)) {
if (!Arrays.equals(input.readAllBytes(), embedded)) {
throw new GradleException("Packed native runtime manifests differ");
}
}
}
}
}
byte[] manifest = contents.get(MANIFEST);
byte[] manifest = runtime.get(MANIFEST);
if (manifest == null) {
throw new GradleException("Missing native runtime dependency manifest");
}
if (outerManifest != null && !Arrays.equals(outerManifest, manifest)) {
throw new GradleException("Packed native runtime manifests differ");
}
verifyManifest(manifest, natives);
for (String module : natives.keySet()) {
byte[] provider = contents.get(RESOURCES + module + ".jar");
byte[] provider = runtime.get(RESOURCES + module + ".jar");
if (provider == null) {
throw new GradleException("Missing embedded native provider: " + module);
}
@@ -137,6 +120,18 @@ public final class NativeRuntimeArtifacts {
}
}
public static Map<String, byte[]> entries(File artifact) throws IOException {
Map<String, byte[]> contents = new TreeMap<>();
try (ZipInputStream archive = new ZipInputStream(Files.newInputStream(artifact.toPath()))) {
for (ZipEntry entry = archive.getNextEntry(); entry != null; entry = archive.getNextEntry()) {
if (!entry.isDirectory()) {
contents.put(entry.getName(), archive.readAllBytes());
}
}
}
return contents;
}
private static void verifyManifest(byte[] bytes, Map<String, File> natives) throws IOException {
Properties manifest = new Properties();
manifest.load(new ByteArrayInputStream(bytes));
@@ -163,18 +158,6 @@ public final class NativeRuntimeArtifacts {
}
}
private static Map<String, byte[]> read(InputStream source) throws IOException {
Map<String, byte[]> contents = new TreeMap<>();
try (ZipInputStream archive = new ZipInputStream(source)) {
for (ZipEntry entry = archive.getNextEntry(); entry != null; entry = archive.getNextEntry()) {
if (!entry.isDirectory()) {
contents.put(entry.getName(), archive.readAllBytes());
}
}
}
return contents;
}
private static boolean implementation(String name) {
if (!name.startsWith(NATIVE)) {
return false;
@@ -4,13 +4,11 @@ import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.tukaani.xz.LZMA2Options;
import org.tukaani.xz.XZOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
@@ -22,6 +20,7 @@ import java.util.TreeMap;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
@@ -89,15 +88,35 @@ public class NativeRuntimeArtifactsTest {
public void verifiesTheEmbeddedProviderBytesInsideThePackedRuntime() throws Exception {
Map<String, File> natives = natives();
Map<String, byte[]> runtime = runtime(natives, natives);
NativeRuntimeArtifacts.verifyPacked(packed(runtime), MODULES, natives);
NativeRuntimeArtifacts.verifyPacked(jar("ordinary.jar", runtime), MODULES, natives);
byte[] manifest = runtime.get(NativeRuntimeArtifacts.MANIFEST);
NativeRuntimeArtifacts.verifyPacked(runtime, manifest, MODULES, natives);
NativeRuntimeArtifacts.verifyPacked(runtime, null, MODULES, natives);
Map<String, File> rebuilt = new TreeMap<>(natives);
rebuilt.put("native-v26_2_R1", provider("rebuilt.jar", "art/arcane/volmlib/util/collection/KMap"));
assertThrows(GradleException.class, () -> NativeRuntimeArtifacts.verifyPacked(packed(runtime(natives, rebuilt)),
MODULES, natives));
assertThrows(GradleException.class, () -> NativeRuntimeArtifacts.verifyPacked(runtime(natives, rebuilt),
manifest, MODULES, natives));
Map<String, byte[]> missing = new TreeMap<>(runtime);
missing.remove(NativeRuntimeArtifacts.RESOURCES + "native-v26_2_R1.jar");
assertThrows(GradleException.class, () -> NativeRuntimeArtifacts.verifyPacked(packed(missing), MODULES, natives));
assertThrows(GradleException.class, () -> NativeRuntimeArtifacts.verifyPacked(missing, manifest, MODULES, natives));
}
@Test
public void rejectsAnOuterManifestThatDiffersFromTheRuntimeOne() throws Exception {
Map<String, File> natives = natives();
Map<String, byte[]> runtime = runtime(natives, natives);
byte[] outer = (new String(runtime.get(NativeRuntimeArtifacts.MANIFEST), StandardCharsets.UTF_8) + "extra=1\n")
.getBytes(StandardCharsets.UTF_8);
assertThrows(GradleException.class, () -> NativeRuntimeArtifacts.verifyPacked(runtime, outer, MODULES, natives));
}
@Test
public void readsEveryFileEntryOfAnOrdinaryJar() throws Exception {
Map<String, byte[]> runtime = runtime(natives(), natives());
Map<String, byte[]> read = NativeRuntimeArtifacts.entries(jar("ordinary.jar", runtime));
assertEquals(runtime.keySet(), read.keySet());
for (Map.Entry<String, byte[]> entry : runtime.entrySet()) {
assertArrayEquals(entry.getValue(), read.get(entry.getKey()));
}
}
private Map<String, File> natives() throws IOException {
@@ -137,17 +156,6 @@ public class NativeRuntimeArtifactsTest {
return contents;
}
private File packed(Map<String, byte[]> runtime) throws IOException {
ByteArrayOutputStream compressed = new ByteArrayOutputStream();
try (XZOutputStream xz = new XZOutputStream(compressed, new LZMA2Options(1))) {
xz.write(Files.readAllBytes(jar("payload.jar", runtime).toPath()));
}
Map<String, byte[]> outer = new TreeMap<>();
outer.put(NativeRuntimeArtifacts.MANIFEST, runtime.get(NativeRuntimeArtifacts.MANIFEST));
outer.put("META-INF/volmit/runtime.jar.xz", compressed.toByteArray());
return jar("packed.jar", outer);
}
private File jar(String name, Map<String, byte[]> contents) throws IOException {
Path file = temporary.newFolder().toPath().resolve(name);
try (JarOutputStream jar = new JarOutputStream(Files.newOutputStream(file))) {
+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);
}
@@ -18,27 +18,37 @@
package art.arcane.iris.generation.biome;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.SeedTable;
import art.arcane.volmlib.util.noise.CNG;
/**
* What one engine derives from an {@link IrisBiomePaletteLayer}: the block selection and depth generators of the
* seeds that sample it.
* seeds that sample it. A column walk asks for one layer seed per depth, so the layer table holds the layer's whole
* thickness for a few parent seeds instead of rebuilding a generator on every depth step.
*/
public final class PaletteLayerRuntime {
private static final int LAYER_SEED_CAPACITY = 32;
private static final int LAYER_RECENT_SLOTS = 32;
private static final int MAX_LAYER_RECENT_SLOTS = 4096;
private static final int PARENT_SEEDS_PER_LAYER = 4;
private static final int HEIGHT_SEED_CAPACITY = 32;
private final PackRuntime runtime;
private final SeedTable<CNG> layerGenerators;
private final SeedTable<CNG> heightGenerators;
private final boolean shareGenerator;
public PaletteLayerRuntime(IrisBiomePaletteLayer layer, PackRuntime runtime) {
this.runtime = runtime;
this.layerGenerators = new SeedTable<>(LAYER_SEED_CAPACITY, LAYER_RECENT_SLOTS,
seed -> layer.createLayerGenerator(seed, runtime));
IrisGeneratorStyle style = layer.getStyle();
// A seeded style rolls from its own seed and the world seed, never the caller's, so every depth builds the same noise.
this.shareGenerator = style != null
&& (style.isSeeded() || style.canShareExpressionGenerator(runtime.data()));
int depthSeeds = Math.max(1, Math.max(layer.getMinHeight(), layer.getMaxHeight()));
this.layerGenerators = new SeedTable<>(Math.max(LAYER_SEED_CAPACITY, depthSeeds * PARENT_SEEDS_PER_LAYER),
recentSlots(depthSeeds), seed -> layer.createLayerGenerator(seed, runtime));
this.heightGenerators = new SeedTable<>(HEIGHT_SEED_CAPACITY, IrisBiomePaletteLayer::createHeightGenerator);
}
@@ -48,10 +58,16 @@ public final class PaletteLayerRuntime {
}
public CNG layerGenerator(long seed) {
return layerGenerators.get(seed);
return layerGenerators.get(shareGenerator ? 0L : seed);
}
public CNG heightGenerator(long seed) {
return heightGenerators.get(seed);
}
/** Consecutive depth seeds land in distinct slots when the slot count covers the thickness. */
private static int recentSlots(int depthSeeds) {
int covering = Integer.highestOneBit(Math.min(depthSeeds, MAX_LAYER_RECENT_SLOTS) - 1) << 1;
return Math.clamp(covering, LAYER_RECENT_SLOTS, MAX_LAYER_RECENT_SLOTS);
}
}
@@ -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;
@@ -87,7 +88,7 @@ public class MantleObjectComponent extends IrisMantleComponent {
private static final int BEDROCK_CLEARANCE = 6;
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 +106,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/"))
@@ -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) {
@@ -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);
@@ -21,6 +21,7 @@ package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.image.IrisImageMap;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.pack.loading.ResourceLoader;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.world.history.GenerationKernelRegistry;
@@ -42,7 +43,9 @@ import lombok.experimental.Accessors;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@Snippet("style")
@@ -83,6 +86,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;
@@ -97,6 +102,46 @@ public class IrisGeneratorStyle {
return createNoCache(rng, runtime, 1, 0, false);
}
/**
* Whether this style can share an expression generator across caller seeds within a pack runtime.
*/
public boolean canShareExpressionGenerator(IrisData data) {
return expression != null && canShareExpressionGenerator(data, new HashSet<>());
}
private boolean canShareExpressionGenerator(IrisData data, Set<String> activeExpressions) {
if (getClass() != IrisGeneratorStyle.class || expression == null || data == null
|| fracture != null || cellularFrequency != 0D || cacheSize != 0
|| !activeExpressions.add(expression)) {
return false;
}
try {
ResourceLoader<IrisExpression> loader = data.getExpressionLoader();
IrisExpression source = loader == null ? null : loader.load(expression);
if (source == null || source.getClass() != IrisExpression.class
|| source.getVariables() == null || source.getFunctions() == null) {
return false;
}
for (IrisExpressionLoad variable : source.getVariables()) {
if (variable.getEngineValue() != null || variable.getEngineStreamValue() != null
|| (variable.getStyleValue() != null
&& !variable.getStyleValue().canShareExpressionGenerator(data, activeExpressions))) {
return false;
}
}
for (IrisExpressionFunction function : source.getFunctions()) {
if (function.getEngineStreamValue() != null || function.getStyleValue() == null
|| !function.getStyleValue().canShareExpressionGenerator(data, activeExpressions)) {
return false;
}
}
return true;
} finally {
activeExpressions.remove(expression);
}
}
public CNG createScaledGenerator(RNG rng, PackRuntime runtime, double scaleFactor) {
return createNoCache(rng, runtime).bake().scale(scaleFactor).bake();
}
@@ -119,7 +164,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 +235,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 +304,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");
}
@@ -300,14 +300,6 @@ public class IrisPostModifier extends EngineAssignedModifier<NativeBlockState> {
setPostBlock(x, h + 1, z, result, originX, originZ, currentData);
}
}
if (B.isFoliage(b) || IrisProceduralBlocks.materialKey(b).equals("minecraft:dead_bush")) {
NativeBlockState onto = getPostBlock(x, h, z, originX, originZ, currentData);
if (!B.canPlaceOnto(b, onto) && !B.isDecorant(b)) {
setPostBlock(x, h + 1, z, AIR.get(), originX, originZ, currentData);
}
}
}
public boolean isAir(int x, int y, int z, int originX, int originZ, Hunk<NativeBlockState> currentData) {
@@ -177,6 +177,8 @@ public class IrisDimension extends IrisRegistrant {
private int version = 1;
@Description("When a block key does not exist on the running Minecraft version, generate this block state instead. Keys are base block keys such as minecraft:sulfur; values are full block states. Applies to every palette, decorator, deposit, replace rule and object in this pack. Content that uses a missing block with no fallback here (and no per-entry backup) is excluded from generation on that version and listed at startup.")
private KMap<String, String> blockFallbacks = new KMap<>();
@Description("When true, the pack refuses to load if this Minecraft version lacks content it uses and no fallback covers it, instead of generating without that content. Declared fallbacks (blockFallbacks, block backup) still apply.")
private boolean requireAllContent = false;
@ArrayType(min = 1, type = IrisBlockDrops.class)
@Description("Define custom block drops for this dimension")
private KList<IrisBlockDrops> blockDrops = new KList<>();
@@ -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) {
@@ -8,6 +8,7 @@ import art.arcane.iris.integration.ExternalDataSVC;
import art.arcane.iris.generation.cache.Cache;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.platform.bukkit.BukkitBlockResolution;
import art.arcane.iris.platform.bukkit.nms.INMS;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.spi.IrisServices;
import art.arcane.iris.generation.block.IrisCustomData;
@@ -83,6 +84,7 @@ public class CraftEngineDataProvider extends ExternalDataProvider implements Lis
@EventHandler
public void onReload(CraftEngineReloadEvent event) {
forgetServerBlockRules();
if (!updateContent()) {
return;
}
@@ -92,6 +94,13 @@ public class CraftEngineDataProvider extends ExternalDataProvider implements Lis
}
}
// Custom blocks carry their own placement rules, so answers about them can change with a reload.
private static void forgetServerBlockRules() {
if (INMS.isBound()) {
INMS.get().forgetBlockRules();
}
}
@Override
public @NotNull List<BlockProperty> getBlockProperties(@NotNull Identifier blockId) throws MissingResourceException {
ImmutableBlockState blockState = findBlockState(blockId);
@@ -0,0 +1,100 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2026 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.pack;
import art.arcane.iris.pack.validation.CompatFinding;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
/**
* Which pack files a dimension can reach, found by following every string in its file that names another pack file,
* then every string in those files, and so on. It over-reaches on purpose: a string that matches a key in any folder
* counts, so a finding is only treated as unused when nothing the dimension reaches mentions its subject.
*/
final class PackContentReach {
private static final String SNIPPET_PREFIX = "snippet/";
private static final String PLACEMENT_SUBJECT = "placement";
private static final String PLACEMENT_KEY_SEPARATOR = ", ";
private static final int KEY_LENGTH_LIMIT = 512;
private PackContentReach() {
}
/** Every string reachable from {@code dimensionFile}, plus the dimension's own key. */
static Set<String> referencedFrom(File packFolder, File dimensionFile, String dimensionKey, Collection<String> folders) {
Set<String> reached = new HashSet<>();
Set<File> visited = new HashSet<>();
ArrayDeque<File> pending = new ArrayDeque<>();
pending.add(dimensionFile);
while (!pending.isEmpty()) {
File file = pending.poll();
if (!visited.add(file.getAbsoluteFile())) {
continue;
}
String text;
try {
text = Files.readString(file.toPath(), StandardCharsets.UTF_8);
} catch (IOException | RuntimeException unreadable) {
continue;
}
for (String value : PackValidationIo.listReferencedKeysFromCorpus(text)) {
if (value.isBlank() || value.length() > KEY_LENGTH_LIMIT || value.contains("..") || !reached.add(value)) {
continue;
}
for (String folder : folders) {
queueIfFile(pending, new File(packFolder, folder + "/" + value + ".json"));
}
if (value.startsWith(SNIPPET_PREFIX)) {
queueIfFile(pending, new File(packFolder, value + ".json"));
}
}
}
reached.add(dimensionKey);
return reached;
}
/** Findings without a subject count as reached, so nothing is skipped without a reason. */
static boolean reaches(Set<String> reached, CompatFinding finding) {
String subjectKey = finding.subjectKey();
if (subjectKey.isEmpty() || reached.contains(subjectKey)) {
return true;
}
if (PLACEMENT_SUBJECT.equals(finding.subjectType())) {
for (String objectKey : subjectKey.split(PLACEMENT_KEY_SEPARATOR)) {
if (reached.contains(objectKey)) {
return true;
}
}
}
return false;
}
private static void queueIfFile(ArrayDeque<File> pending, File candidate) {
if (candidate.isFile()) {
pending.add(candidate);
}
}
}
@@ -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")) {
@@ -18,6 +18,7 @@
package art.arcane.iris.pack;
import art.arcane.iris.pack.validation.CompatAction;
import art.arcane.iris.pack.validation.CompatFinding;
import art.arcane.iris.pack.validation.PackCompatReport;
import art.arcane.iris.pack.loading.IrisData;
@@ -38,7 +39,9 @@ import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
@@ -64,6 +67,9 @@ public final class PackValidator {
static final List<String> UNSUPPORTED_STRUCTURE_TRANSFORM_FIELDS = List.of("rotation", "translate", "scale");
static final Pattern RESOURCE_KEY_PATTERN = Pattern.compile("[a-z0-9_.-]+:[a-z0-9/._-]+");
private static final int BLOCKING_REASON_LIMIT = 3;
private static final int MISSING_CONTENT_SUBJECTS_PER_KEY = 3;
private static final String MISSING_CONTENT_KEY_SEPARATOR = " | ";
private static final Set<CompatAction> REMOVING_ACTIONS = EnumSet.of(CompatAction.EXCLUDED, CompatAction.DROPPED);
/**
* Binary assets, not key-bearing registrants: an object is gated through the placements that can place it
* (palette header only) and images carry no registry keys, so loading every one of them here would parse the
@@ -200,9 +206,12 @@ public final class PackValidator {
if (!data.getContentGate().ready()) {
return List.of();
}
boolean dimensionExcluded = loadEverything(packFolder, data, dimensionFiles);
GatedDimensions dimensions = loadEverything(packFolder, data, dimensionFiles);
List<CompatFinding> findings = data.getCompatReport().findings();
applyCompatFindings(minecraftVersion, dimensionExcluded, findings, blockingErrors, warnings);
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);
@@ -225,10 +234,14 @@ public final class PackValidator {
* anything else resolves) and evaluates every placement reachable from the dimensions, regions and biomes, plus
* every static object on each dimension.
*
* @return true when any dimension in the pack cannot generate on this server
* @return whether any dimension in the pack cannot generate on this server, and what each dimension that opted
* into requiring all content can reach
*/
private static boolean loadEverything(File packFolder, IrisData data, File[] dimensionFiles) {
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) {
IrisDimension dimension = data.getDimensionLoader().load(
@@ -238,6 +251,12 @@ public final class PackValidator {
}
if (dimension.isCompatExcluded()) {
dimensionExcluded = true;
} else {
regionKeys.addAll(dimension.getRegions());
}
if (dimension.isRequireAllContent()) {
reachedByRequiringDimension.put(dimension.getLoadKey(), PackContentReach.referencedFrom(
packFolder, dimensionFile, dimension.getLoadKey(), folders));
}
// Static objects gate themselves (the walker never descends into them), so ask each one here.
dimension.evaluateStaticObjectsCompat(data);
@@ -256,7 +275,31 @@ public final class PackValidator {
for (IrisObjectPlacement placement : placements) {
placement.evaluateCompat(data);
}
return dimensionExcluded;
return new GatedDimensions(dimensionExcluded, reachedByRequiringDimension, regionKeys);
}
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) {
@@ -315,9 +358,7 @@ public final class PackValidator {
/** {@code Pack cannot generate on Minecraft 26.1.2: minecraft:sulfur (block), minecraft:camel (entity)} */
static String excludedDimensionError(String minecraftVersion, List<CompatFinding> findings) {
StringBuilder sb = new StringBuilder(96);
sb.append("Pack cannot generate on Minecraft ")
.append(minecraftVersion == null || minecraftVersion.isBlank() ? "unknown" : minecraftVersion)
.append(": ");
sb.append("Pack cannot generate on Minecraft ").append(versionOrUnknown(minecraftVersion)).append(": ");
Set<String> reasons = new LinkedHashSet<>();
if (findings != null) {
for (CompatFinding finding : findings) {
@@ -332,6 +373,60 @@ public final class PackValidator {
return sb.toString();
}
/**
* A dimension with {@code requireAllContent} refuses to load when the gate excluded or dropped anything it can
* reach; content no file of the dimension leads to is left out, and substitutions are declared fallbacks and never
* count.
*/
static void applyRequireAllContent(
String packName,
Map<String, Set<String>> reachedByRequiringDimension,
String minecraftVersion,
List<CompatFinding> findings,
List<String> blockingErrors
) {
if (reachedByRequiringDimension == null || reachedByRequiringDimension.isEmpty()) {
return;
}
List<CompatFinding> removed = removedContent(findings);
for (Map.Entry<String, Set<String>> dimension : reachedByRequiringDimension.entrySet()) {
List<CompatFinding> reached = removed.stream()
.filter(finding -> PackContentReach.reaches(dimension.getValue(), finding))
.toList();
if (!reached.isEmpty()) {
addDistinct(blockingErrors,
List.of(missingContentError(packName, dimension.getKey(), minecraftVersion, reached)));
}
}
}
private static List<CompatFinding> removedContent(List<CompatFinding> findings) {
if (findings == null) {
return List.of();
}
return findings.stream().filter(finding -> REMOVING_ACTIONS.contains(finding.action())).toList();
}
/**
* {@code Dimension 'overworld' in pack 'overworld' uses requireAllContent and content is unavailable on Minecraft
* 26.1.2: minecraft:sulfur (block): excluded biome cave/sulfur at layers[0].palette[1] | ...}
*/
static String missingContentError(
String packName,
String dimensionKey,
String minecraftVersion,
List<CompatFinding> removed
) {
List<String> keyLines = PackCompatReport.of(removed).keyLines(MISSING_CONTENT_SUBJECTS_PER_KEY);
return "Dimension '" + dimensionKey + "' in pack '" + packName
+ "' uses requireAllContent and content is unavailable on Minecraft "
+ versionOrUnknown(minecraftVersion) + ": " + String.join(MISSING_CONTENT_KEY_SEPARATOR, keyLines);
}
private static String versionOrUnknown(String minecraftVersion) {
return minecraftVersion == null || minecraftVersion.isBlank() ? "unknown" : minecraftVersion;
}
/** Boot listing for a validated pack; empty when the gate found nothing. */
public static List<String> compatBootLines(PackValidationResult result, String minecraftVersion, int perKeyCap) {
if (result == null || result.getCompatFindings().isEmpty()) {
@@ -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");
}
@@ -49,6 +49,16 @@ public final class DataFixerV263 extends DataFixerV1217 {
return fixed;
}
/** 26.3 renamed the bed rule's explodes flag to destroy_on_use; the old key is ignored there. */
@Override
public void fixDimension(Dimension dimension, JSONObject json) {
super.fixDimension(dimension, json);
JSONObject bedRule = json.getJSONObject("attributes").optJSONObject("minecraft:gameplay/bed_rule");
if (bedRule != null && bedRule.has("explodes")) {
bedRule.put("destroy_on_use", bedRule.remove("explodes"));
}
}
private static void color(JSONObject object, String key) {
if (object.opt(key) instanceof Number value) {
object.put(key, String.format(Locale.ROOT, "#%06x", value.intValue() & 0xFFFFFF));
@@ -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;
}
@@ -25,6 +25,7 @@ import art.arcane.iris.integration.ExternalDataSVC;
import art.arcane.iris.structure.object.IrisObjectRotation;
import art.arcane.volmlib.nativelib.terrain.BlockStateKey;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import art.arcane.volmlib.nativelib.block.SurvivalAnswer;
import art.arcane.iris.generation.block.IrisCustomData;
import art.arcane.iris.generation.geometry.IrisBlockVector;
import art.arcane.iris.spi.IrisServices;
@@ -429,7 +430,18 @@ public final class BukkitBlockState implements NativeBlockState {
@Override
public boolean canPlaceOnto(NativeBlockState onto) {
return BukkitBlockResolution.canPlaceOnto(data.getMaterial(), ((BlockData) onto.nativeHandle()).getMaterial());
BlockData plant = realBlockOf(data);
BlockData ground = realBlockOf((BlockData) onto.nativeHandle());
SurvivalAnswer serverRule = INMS.isBound() ? INMS.get().canSurviveOn(plant, ground) : SurvivalAnswer.UNANSWERED;
return switch (serverRule) {
case SURVIVES -> true;
case FAILS -> false;
case UNANSWERED -> BukkitBlockResolution.canPlaceOnto(plant.getMaterial(), ground.getMaterial());
};
}
private static BlockData realBlockOf(BlockData data) {
return data instanceof IrisCustomData custom ? custom.getBase() : data;
}
@Override
@@ -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)
@@ -417,7 +418,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 +437,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));
@@ -2,14 +2,20 @@ package art.arcane.iris.generation.biome;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.testsupport.MockPackData;
import art.arcane.iris.generation.noise.IrisExpression;
import art.arcane.iris.generation.noise.IrisExpressionFunction;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.NoiseStyle;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.pack.loading.ResourceLoader;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.noise.CNG;
import art.arcane.volmlib.util.math.RNG;
import org.junit.Test;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
@@ -17,6 +23,9 @@ import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -28,6 +37,71 @@ public final class IrisBiomePaletteLayerGeneratorCacheTest {
private static final int SIGNATURE = 7;
private static final long LAYER_SIGNATURE = 2L;
@Test
public void coordinateOnlyLayerSharesOneGeneratorWithoutChangingItsSamples() {
IrisGeneratorStyle color = new IrisGeneratorStyle().setExpression("color");
PackRuntime runtime = runtimeWithExpressions(Map.of(
"material", new IrisExpression()
.setExpression("if(y >= 25 + 19 * cos((x-y)/43), 0.90, color(abs(sin((x-y)/19 + z/33)), 0, 0))")
.setFunctions(new KList<>(new IrisExpressionFunction().setName("color").setArgs(3).setStyleValue(color))),
"color", new IrisExpression().setExpression("if(x < 0.03, 0.70, if(x < 0.07, 0.40, 0.10))")));
IrisGeneratorStyle style = new IrisGeneratorStyle().setExpression("material");
IrisBiomePaletteLayer layer = new IrisBiomePaletteLayer().zero().setStyle(style);
CNG shared = layer.getLayerGenerator(new RNG(17L), 0, runtime);
List<String> blocks = List.of("end_stone", "blackstone", "obsidian", "air");
for (int depth = 0; depth < 79; depth++) {
RNG caller = new RNG(17L + depth * 41L);
long originalSeed = caller.getSeed() + depth + LAYER_SIGNATURE;
CNG original = style.createNoCache(new RNG(originalSeed), runtime);
assertSame(shared, layer.getLayerGenerator(caller, depth, runtime));
for (int x = -32; x < 32; x += 3) {
double z = 41.5D - x;
assertEquals(original.fit(blocks, x, depth, z), shared.fit(blocks, x, depth, z));
assertEquals(original.noise(x, depth, z), shared.noise(x, depth, z), 0D);
}
}
}
@Test
public void nestedSeededNoiseKeepsDistinctLayerGenerators() {
IrisGeneratorStyle style = new IrisGeneratorStyle().setExpression("seeded");
PackRuntime runtime = runtimeWithExpressions(Map.of(
"seeded", new IrisExpression().setExpression("noise(x, z)")
.setFunctions(new KList<>(new IrisExpressionFunction()
.setName("noise").setStyleValue(NoiseStyle.SIMPLEX.style())))));
IrisBiomePaletteLayer layer = new IrisBiomePaletteLayer().zero().setStyle(style);
CNG first = layer.getLayerGenerator(new RNG(17L), 0, runtime);
CNG second = layer.getLayerGenerator(new RNG(29L), 0, runtime);
assertNotSame(first, second);
assertEquals(style.createNoCache(new RNG(17L + LAYER_SIGNATURE), runtime).noise(-23D, 7D, 11D),
first.noise(-23D, 7D, 11D), 0D);
assertEquals(style.createNoCache(new RNG(29L + LAYER_SIGNATURE), runtime).noise(-23D, 7D, 11D),
second.noise(-23D, 7D, 11D), 0D);
}
@Test
public void recursiveAndMissingExpressionReferencesDoNotQualifyForSharing() {
IrisGeneratorStyle recursive = new IrisGeneratorStyle().setExpression("recursive");
IrisGeneratorStyle missing = new IrisGeneratorStyle().setExpression("missing");
PackRuntime runtime = runtimeWithExpressions(Map.of(
"recursive", new IrisExpression().setExpression("again(x, z)")
.setFunctions(new KList<>(new IrisExpressionFunction()
.setName("again").setStyleValue(recursive)))));
assertFalse(recursive.canShareExpressionGenerator(runtime.data()));
assertFalse(missing.canShareExpressionGenerator(runtime.data()));
}
private static PackRuntime runtimeWithExpressions(Map<String, IrisExpression> contents) {
IrisData data = MockPackData.create();
ResourceLoader<IrisExpression> expressions = mock();
when(data.getExpressionLoader()).thenReturn(expressions);
when(expressions.load(any(String.class))).thenAnswer(call -> contents.get(call.getArgument(0)));
return data.standalonePackRuntime();
}
@Test
public void callerSeedsDoNotShareAFirstWinnerGenerator() {
GeneratorFixture fixture = new GeneratorFixture();
@@ -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,138 @@
package art.arcane.iris.generation.biome;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.NoiseStyle;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.testsupport.MockPackData;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG;
import org.junit.Test;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
public final class PaletteLayerDepthCacheTest {
private static final long[] PARENT_SEEDS = {0L, 17L, -9_223_372_036_854_775_807L, 8_675_309L, 1_234_567_890_123L};
private static final int[] THICKNESSES = {1, 8, 33, 96, 300};
private static final int LAYER_INDEX = 3;
private static final int COLUMNS = 256;
private static final int BENCH_THICKNESS = 96;
private static final int BENCH_CHUNKS = 8;
@Test
public void deepLayerBuildsEachDepthGeneratorOnce() {
CountingStyle style = new CountingStyle(NoiseStyle.SIMPLEX);
IrisBiomePaletteLayer layer = layer(style, BENCH_THICKNESS);
PackRuntime runtime = MockPackData.create().standalonePackRuntime();
walkChunks(layer, runtime, new RNG(17L), BENCH_THICKNESS, 2);
assertEquals(BENCH_THICKNESS, style.builds.get());
}
@Test
public void seededLayerBuildsOneGeneratorForEveryDepthAndParent() {
CountingStyle style = new CountingStyle(NoiseStyle.SIMPLEX);
style.setSeed(4_242L);
IrisBiomePaletteLayer layer = layer(style, BENCH_THICKNESS);
PackRuntime runtime = MockPackData.create().standalonePackRuntime();
for (long parentSeed : PARENT_SEEDS) {
walkChunks(layer, runtime, new RNG(parentSeed), BENCH_THICKNESS, 1);
}
assertEquals(1, style.builds.get());
}
@Test
public void cachedDepthGeneratorsMatchFreshBuilds() {
assertMatchesFreshBuilds(new IrisGeneratorStyle(NoiseStyle.SIMPLEX));
assertMatchesFreshBuilds(new IrisGeneratorStyle(NoiseStyle.CELLULAR).setFracture(
new IrisGeneratorStyle(NoiseStyle.PERLIN).zoomed(3D)).zoomed(0.5D));
assertMatchesFreshBuilds(new IrisGeneratorStyle(NoiseStyle.SIMPLEX).setSeed(77L));
assertMatchesFreshBuilds(new IrisGeneratorStyle(NoiseStyle.PERLIN).setSeed(-3L)
.setFracture(new IrisGeneratorStyle(NoiseStyle.SIMPLEX)));
}
/** Prints builds and thread CPU time for a deep-layer chunk walk; compare runs on the same machine. */
@Test
public void reportDeepLayerWalkCost() {
ThreadMXBean threads = ManagementFactory.getThreadMXBean();
for (int round = 0; round < 3; round++) {
for (boolean fractured : new boolean[]{false, true}) {
CountingStyle style = new CountingStyle(fractured ? NoiseStyle.CELLULAR : NoiseStyle.SIMPLEX);
if (fractured) {
style.setFracture(new IrisGeneratorStyle(NoiseStyle.PERLIN).zoomed(3D));
}
IrisBiomePaletteLayer layer = layer(style, BENCH_THICKNESS);
PackRuntime runtime = MockPackData.create().standalonePackRuntime();
long start = threads.getCurrentThreadCpuTime();
double sink = walkChunks(layer, runtime, new RNG(17L), BENCH_THICKNESS, BENCH_CHUNKS);
long cpu = threads.getCurrentThreadCpuTime() - start;
System.out.printf("palette depth walk %s: thickness=%d chunks=%d builds=%d cpu=%.1fms (%.2fms/chunk) sink=%.3f%n",
fractured ? "cellular+fracture" : "simplex", BENCH_THICKNESS, BENCH_CHUNKS, style.builds.get(),
cpu / 1e6D, cpu / 1e6D / BENCH_CHUNKS, sink);
}
}
}
private static void assertMatchesFreshBuilds(IrisGeneratorStyle style) {
for (int thickness : THICKNESSES) {
IrisBiomePaletteLayer layer = layer(style, thickness);
PackRuntime runtime = MockPackData.create().standalonePackRuntime();
int blockCount = layer.getBlockData(runtime.data()).size();
for (int pass = 0; pass < 2; pass++) {
for (long parentSeed : PARENT_SEEDS) {
RNG parent = new RNG(parentSeed);
for (int depth = 0; depth < thickness; depth++) {
int signature = LAYER_INDEX + depth;
long seed = parentSeed + signature + thickness + thickness + blockCount;
CNG fresh = style.createNoCache(new RNG(seed), runtime);
CNG cached = layer.getLayerGenerator(parent, signature, runtime);
for (int sample = 0; sample < 6; sample++) {
double x = sample * 37.25D - 91D + depth;
double z = 13.5D - sample * 19D - depth;
assertEquals(fresh.noise(x, depth, z), cached.noise(x, depth, z), 0D);
assertEquals(fresh.noise(x, z), cached.noise(x, z), 0D);
}
}
}
}
}
}
private static double walkChunks(IrisBiomePaletteLayer layer, PackRuntime runtime, RNG parent, int thickness, int chunks) {
double sink = 0D;
for (int chunk = 0; chunk < chunks; chunk++) {
for (int column = 0; column < COLUMNS; column++) {
double x = chunk * 16 + (column & 15);
double z = column >> 4;
for (int depth = 0; depth < thickness; depth++) {
sink += layer.getLayerGenerator(parent, LAYER_INDEX + depth, runtime).noise(x + depth, depth, z - depth);
}
}
}
return sink;
}
private static IrisBiomePaletteLayer layer(IrisGeneratorStyle style, int thickness) {
return new IrisBiomePaletteLayer().zero().setStyle(style).setMinHeight(thickness).setMaxHeight(thickness);
}
private static final class CountingStyle extends IrisGeneratorStyle {
private final AtomicInteger builds = new AtomicInteger();
private CountingStyle(NoiseStyle style) {
super(style);
}
@Override
public CNG createNoCache(RNG rng, PackRuntime runtime) {
builds.incrementAndGet();
return super.createNoCache(rng, runtime);
}
}
}
@@ -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,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,108 @@
package art.arcane.iris.pack;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.pack.validation.CompatAction;
import art.arcane.iris.pack.validation.CompatFinding;
import art.arcane.iris.pack.validation.CompatRegistry;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class PackValidatorMissingContentFailureTest {
private static final String PACK = "overworld";
private static final Map<String, Set<String>> REQUIRING_DIMENSION =
Map.of("overworld", Set.of("overworld", "cave/sulfur", "desert", "desert/dunes", "a", "b", "c", "d", "e"));
private static CompatFinding block(CompatAction action, String subjectKey) {
return new CompatFinding(
CompatRegistry.BLOCK, "minecraft:sulfur", action, "Biome", subjectKey, "layers[0].palette[1]");
}
private static CompatFinding entity(CompatAction action, String subjectKey) {
return new CompatFinding(
CompatRegistry.ENTITY, "minecraft:camel", action, "Spawner", subjectKey, "spawns[0]");
}
private static List<String> blockingErrors(Map<String, Set<String>> requiringDimensions, List<CompatFinding> findings) {
List<String> blockingErrors = new ArrayList<>();
PackValidator.applyRequireAllContent(PACK, requiringDimensions, "26.1.2", findings, blockingErrors);
return blockingErrors;
}
@Test
public void requirementIsOffByDefaultAndMissingContentStaysNonBlocking() {
assertFalse(new IrisDimension().isRequireAllContent());
List<String> errors = blockingErrors(Map.of(),
List.of(block(CompatAction.EXCLUDED, "cave/sulfur"), entity(CompatAction.DROPPED, "desert")));
assertTrue(errors.toString(), errors.isEmpty());
}
@Test
public void droppedEntryFailsTheDimension() {
List<String> errors = blockingErrors(REQUIRING_DIMENSION, List.of(entity(CompatAction.DROPPED, "desert")));
assertEquals(List.of("Dimension 'overworld' in pack 'overworld' uses requireAllContent and content is unavailable"
+ " on Minecraft 26.1.2: minecraft:camel (entity): dropped Spawner desert at spawns[0]"), errors);
}
@Test
public void excludedRegistrantFailsTheDimension() {
List<String> errors = blockingErrors(REQUIRING_DIMENSION, List.of(
block(CompatAction.EXCLUDED, "cave/sulfur"), entity(CompatAction.DROPPED, "desert")));
assertEquals(1, errors.size());
assertTrue(errors.getFirst(), errors.getFirst().endsWith(
": minecraft:sulfur (block): excluded Biome cave/sulfur at layers[0].palette[1]"
+ " | minecraft:camel (entity): dropped Spawner desert at spawns[0]"));
}
@Test
public void findingsTheDimensionNeverReachesAreLeftOut() {
List<String> errors = blockingErrors(Map.of("overworld", Set.of("overworld", "desert")), List.of(
block(CompatAction.EXCLUDED, "cave/sulfur"), entity(CompatAction.DROPPED, "desert")));
assertEquals(List.of("Dimension 'overworld' in pack 'overworld' uses requireAllContent and content is unavailable"
+ " on Minecraft 26.1.2: minecraft:camel (entity): dropped Spawner desert at spawns[0]"), errors);
}
@Test
public void dimensionReachingNoRemovedContentIsLoadable() {
assertTrue(blockingErrors(Map.of("overworld", Set.of("overworld")),
List.of(block(CompatAction.EXCLUDED, "cave/sulfur"))).isEmpty());
}
@Test
public void substitutionsAloneKeepTheDimensionLoadable() {
List<String> errors = blockingErrors(REQUIRING_DIMENSION, List.of(block(CompatAction.SUBSTITUTED, "desert/dunes")));
assertTrue(errors.toString(), errors.isEmpty());
}
@Test
public void dimensionWithNothingMissingIsLoadable() {
assertTrue(blockingErrors(REQUIRING_DIMENSION, List.of()).isEmpty());
}
@Test
public void substitutionsAreLeftOutAndSubjectsAreCappedPerKey() {
List<String> errors = blockingErrors(REQUIRING_DIMENSION, List.of(
block(CompatAction.EXCLUDED, "a"),
block(CompatAction.EXCLUDED, "b"),
block(CompatAction.DROPPED, "c"),
block(CompatAction.DROPPED, "d"),
block(CompatAction.SUBSTITUTED, "e")));
assertEquals(1, errors.size());
assertTrue(errors.getFirst(), errors.getFirst().endsWith("; +1 more"));
assertFalse(errors.getFirst(), errors.getFirst().contains("substituted"));
}
}
@@ -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,70 @@
package art.arcane.iris.pack.datapack.v1217;
import art.arcane.iris.pack.datapack.IDataFixer.Dimension;
import art.arcane.iris.pack.datapack.v263.DataFixerV263;
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();
private final DataFixerV1217 fixer263 = new DataFixerV263();
@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 netherBedsExplodeBefore263() {
assertNoSleep(bedRule(fixer, Dimension.NETHER), "explodes", "destroy_on_use");
}
@Test
public void endBedsExplodeBefore263() {
assertNoSleep(bedRule(fixer, Dimension.END), "explodes", "destroy_on_use");
}
@Test
public void netherBedsAreDestroyedOnUseFrom263() {
assertNoSleep(bedRule(fixer263, Dimension.NETHER), "destroy_on_use", "explodes");
}
@Test
public void endBedsAreDestroyedOnUseFrom263() {
assertNoSleep(bedRule(fixer263, Dimension.END), "destroy_on_use", "explodes");
}
@Test
public void overworldBedsSleepWhenDarkFrom263() {
JSONObject rule = bedRule(fixer263, Dimension.OVERWORLD);
assertEquals("when_dark", rule.getString("can_sleep"));
assertFalse(rule.has("explodes"));
assertFalse(rule.has("destroy_on_use"));
}
private JSONObject bedRule(Dimension dimension) {
return bedRule(fixer, dimension);
}
private static JSONObject bedRule(DataFixerV1217 fixer, Dimension dimension) {
return fixer.createDimension(dimension, -64, 384, 384, null)
.getJSONObject("attributes")
.getJSONObject("minecraft:gameplay/bed_rule");
}
private static void assertNoSleep(JSONObject rule, String presentKey, String absentKey) {
assertEquals("never", rule.getString("can_sleep"));
assertEquals("never", rule.getString("can_set_spawn"));
assertTrue(rule.getBoolean(presentKey));
assertFalse(rule.has(absentKey));
}
}
@@ -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 = "89641e077a85bec8a27681f2ce6166150cc37277bc6f58793081b669432782f2";
private static final String EXPECTED_SCHEMA_DIGEST = "1a10c843c6dbe0f60b2dd2cd3a48c04407f30b0ade212cc69a6ba1c4188f25ce";
private static final List<Class<?>> SCHEMA_ROOTS = List.of(
IrisDimension.class,
@@ -0,0 +1,93 @@
package art.arcane.iris.pack.validation;
import art.arcane.iris.pack.PackValidationResult;
import art.arcane.iris.pack.PackValidator;
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.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class MissingContentFailurePackValidationTest {
private static final String PACK = "sulfur-pack";
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Before
public void bindRegistriesWithoutSulfur() {
CompatFixtures.bind(CompatFixtures.registries("minecraft:sulfur"));
}
@After
public void unbind() {
CompatFixtures.unbind();
}
private File packWithSulfurBiome(boolean requireAllContent) throws Exception {
File pack = temporaryFolder.newFolder(PACK);
write(pack, "dimensions/main.json", "{\"requireAllContent\":" + requireAllContent + ",\"regions\":[\"main\"]}");
write(pack, "regions/main.json", "{\"landBiomes\":[\"plain\",\"sulfur\"]}");
write(pack, "biomes/plain.json", "{\"name\":\"Plain\"}");
write(pack, "biomes/sulfur.json",
"{\"name\":\"Sulfur\",\"layers\":[{\"palette\":[{\"block\":\"minecraft:sulfur\"}]}]}");
return pack;
}
private static boolean hasMissingContentError(PackValidationResult result) {
return result.getBlockingErrors().stream().anyMatch(error -> error.contains("uses requireAllContent"));
}
@Test
public void lenientDimensionKeepsGatedContentOutOfTheBlockingErrors() throws Exception {
PackValidationResult result = PackValidator.validate(packWithSulfurBiome(false));
assertFalse(result.getCompatFindings().isEmpty());
assertFalse(result.getBlockingErrors().toString(), hasMissingContentError(result));
}
@Test
public void requiringDimensionFailsValidationNamingTheRemovedContent() throws Exception {
PackValidationResult result = PackValidator.validate(packWithSulfurBiome(true));
assertFalse(result.isLoadable());
assertTrue(result.getBlockingErrors().toString(), result.getBlockingErrors().contains(
"Dimension 'main' in pack '" + PACK + "' uses requireAllContent and content is unavailable on Minecraft"
+ " 26.1.2: minecraft:sulfur (block): excluded biome sulfur at layers[0].palette[0];"
+ " dropped region main at landBiomes[1] sulfur"));
}
@Test
public void requiringDimensionIgnoresContentItNeverReaches() throws Exception {
File pack = temporaryFolder.newFolder(PACK);
write(pack, "dimensions/main.json", "{\"requireAllContent\":true,\"regions\":[\"main\"]}");
write(pack, "regions/main.json", "{\"landBiomes\":[\"plain\"]}");
write(pack, "biomes/plain.json", "{\"name\":\"Plain\"}");
write(pack, "biomes/stray.json",
"{\"name\":\"Stray\",\"layers\":[{\"palette\":[{\"block\":\"minecraft:sulfur\"}]}]}");
PackValidationResult result = PackValidator.validate(pack);
assertFalse(result.getCompatFindings().isEmpty());
assertFalse(result.getBlockingErrors().toString(), hasMissingContentError(result));
}
private static void write(File root, String relative, String content) throws Exception {
Path path = root.toPath().resolve(relative);
Files.createDirectories(path.getParent());
Files.writeString(path, content, StandardCharsets.UTF_8);
}
}
@@ -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) {