From d720e9afabe76a033f8cb7476dfa2e7bf3da97ea Mon Sep 17 00:00:00 2001 From: Piexel <107539181+piexelated@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:39:53 +0100 Subject: [PATCH 01/12] Fix studio world leak (#1276) - Move seeded generator caches into engine-owned PackRuntime - Replace per-thread ThreadLocal memos with engine-owned ThreadSlots - Release engine-keyed structure entries when an engine closes - Keep pack objects as read-only configuration --- .../iris/modded/ModdedEngineEffects.java | 8 +- .../iris/modded/ModdedEntitySpawner.java | 8 +- .../modded/ModdedNativeStructurePolicy.java | 3 +- .../iris/generation/bake/ChunkBakeCache.java | 3 +- .../iris/generation/bake/TerrainProgram.java | 15 +- .../iris/generation/biome/BiomeRuntime.java | 155 ++++++ .../biome/FloatingChildRuntime.java | 57 ++ .../generation/biome/FloatingIslandMemo.java | 67 +++ .../biome/FloatingIslandSample.java | 134 ++--- .../iris/generation/biome/IrisBiome.java | 182 ++----- .../biome/IrisBiomeGeneratorLink.java | 5 +- .../biome/IrisBiomeLayerGenerator.java | 86 +-- .../biome/IrisBiomeLayerHeightCache.java | 68 --- .../iris/generation/biome/IrisBiomeOres.java | 18 +- .../biome/IrisBiomePaletteLayer.java | 151 ++---- .../biome/IrisFloatingChildBiomes.java | 124 ++--- .../generation/biome/PaletteLayerRuntime.java | 57 ++ .../generation/cache/LazyBoundedCache.java | 49 -- .../cave/IrisCaveProfileSampler.java | 14 +- .../generation/decoration/DecoratorCore.java | 72 +-- .../decoration/DecoratorRuntime.java | 57 ++ .../generation/decoration/DepositRuntime.java | 75 +++ .../decoration/FloatingDecorator.java | 8 +- .../decoration/HydrologyVegetation.java | 19 +- .../decoration/IrisCeilingDecorator.java | 12 +- .../generation/decoration/IrisDecorator.java | 123 ++--- .../decoration/IrisDepositGenerator.java | 63 +-- .../generation/decoration/IrisOreBands.java | 44 +- .../decoration/IrisOreGenerator.java | 72 +-- .../decoration/IrisProceduralBlocks.java | 3 +- .../decoration/IrisSeaFloorDecorator.java | 16 +- .../decoration/IrisSeaSurfaceDecorator.java | 16 +- .../decoration/IrisShoreLineDecorator.java | 18 +- .../generation/decoration/IrisSugarCane.java | 3 +- .../decoration/IrisSurfaceDecorator.java | 16 +- .../decoration/OreBandsRuntime.java | 68 +++ .../formation/FormationBlockResolver.java | 3 +- .../decoration/tree/TreeBlockResolver.java | 5 +- .../hydrology/engine/HydrologyRuntime.java | 5 +- .../engine/IrisHydrologyTerrainSource.java | 2 +- .../mantle/FloatingIslandSampleResolver.java | 9 +- .../generation/mantle/IrisCaveCarver3D.java | 20 +- .../mantle/IrisStructureComponent.java | 9 +- .../mantle/MantleCarvingComponent.java | 3 +- .../mantle/MantleFloatingObjectComponent.java | 9 +- .../mantle/MantleObjectComponent.java | 9 +- .../iris/generation/mantle/MantleWriter.java | 7 +- .../generation/noise/ExpressionNoise.java | 4 +- .../generation/noise/ExpressionRuntime.java | 258 +++++++++ .../generation/noise/GeneratorProgram.java | 16 +- .../generation/noise/GeneratorRuntime.java | 45 ++ .../iris/generation/noise/IrisExpression.java | 143 ++--- .../noise/IrisExpressionFunction.java | 110 +--- .../generation/noise/IrisExpressionLoad.java | 131 ----- .../iris/generation/noise/IrisGenerator.java | 168 ++---- .../generation/noise/IrisGeneratorStyle.java | 112 +--- .../generation/noise/IrisNoiseGenerator.java | 116 +--- .../noise/IrisShapedGeneratorStyle.java | 14 +- .../generation/noise/IrisStyledRange.java | 10 +- .../runtime/DimensionStackContext.java | 2 +- .../runtime/DimensionTerrainContext.java | 46 +- .../iris/generation/runtime/Engine.java | 3 + .../generation/runtime/EngineHotloader.java | 2 + .../runtime/EngineRuntimeBuilder.java | 12 +- .../runtime/EngineShutdownSequence.java | 15 + .../generation/runtime/EngineThreadState.java | 46 +- .../runtime/GenerationCacheWarmer.java | 31 +- .../generation/runtime/GenerationRuntime.java | 4 + .../iris/generation/runtime/IrisComplex.java | 39 +- .../iris/generation/runtime/IrisEngine.java | 11 + .../iris/generation/runtime/PackRuntime.java | 258 +++++++++ .../iris/generation/runtime/RuntimeTable.java | 68 +++ .../iris/generation/runtime/SeedTable.java | 99 ++++ .../iris/generation/runtime/ThreadSlots.java | 150 ++++++ .../generation/stage/IrisBiomeActuator.java | 3 +- .../generation/stage/IrisCarveModifier.java | 28 +- .../generation/stage/IrisCarveScratch.java | 8 + .../stage/IrisDecorantActuator.java | 4 +- .../generation/stage/IrisDepositModifier.java | 18 +- .../stage/IrisDimensionStackActuator.java | 10 +- .../stage/IrisFloatingChildBiomeModifier.java | 31 +- .../generation/stage/IrisPostModifier.java | 4 +- .../stage/IrisTerrainNormalActuator.java | 67 ++- .../generation/subterrain/SubterrainPlan.java | 3 +- .../SubterrainSurfaceMaterials.java | 13 +- .../terrain/ContinentGenerator.java | 10 +- .../generation/terrain/IrisDimension.java | 44 +- .../terrain/IrisDimensionCarvingEntry.java | 12 +- .../terrain/IrisDimensionCarvingResolver.java | 28 +- .../terrain/IrisMaterialPalette.java | 84 +-- .../iris/generation/terrain/IrisRegion.java | 17 +- .../generation/terrain/RegionSelection.java | 2 +- .../generation/terrain/Terrain3DRuntime.java | 9 +- .../compile/biome/SelectorCompiler.java | 4 +- .../compile/decoration/DecoratorCoverage.java | 2 +- .../compile/noise/NoiseStyleCompiler.java | 10 +- .../export/compile/object/VariantPlanner.java | 2 +- .../compile/subterrain/SubterrainBaker.java | 11 +- .../compile/terrain/VolumetricCompiler.java | 2 +- .../arcane/iris/pack/loading/IrisData.java | 41 ++ .../nms/BukkitStructureStagePolicy.java | 3 +- .../generation/BukkitChunkGenerator.java | 8 + .../graph/StructureGraphCatalog.java | 17 +- .../NativeStructureOwnershipStore.java | 44 +- .../nativegen/NativeStructureVolumeIndex.java | 6 +- .../object/HeightmapObjectPlacer.java | 10 +- .../structure/object/IrisObjectPlacement.java | 61 +-- .../structure/object/IrisObjectReplace.java | 6 +- .../structure/object/ObjectBlockPass.java | 5 +- .../structure/object/PlacementContext.java | 3 + ...cementModuleNativeStructureProtection.java | 3 +- .../object/PlacementModulePaint.java | 3 +- .../object/PlacementModulePreparation.java | 2 +- .../object/PlacementModuleStilt.java | 7 +- .../placement/IrisStructureLocator.java | 12 +- .../placement/IrisStructureStrata.java | 42 +- .../placement/StructurePlacementScope.java | 42 +- .../placement/StructureReachability.java | 6 +- .../studio/map/BiomePalettePlacement.java | 49 +- .../iris/studio/map/BiomeTintField.java | 9 +- .../iris/studio/map/NoiseExplorerGUI.java | 7 +- .../iris/studio/map/PaletteLayerPreview.java | 2 +- .../arcane/iris/world/entity/IrisEffect.java | 17 +- .../arcane/iris/world/entity/IrisEntity.java | 3 +- .../history/GenerationBoundaryStore.java | 3 +- .../GenerationHistoryRuntimeRouter.java | 9 +- .../world/history/TransitionBandIndex.java | 3 +- .../history/TransitionBoundarySampler.java | 5 +- .../history/TransitionDisplacementField.java | 3 +- .../FloatingIslandBoundarySamplerTest.java | 39 +- .../biome/FloatingIslandLockedLayersTest.java | 20 +- .../biome/FloatingIslandMemoContextTest.java | 43 +- .../biome/IrisBiomeCeilingLayerTest.java | 21 +- .../biome/IrisBiomeChildrenGeneratorTest.java | 5 +- .../biome/IrisBiomeFieldSeedCohesionTest.java | 25 +- .../IrisBiomeGeneratorSeedIsolationTest.java | 65 ++- .../biome/IrisBiomeLayerHeightCacheTest.java | 88 ++- .../biome/IrisBiomeLayerSlopeSourceTest.java | 24 +- .../biome/IrisBiomeLockedLayerTest.java | 40 +- ...isBiomePaletteLayerGeneratorCacheTest.java | 20 +- .../biome/IrisSurfaceLayerFallbackTest.java | 15 +- .../cache/LazyBoundedCacheTest.java | 139 ----- .../cave/IrisCaveProfileSamplerTest.java | 9 +- .../DecorationFailureContainmentTest.java | 6 +- .../decoration/DecoratorCoreTest.java | 221 ++++---- .../DecoratorStackSamplingTest.java | 14 +- .../decoration/HydrologyVegetationTest.java | 7 +- .../IrisDecoratorCaveContextTest.java | 11 +- .../decoration/IrisDecoratorHeightTest.java | 6 +- .../IrisDecoratorPaletteSelectionTest.java | 22 +- .../IrisDecoratorSeedCohesionTest.java | 3 + .../IrisDecoratorVarianceGeneratorTest.java | 5 +- .../decoration/IrisDepositTuningTest.java | 65 ++- .../decoration/IrisOreBandsTest.java | 26 +- .../decoration/IrisOreGeneratorTest.java | 19 +- .../decoration/IrisOreSeedCohesionTest.java | 5 +- .../IrisSeaDecoratorBoundsTest.java | 7 +- .../IrisShoreLineDecoratorTest.java | 21 +- .../IrisSugarCanePlacementTest.java | 9 +- .../formation/FormationBlockResolverTest.java | 3 +- .../IrisCaveCarver3DCellKernelTest.java | 2 + .../mantle/IrisCaveCarver3DLatticeTest.java | 2 + .../IrisCaveCarver3DNearParityTest.java | 11 +- .../IrisStructureFoundationWriteTest.java | 14 +- .../mantle/MantleCarvedTerrainTest.java | 2 + ...antleFloatingObjectComponentEmptyTest.java | 3 +- .../generation/mantle/PlacementReachTest.java | 5 +- .../noise/GeneratorProgramParityTest.java | 15 +- .../noise/IrisExpressionCoordinateTest.java | 25 +- .../IrisExpressionLoadEngineCacheTest.java | 58 +- .../noise/IrisExpressionScratchTest.java | 103 ++-- .../noise/IrisExpressionSeedCohesionTest.java | 52 +- .../noise/IrisGeneratorBatchTest.java | 27 +- .../IrisGeneratorStyleCacheIsolationTest.java | 34 +- .../noise/IrisGeneratorStyleOverrideTest.java | 15 +- .../noise/IrisGeneratorSurfaceDetailTest.java | 113 ++-- .../noise/IrisNoiseGeneratorCacheTest.java | 67 +-- .../IrisNoiseGeneratorFractureMirrorTest.java | 7 +- .../noise/IrisNoiseGeneratorFractureTest.java | 79 +-- .../noise/IrisNoiseGeneratorRemapTest.java | 3 +- .../noise/NoiseSeedCohesionTest.java | 7 +- .../noise/NoiseStyleContractTest.java | 35 +- .../noise/PatternNoiseStyleTest.java | 3 +- .../DimensionTerrain3DCompositionTest.java | 3 +- .../runtime/EngineBiomeColumnTest.java | 1 + .../runtime/EngineShutdownDrainTest.java | 25 +- .../HydrologyVegetationSourceTest.java | 5 +- .../IrisCarveWallPaletteScopeTest.java | 14 +- .../runtime/IrisComplexChunkCornersTest.java | 6 +- ...risComplexConstantGeneratorBoundsTest.java | 14 +- .../IrisComplexGeneratorOrderingTest.java | 6 +- .../IrisComplexGridBoundsCacheTest.java | 6 +- .../runtime/IrisComplexSelfSelectionTest.java | 2 +- .../runtime/IrisComplexTransitionTest.java | 7 +- .../IrisEngineGenerationCacheWarmTest.java | 5 +- .../IrisEngineGenerationRuntimeScopeTest.java | 8 +- .../runtime/IrisEngineStreamTypeTest.java | 2 +- .../generation/runtime/RuntimeTableTest.java | 59 ++ .../generation/runtime/ThreadSlotsTest.java | 128 +++++ .../stage/IrisCarveModifierLayerMemoTest.java | 12 +- .../IrisCarveModifierSubterrainMaskTest.java | 4 +- .../stage/IrisDepositModifierContextTest.java | 10 +- .../IrisDepositModifierOrderingTest.java | 2 +- .../stage/IrisDepositModifierParityTest.java | 7 +- .../IrisDepositModifierPoolGuardTest.java | 2 +- .../IrisTerrainNormalActuatorBankCutTest.java | 9 +- ...TerrainNormalActuatorColumnParityTest.java | 21 +- ...risTerrainNormalActuatorHydrologyTest.java | 17 +- .../SubterrainSurfaceMaterialsTest.java | 13 +- .../terrain/ContinentGeneratorTest.java | 5 +- .../IrisDimensionCarvingEntryTest.java | 5 +- ...risDimensionCarvingResolverParityTest.java | 54 +- ...IrisMaterialPaletteGeneratorCacheTest.java | 20 +- .../terrain/TerrainFieldSeedCohesionTest.java | 27 +- .../compile/biome/IrisSelectionReference.java | 13 +- .../decoration/DecorationStageTest.java | 3 +- .../compile/noise/NoiseStyleCompilerTest.java | 5 +- .../noise/SmoothNoiseFidelityTest.java | 7 +- .../terrain/VolumetricCompilerTest.java | 5 +- .../loading/IrisDataCloseLoadedUnderTest.java | 48 ++ .../value/IrisMathNoiseHotPathParityTest.java | 7 +- .../iris/purity/PackRuntimeStateGateTest.java | 507 ++++++++++++++++++ .../NativeStructureOwnershipStoreTest.java | 20 + .../object/HeightmapObjectPlacerTest.java | 5 +- ...bjectPlacementLifecycleRegressionTest.java | 3 +- ...isObjectPlacementRunnerRegressionTest.java | 20 +- ...isObjectPlacementSurfaceWarpCacheTest.java | 27 +- .../object/ObjectPlacementGoldenTest.java | 5 +- .../IrisStructureLocatorContractTest.java | 19 +- .../placement/IrisStructureStrataTest.java | 36 +- .../StructurePlacementScopeTest.java | 26 + .../iris/testsupport/GeneratorSampling.java | 6 +- .../arcane/iris/testsupport/MockPackData.java | 47 ++ .../testsupport/RunningEnginePackData.java | 5 +- .../iris/probe/EngineReleaseProbeTest.java | 142 +++++ .../engine-release/biomes/terrain.json | 23 + .../engine-release/dimensions/release.json | 11 + .../engine-release/generators/terrain.json | 5 + .../engine-release/regions/terrain.json | 6 + 239 files changed, 4755 insertions(+), 3170 deletions(-) create mode 100644 core/src/main/java/art/arcane/iris/generation/biome/BiomeRuntime.java create mode 100644 core/src/main/java/art/arcane/iris/generation/biome/FloatingChildRuntime.java create mode 100644 core/src/main/java/art/arcane/iris/generation/biome/FloatingIslandMemo.java delete mode 100644 core/src/main/java/art/arcane/iris/generation/biome/IrisBiomeLayerHeightCache.java create mode 100644 core/src/main/java/art/arcane/iris/generation/biome/PaletteLayerRuntime.java delete mode 100644 core/src/main/java/art/arcane/iris/generation/cache/LazyBoundedCache.java create mode 100644 core/src/main/java/art/arcane/iris/generation/decoration/DecoratorRuntime.java create mode 100644 core/src/main/java/art/arcane/iris/generation/decoration/DepositRuntime.java create mode 100644 core/src/main/java/art/arcane/iris/generation/decoration/OreBandsRuntime.java create mode 100644 core/src/main/java/art/arcane/iris/generation/noise/ExpressionRuntime.java create mode 100644 core/src/main/java/art/arcane/iris/generation/noise/GeneratorRuntime.java create mode 100644 core/src/main/java/art/arcane/iris/generation/runtime/PackRuntime.java create mode 100644 core/src/main/java/art/arcane/iris/generation/runtime/RuntimeTable.java create mode 100644 core/src/main/java/art/arcane/iris/generation/runtime/SeedTable.java create mode 100644 core/src/main/java/art/arcane/iris/generation/runtime/ThreadSlots.java delete mode 100644 core/src/test/java/art/arcane/iris/generation/cache/LazyBoundedCacheTest.java create mode 100644 core/src/test/java/art/arcane/iris/generation/runtime/RuntimeTableTest.java create mode 100644 core/src/test/java/art/arcane/iris/generation/runtime/ThreadSlotsTest.java create mode 100644 core/src/test/java/art/arcane/iris/pack/loading/IrisDataCloseLoadedUnderTest.java create mode 100644 core/src/test/java/art/arcane/iris/purity/PackRuntimeStateGateTest.java create mode 100644 core/src/test/java/art/arcane/iris/testsupport/MockPackData.java create mode 100644 probe/src/test/java/art/arcane/iris/probe/EngineReleaseProbeTest.java create mode 100644 probe/src/test/resources/engine-release/biomes/terrain.json create mode 100644 probe/src/test/resources/engine-release/dimensions/release.json create mode 100644 probe/src/test/resources/engine-release/generators/terrain.json create mode 100644 probe/src/test/resources/engine-release/regions/terrain.json diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEngineEffects.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEngineEffects.java index 2b3a58977..d9bdb441c 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEngineEffects.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEngineEffects.java @@ -19,6 +19,7 @@ package art.arcane.iris.modded; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.configuration.IrisSettings; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.BiomeEnvironment; @@ -223,17 +224,18 @@ public final class ModdedEngineEffects extends EngineAssignedComponent implement } private void applyEffects(NativeWorld level, NativeProtocolPlayer player, Iterable effects) { + PackRuntime runtime = PackRuntime.of(getEngine()); for (IrisEffect effect : effects) { try { - applyEffect(level, player, effect); + applyEffect(level, player, effect, runtime); } catch (Throwable error) { IrisLogging.reportError(error); } } } - private void applyEffect(NativeWorld level, NativeProtocolPlayer player, IrisEffect effect) { - if (!effect.shouldApplyNow()) { + private void applyEffect(NativeWorld level, NativeProtocolPlayer player, IrisEffect effect, PackRuntime runtime) { + if (!effect.shouldApplyNow(runtime)) { return; } diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEntitySpawner.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEntitySpawner.java index 90d9a0483..a41c4fe8b 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEntitySpawner.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEntitySpawner.java @@ -18,6 +18,7 @@ package art.arcane.iris.modded; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.configuration.IrisSettings; import art.arcane.iris.generation.decoration.IrisSurface; import art.arcane.iris.generation.runtime.Engine; @@ -127,7 +128,7 @@ public final class ModdedEntitySpawner { entity.configureAnimal(irisEntity); - applySpawnEffect(irisEntity.getSpawnEffect(), entity, level); + applySpawnEffect(irisEntity.getSpawnEffect(), entity, level, PackRuntime.of(engine)); ModdedEntityCommandRunner.run(irisEntity.getRawCommands(), level.world(), blockX, blockY, blockZ); if (riseEffectActive && entity.living()) { startRiseEffect(engine, level, entity); @@ -200,8 +201,9 @@ public final class ModdedEntitySpawner { return level.chunksSafe(chunkX, chunkZ); } - private static void applySpawnEffect(IrisEffect effect, NativeSpawnedEntity entity, NativeEntityRuntime level) { - if (effect == null || !effect.shouldApplyNow()) { + private static void applySpawnEffect(IrisEffect effect, NativeSpawnedEntity entity, NativeEntityRuntime level, + PackRuntime runtime) { + if (effect == null || !effect.shouldApplyNow(runtime)) { return; } diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedNativeStructurePolicy.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedNativeStructurePolicy.java index 6017435ad..ec5d903e9 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedNativeStructurePolicy.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedNativeStructurePolicy.java @@ -1,5 +1,6 @@ package art.arcane.iris.modded; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.volmlib.nativelib.terrain.structure.StructureStagePolicy; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.mantle.DeferredPlacementRecords; @@ -151,7 +152,7 @@ final class ModdedNativeStructurePolicy implements NativeModdedStructureStage.Po @Override public NativeBlockState paletteBlock(StructurePalette source, RNG rng, int x, int y, int z) { - return ((IrisMaterialPalette) source).get(rng, x, y, z, generator.engine().getData()); + return ((IrisMaterialPalette) source).get(rng, x, y, z, PackRuntime.of(generator.engine())); } @Override diff --git a/core/src/main/java/art/arcane/iris/generation/bake/ChunkBakeCache.java b/core/src/main/java/art/arcane/iris/generation/bake/ChunkBakeCache.java index cb1c13dab..f01789bba 100644 --- a/core/src/main/java/art/arcane/iris/generation/bake/ChunkBakeCache.java +++ b/core/src/main/java/art/arcane/iris/generation/bake/ChunkBakeCache.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.bake; +import art.arcane.iris.generation.runtime.ThreadSlots; import art.arcane.iris.generation.cache.ConcurrentClockCache; import art.arcane.iris.generation.stream.ProvisionalSampling; @@ -16,7 +17,7 @@ public final class ChunkBakeCache { private final PlaneSource source; private final ConcurrentClockCache entries; - private final ThreadLocal recent = ThreadLocal.withInitial(Recent::new); + private final ThreadSlots recent = new ThreadSlots<>(Recent::new); private volatile int generation; public ChunkBakeCache(PlaneSource source, int capacityChunks) { diff --git a/core/src/main/java/art/arcane/iris/generation/bake/TerrainProgram.java b/core/src/main/java/art/arcane/iris/generation/bake/TerrainProgram.java index 938922c3d..a7ef5797f 100644 --- a/core/src/main/java/art/arcane/iris/generation/bake/TerrainProgram.java +++ b/core/src/main/java/art/arcane/iris/generation/bake/TerrainProgram.java @@ -3,6 +3,7 @@ package art.arcane.iris.generation.bake; import art.arcane.iris.generation.noise.GeneratorProgram; import art.arcane.iris.generation.noise.IrisGenerator; import art.arcane.iris.generation.noise.TerrainBatchScratch; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.volmlib.util.math.M; import java.util.Arrays; @@ -12,26 +13,28 @@ public final class TerrainProgram { private static final int CONSTANT = 1; private static final int ACTIVE = 2; + private final PackRuntime runtime; private final IrisGenerator[][] generators; private final GeneratorProgram[][] programs; private final long heightSeed; - private TerrainProgram(IrisGenerator[][] generators, GeneratorProgram[][] programs, long heightSeed) { + private TerrainProgram(PackRuntime runtime, IrisGenerator[][] generators, GeneratorProgram[][] programs, long heightSeed) { + this.runtime = runtime; this.generators = generators; this.programs = programs; this.heightSeed = heightSeed; } - public static TerrainProgram compile(IrisGenerator[][] generators, long heightSeed) { + public static TerrainProgram compile(PackRuntime runtime, IrisGenerator[][] generators, long heightSeed) { GeneratorProgram[][] programs = new GeneratorProgram[generators.length][]; for (int group = 0; group < generators.length; group++) { programs[group] = new GeneratorProgram[generators[group].length]; for (int index = 0; index < generators[group].length; index++) { IrisGenerator generator = generators[group][index]; - programs[group][index] = generator.supportsBatch() ? generator.compileProgram(heightSeed) : null; + programs[group][index] = generator.supportsBatch() ? generator.compileProgram(runtime, heightSeed) : null; } } - return new TerrainProgram(generators, programs, heightSeed); + return new TerrainProgram(runtime, generators, programs, heightSeed); } public long heightSeed() { @@ -58,7 +61,7 @@ public final class TerrainProgram { GeneratorProgram[] compiled = programs[group]; for (int member = 0; member < members.length; member++) { GeneratorProgram program = compiled[member]; - double noise = program != null ? program.height(scratch, x, z) : members[member].getHeight(x, z, heightSeed); + double noise = program != null ? program.height(scratch, x, z) : members[member].getHeight(runtime, x, z, heightSeed); if (!Double.isFinite(noise)) { throw new IllegalStateException("Terrain generator noise was not finite at " + x + "," + z + " (generator=" + members[member].getLoadKey() + ", noise=" + noise @@ -148,7 +151,7 @@ public final class TerrainProgram { program.heights(scratch, activeX, activeZ, activeCount, noise); } else { for (int index = 0; index < activeCount; index++) { - noise[index] = members[member].getHeight(activeX[index], activeZ[index], heightSeed); + noise[index] = members[member].getHeight(runtime, activeX[index], activeZ[index], heightSeed); } } for (int index = 0; index < activeCount; index++) { diff --git a/core/src/main/java/art/arcane/iris/generation/biome/BiomeRuntime.java b/core/src/main/java/art/arcane/iris/generation/biome/BiomeRuntime.java new file mode 100644 index 000000000..a02fcc65c --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/biome/BiomeRuntime.java @@ -0,0 +1,155 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.generation.biome; + +import art.arcane.iris.generation.runtime.PackRuntime; +import art.arcane.iris.generation.runtime.SeedTable; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.noise.CNG; + +import art.arcane.iris.generation.decoration.DecoratorRuntime; +import art.arcane.iris.generation.decoration.IrisDecorationPart; +import art.arcane.iris.generation.decoration.IrisDecorator; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicReferenceArray; +import java.util.function.Supplier; + +/** + * What one engine derives from an {@link IrisBiome}: its scatter generators, the children generators per shrink + * scale, the height generators of its layer palettes and the runtimes of those palettes, linked by layer index so + * painting a column reads them without looking each layer up. + */ +public final class BiomeRuntime { + private static final int BIOME_SEED_CAPACITY = 8; + private static final int CHILD_SEED_CAPACITY = 8; + private static final int LAYER_HEIGHT_SEED_CAPACITY = 32; + private static final int SURFACE_LAYER_SEED_OFFSET = 7235; + private static final int SEA_LAYER_SEED_OFFSET = 7735; + private static final int CEILING_LAYER_SEED_OFFSET = 7235; + + private final IrisBiome biome; + private final PackRuntime runtime; + private final SeedTable biomeGenerators; + private final ConcurrentHashMap> childGeneratorsByScale = new ConcurrentHashMap<>(); + private final SeedTable> layerHeights; + private final SeedTable> seaLayerHeights; + private final SeedTable> ceilingLayerHeights; + private final LinkedLayers surfaceLayers; + private final LinkedLayers seaLayers; + private final LinkedLayers ceilingLayers; + private final AtomicReferenceArray decoratorBuckets = + new AtomicReferenceArray<>(IrisDecorationPart.values().length); + + public BiomeRuntime(IrisBiome biome, PackRuntime runtime) { + this.biome = biome; + this.runtime = runtime; + this.biomeGenerators = new SeedTable<>(BIOME_SEED_CAPACITY, seed -> biome.createBiomeGenerator(seed, runtime)); + this.layerHeights = new SeedTable<>(LAYER_HEIGHT_SEED_CAPACITY, seed -> + IrisBiomeLayerGenerator.createHeightGenerators(biome.getLayers(), SURFACE_LAYER_SEED_OFFSET, seed, runtime)); + this.seaLayerHeights = new SeedTable<>(LAYER_HEIGHT_SEED_CAPACITY, seed -> + IrisBiomeLayerGenerator.createHeightGenerators(biome.getSeaLayers(), SEA_LAYER_SEED_OFFSET, seed, runtime)); + this.ceilingLayerHeights = new SeedTable<>(LAYER_HEIGHT_SEED_CAPACITY, seed -> + IrisBiomeLayerGenerator.createHeightGenerators(biome.getCaveCeilingLayers(), CEILING_LAYER_SEED_OFFSET, seed, runtime)); + this.surfaceLayers = new LinkedLayers(biome::getLayers); + this.seaLayers = new LinkedLayers(biome::getSeaLayers); + this.ceilingLayers = new LinkedLayers(biome::getCaveCeilingLayers); + } + + public CNG biomeGenerator(long seed) { + return biomeGenerators.get(seed); + } + + public CNG childrenGenerator(long seed, double scale) { + return childGeneratorsByScale.computeIfAbsent(Double.doubleToLongBits(scale), ignored -> + new SeedTable<>(CHILD_SEED_CAPACITY, childSeed -> biome.createChildrenGenerator(childSeed, scale, runtime))) + .get(seed); + } + + public KList layerHeights(long seed) { + return layerHeights.get(seed); + } + + public KList seaLayerHeights(long seed) { + return seaLayerHeights.get(seed); + } + + public KList ceilingLayerHeights(long seed) { + return ceilingLayerHeights.get(seed); + } + + /** The runtime of the surface layer at this index of {@link IrisBiome#getLayers()}. */ + public PaletteLayerRuntime surfaceLayer(int index) { + return surfaceLayers.get(index); + } + + /** The runtime of the sea layer at this index of {@link IrisBiome#getSeaLayers()}. */ + public PaletteLayerRuntime seaLayer(int index) { + return seaLayers.get(index); + } + + /** The runtime of the cave ceiling layer at this index of {@link IrisBiome#getCaveCeilingLayers()}. */ + public PaletteLayerRuntime ceilingLayer(int index) { + return ceilingLayers.get(index); + } + + /** The runtimes of this part's {@link IrisBiome#getDecoratorBucket} decorators, in bucket order. */ + public DecoratorRuntime[] decorators(IrisDecorationPart part) { + IrisDecorator[] bucket = biome.getDecoratorBucket(part); + LinkedDecorators linked = decoratorBuckets.getAcquire(part.ordinal()); + if (linked != null && linked.bucket() == bucket) { + return linked.runtimes(); + } + DecoratorRuntime[] runtimes = new DecoratorRuntime[bucket.length]; + for (int index = 0; index < bucket.length; index++) { + runtimes[index] = runtime.decorator(bucket[index]); + } + decoratorBuckets.setRelease(part.ordinal(), new LinkedDecorators(bucket, runtimes)); + return runtimes; + } + + private record LinkedDecorators(IrisDecorator[] bucket, DecoratorRuntime[] runtimes) { + } + + private final class LinkedLayers { + private final Supplier> layers; + private volatile PaletteLayerRuntime[] linked; + + private LinkedLayers(Supplier> layers) { + this.layers = layers; + } + + private PaletteLayerRuntime get(int index) { + PaletteLayerRuntime[] current = linked; + if (current == null) { + current = link(layers.get()); + linked = current; + } + return current[index]; + } + + private PaletteLayerRuntime[] link(KList source) { + PaletteLayerRuntime[] result = new PaletteLayerRuntime[source.size()]; + for (int index = 0; index < result.length; index++) { + result[index] = runtime.paletteLayer(source.get(index)); + } + return result; + } + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/biome/FloatingChildRuntime.java b/core/src/main/java/art/arcane/iris/generation/biome/FloatingChildRuntime.java new file mode 100644 index 000000000..16d20520f --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/biome/FloatingChildRuntime.java @@ -0,0 +1,57 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.generation.biome; + +import art.arcane.iris.generation.cave.IrisCaveProfileSampler; +import art.arcane.iris.generation.runtime.PackRuntime; +import art.arcane.iris.generation.runtime.SeedTable; + +import java.util.Optional; + +/** + * What one engine derives from an {@link IrisFloatingChildBiomes} entry: its edge taper profile per base seed and the + * cave profile sampler of the biome it carves with. + */ +public final class FloatingChildRuntime { + private static final int EDGE_PROFILE_SEED_CAPACITY = 8; + + private final IrisFloatingChildBiomes entry; + private final PackRuntime runtime; + private final SeedTable edgeProfiles; + private volatile Optional carvingProfileSampler; + + public FloatingChildRuntime(IrisFloatingChildBiomes entry, PackRuntime runtime) { + this.entry = entry; + this.runtime = runtime; + this.edgeProfiles = new SeedTable<>(EDGE_PROFILE_SEED_CAPACITY, seed -> entry.createEdgeTaperProfile(seed, runtime)); + } + + public FloatingIslandEdgeProfile edgeTaperProfile(long baseSeed) { + return edgeProfiles.get(baseSeed); + } + + public IrisCaveProfileSampler carvingProfileSampler() { + Optional resolved = carvingProfileSampler; + if (resolved == null) { + resolved = Optional.ofNullable(entry.createCarvingProfileSampler(runtime)); + carvingProfileSampler = resolved; + } + return resolved.orElse(null); + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/biome/FloatingIslandMemo.java b/core/src/main/java/art/arcane/iris/generation/biome/FloatingIslandMemo.java new file mode 100644 index 000000000..2754fbefa --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/biome/FloatingIslandMemo.java @@ -0,0 +1,67 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.generation.biome; + +import java.util.HashMap; + +/** + * One worker's floating island samples for the chunk it is generating. A runtime scope keeps one per worker thread, + * so the memo never outlives the engine that produced its samples. + */ +public final class FloatingIslandMemo { + private static final int CHUNK_COLUMN_COUNT = 256; + + private final HashMap samples = new HashMap<>(CHUNK_COLUMN_COUNT); + private MemoContext context; + + public void clear() { + samples.clear(); + context = null; + } + + /** The memoized sample for this column and parent, which may itself be null; null when not sampled yet. */ + MemoizedSample find(IrisBiome parent, long column) { + MemoizedSample cached = samples.get(column); + return cached != null && cached.parent == parent ? cached : null; + } + + void remember(IrisBiome parent, long column, FloatingIslandSample sample) { + samples.put(column, new MemoizedSample(parent, sample)); + } + + void enterChunk(int chunkX, int chunkZ, int height, long seed, FloatingIslandBoundarySampler boundarySampler) { + if (context != null && context.matches(chunkX, chunkZ, height, seed, boundarySampler)) { + return; + } + samples.clear(); + context = new MemoContext(chunkX, chunkZ, height, seed, boundarySampler); + } + + private record MemoContext(int chunkX, int chunkZ, int height, long seed, + FloatingIslandBoundarySampler boundarySampler) { + private boolean matches(int chunkX, int chunkZ, int height, long seed, + FloatingIslandBoundarySampler boundarySampler) { + return this.chunkX == chunkX && this.chunkZ == chunkZ && this.height == height && this.seed == seed + && this.boundarySampler == boundarySampler; + } + } + + record MemoizedSample(IrisBiome parent, FloatingIslandSample sample) { + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/biome/FloatingIslandSample.java b/core/src/main/java/art/arcane/iris/generation/biome/FloatingIslandSample.java index d5c86bd85..7fe401092 100644 --- a/core/src/main/java/art/arcane/iris/generation/biome/FloatingIslandSample.java +++ b/core/src/main/java/art/arcane/iris/generation/biome/FloatingIslandSample.java @@ -20,16 +20,12 @@ package art.arcane.iris.generation.biome; import art.arcane.iris.generation.cave.IrisCaveProfileSampler; -import art.arcane.iris.pack.loading.IrisData; -import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.spi.IrisLogging; import art.arcane.volmlib.util.noise.CNG; import art.arcane.volmlib.util.collection.KList; -import it.unimi.dsi.fastutil.longs.Long2DoubleOpenHashMap; import java.util.Arrays; -import java.util.HashMap; -import java.util.IdentityHashMap; import java.util.concurrent.atomic.AtomicBoolean; public final class FloatingIslandSample { @@ -51,8 +47,6 @@ public final class FloatingIslandSample { private static final double CARVE_MAX_VERTICAL_RUN_FRACTION = 0.18D; private static final ThreadLocal LAST_REJECT = ThreadLocal.withInitial(() -> new int[1]); private static final ThreadLocal LAST_DENSITY = ThreadLocal.withInitial(() -> new double[2]); - private static final ThreadLocal CHUNK_MEMO = ThreadLocal.withInitial(ChunkMemo::new); - private static final ThreadLocal> FOOTPRINT_MEMO = ThreadLocal.withInitial(IdentityHashMap::new); private static final AtomicBoolean NULL_CNG_WARNED = new AtomicBoolean(false); public static int getLastReject() { @@ -67,33 +61,20 @@ public final class FloatingIslandSample { return LAST_DENSITY.get()[1]; } - public static void clearThreadCaches() { - CHUNK_MEMO.remove(); - FOOTPRINT_MEMO.remove(); - LAST_REJECT.remove(); - LAST_DENSITY.remove(); + public static void clearChunkMemo(PackRuntime runtime) { + runtime.floatingIslandMemo().clear(); } - public static void clearChunkMemo() { - CHUNK_MEMO.get().samples.clear(); - FOOTPRINT_MEMO.get().clear(); - } - - public static FloatingIslandSample sampleMemoized(IrisBiome parent, int wx, int wz, int chunkHeight, long baseSeed, IrisData data, Engine engine, FloatingIslandBoundarySampler boundarySampler) { - long key = (((long) wx) << 32) ^ (wz & 0xFFFFFFFFL); - ChunkMemo memo = CHUNK_MEMO.get(); - if (memo.context == null || !memo.context.matches(wx >> 4, wz >> 4, chunkHeight, baseSeed, - data, engine, boundarySampler)) { - memo.samples.clear(); - FOOTPRINT_MEMO.get().clear(); - memo.context = new MemoContext(wx >> 4, wz >> 4, chunkHeight, baseSeed, data, engine, boundarySampler); + public static FloatingIslandSample sampleMemoized(IrisBiome parent, int wx, int wz, int chunkHeight, long baseSeed, PackRuntime runtime, FloatingIslandBoundarySampler boundarySampler) { + long column = (((long) wx) << 32) ^ (wz & 0xFFFFFFFFL); + FloatingIslandMemo memo = runtime.floatingIslandMemo(); + memo.enterChunk(wx >> 4, wz >> 4, chunkHeight, baseSeed, boundarySampler); + FloatingIslandMemo.MemoizedSample cached = memo.find(parent, column); + if (cached != null) { + return cached.sample(); } - MemoizedSample cached = memo.samples.get(key); - if (cached != null && cached.parent == parent) { - return cached.sample; - } - FloatingIslandSample result = sample(parent, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler); - memo.samples.put(key, new MemoizedSample(parent, result)); + FloatingIslandSample result = sample(parent, wx, wz, chunkHeight, baseSeed, runtime, boundarySampler); + memo.remember(parent, column, result); return result; } @@ -184,18 +165,18 @@ public final class FloatingIslandSample { } private static int maximumEdgeFieldWidth(KList entries, long baseSeed, - IrisData data, IrisBiome parent) { + PackRuntime runtime, IrisBiome parent) { int maximumWidth = FloatingIslandEdgeProfile.MIN_WIDTH; for (IrisFloatingChildBiomes entry : entries) { - FloatingIslandEdgeProfile profile = resolveEdgeProfile(entry, baseSeed, data, parent); + FloatingIslandEdgeProfile profile = resolveEdgeProfile(entry, baseSeed, runtime, parent); maximumWidth = Math.max(maximumWidth, profile.fieldWidth()); } return maximumWidth; } private static FloatingIslandEdgeProfile resolveEdgeProfile(IrisFloatingChildBiomes entry, long baseSeed, - IrisData data, IrisBiome parent) { - FloatingIslandEdgeProfile profile = entry.getEdgeTaperProfile(baseSeed, data); + PackRuntime runtime, IrisBiome parent) { + FloatingIslandEdgeProfile profile = entry.getEdgeTaperProfile(baseSeed, runtime); if (profile != null) { return profile; } @@ -203,17 +184,17 @@ public final class FloatingIslandSample { return FloatingIslandEdgeProfile.DEFAULT; } - public static FloatingIslandSample sample(IrisBiome parent, int wx, int wz, int chunkHeight, long baseSeed, IrisData data, Engine engine, FloatingIslandBoundarySampler boundarySampler) { + public static FloatingIslandSample sample(IrisBiome parent, int wx, int wz, int chunkHeight, long baseSeed, PackRuntime runtime, FloatingIslandBoundarySampler boundarySampler) { KList entries = parent.getFloatingChildBiomes(); if (entries == null || entries.isEmpty()) { return reject(REJECT_NO_ENTRIES); } - int boundaryFieldWidth = maximumEdgeFieldWidth(entries, baseSeed, data, parent); + int boundaryFieldWidth = maximumEdgeFieldWidth(entries, baseSeed, runtime, parent); int parentBoundaryDistance = boundarySampler.edgeDistance(parent, wx, wz, boundaryFieldWidth); if (parent.isMergeFloatingChildBiomes()) { - return sampleMerged(parent, entries, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler, + return sampleMerged(parent, entries, wx, wz, chunkHeight, baseSeed, runtime, boundarySampler, parentBoundaryDistance, boundaryFieldWidth); } @@ -223,7 +204,7 @@ public final class FloatingIslandSample { entry = entries.getFirst(); } else { IrisFloatingChildBiomes reference = entries.getFirst(); - CNG picker = reference.getPickerCng(baseSeed, data); + CNG picker = reference.getPickerCng(baseSeed, runtime); if (picker == null) { warnNullCng("pickerStyle", parent); return reject(REJECT_NO_PICK); @@ -237,20 +218,20 @@ public final class FloatingIslandSample { ownershipBoundaryDistance = ownership.boundaryDistance(); } - return sampleEntry(parent, entry, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler, + return sampleEntry(parent, entry, wx, wz, chunkHeight, baseSeed, runtime, boundarySampler, parentBoundaryDistance, ownershipBoundaryDistance); } private static FloatingIslandSample sampleMerged(IrisBiome parent, KList entries, - int wx, int wz, int chunkHeight, long baseSeed, IrisData data, - Engine engine, FloatingIslandBoundarySampler boundarySampler, + int wx, int wz, int chunkHeight, long baseSeed, PackRuntime runtime, + FloatingIslandBoundarySampler boundarySampler, int parentBoundaryDistance, int boundaryFieldWidth) { KList samples = new KList<>(); int minY = Integer.MAX_VALUE; int maxY = Integer.MIN_VALUE; for (IrisFloatingChildBiomes entry : entries) { - FloatingIslandSample sample = sampleEntry(parent, entry, wx, wz, chunkHeight, baseSeed, data, engine, + FloatingIslandSample sample = sampleEntry(parent, entry, wx, wz, chunkHeight, baseSeed, runtime, boundarySampler, parentBoundaryDistance, boundaryFieldWidth + 1); if (sample == null) { continue; @@ -313,11 +294,11 @@ public final class FloatingIslandSample { } private static FloatingIslandSample sampleEntry(IrisBiome parent, IrisFloatingChildBiomes entry, int wx, int wz, - int chunkHeight, long baseSeed, IrisData data, Engine engine, + int chunkHeight, long baseSeed, PackRuntime runtime, FloatingIslandBoundarySampler boundarySampler, int parentBoundaryDistance, int ownershipBoundaryDistance) { - FloatingIslandEdgeProfile edgeProfile = resolveEdgeProfile(entry, baseSeed, data, parent); - CNG footprintCng = entry.getFootprintCng(baseSeed, data); + FloatingIslandEdgeProfile edgeProfile = resolveEdgeProfile(entry, baseSeed, runtime, parent); + CNG footprintCng = entry.getFootprintCng(baseSeed, runtime); if (footprintCng == null) { warnNullCng("footprintStyle", parent); return reject(REJECT_NO_SEED); @@ -343,23 +324,23 @@ public final class FloatingIslandSample { return reject(REJECT_NO_THICKNESS); } - CNG altitudeCng = entry.getAltitudeCng(baseSeed, data); + CNG altitudeCng = entry.getAltitudeCng(baseSeed, runtime); if (altitudeCng == null) { warnNullCng("altitudeStyle", parent); return reject(REJECT_NO_SEED); } double altNoise = altitudeCng.noise(wx, wz); double altClamped = Math.max(0, Math.min(1, altNoise)); - int worldMin = engine.getWorld().minHeight(); + int worldMin = runtime.engine().getWorld().minHeight(); int minAlt = Math.max(0, entry.getMinHeightAboveSurface() - worldMin); int maxAlt = Math.max(minAlt, entry.getMaxHeightAboveSurface() - worldMin); int baseY = minAlt + (int) Math.round(altClamped * (maxAlt - minAlt)); - IrisBiome target = entry.getRealBiome(parent, data); - int fullTopHeight = computeTopHeight(entry, target, engine, baseSeed, wx, wz, data); + IrisBiome target = entry.getRealBiome(parent, runtime.data()); + int fullTopHeight = computeTopHeight(entry, target, runtime, baseSeed, wx, wz); int topH = roundedEdgeHeight(fullTopHeight, edgeFade); - CNG bottomCng = entry.getBottomCng(baseSeed, data); + CNG bottomCng = entry.getBottomCng(baseSeed, runtime); if (bottomCng == null) { warnNullCng("bottomStyle", parent); return reject(REJECT_NO_SEED); @@ -416,11 +397,11 @@ public final class FloatingIslandSample { } boolean[] solidMask = new boolean[thickness]; - CNG wallWarp = entry.getWallWarpCng(baseSeed, data); + CNG wallWarp = entry.getWallWarpCng(baseSeed, runtime); double warpAmp = Math.max(0, entry.getWallWarpAmplitude()); double effectiveWarpAmp = effectiveWallWarpAmplitude(warpAmp, edgeFade); - IrisCaveProfileSampler carvingProfileSampler = entry.getCarvingProfileSampler(engine, data); - CNG carve = carvingProfileSampler == null && !entry.hasCarvingReference() ? entry.getCarveCng(baseSeed, data) : null; + IrisCaveProfileSampler carvingProfileSampler = entry.getCarvingProfileSampler(runtime); + CNG carve = carvingProfileSampler == null && !entry.hasCarvingReference() ? entry.getCarveCng(baseSeed, runtime) : null; double carveThreshold = entry.getCarveThreshold(); boolean useWarp = wallWarp != null && effectiveWarpAmp > 0; boolean useProfileCarve = carvingProfileSampler != null; @@ -683,27 +664,7 @@ public final class FloatingIslandSample { } private static double footprintSigned(CNG footprintCng, int wx, int wz) { - IdentityHashMap memoByCng = FOOTPRINT_MEMO.get(); - Long2DoubleOpenHashMap memo = memoByCng.get(footprintCng); - if (memo == null) { - memo = new Long2DoubleOpenHashMap(512); - memo.defaultReturnValue(Double.NaN); - memoByCng.put(footprintCng, memo); - } - - long key = columnKey(wx, wz); - double cached = memo.get(key); - if (!Double.isNaN(cached)) { - return cached; - } - - double signed = signedFromUnit(footprintCng.noise(wx, wz)); - memo.put(key, signed); - return signed; - } - - private static long columnKey(int wx, int wz) { - return ((long) wx << 32) ^ (wz & 0xFFFFFFFFL); + return signedFromUnit(footprintCng.noise(wx, wz)); } private static double signedFromUnit(double value) { @@ -779,7 +740,7 @@ public final class FloatingIslandSample { } } - private static int computeTopHeight(IrisFloatingChildBiomes entry, IrisBiome target, Engine engine, long baseSeed, int wx, int wz, IrisData data) { + private static int computeTopHeight(IrisFloatingChildBiomes entry, IrisBiome target, PackRuntime runtime, long baseSeed, int wx, int wz) { int maxTopHeight = Math.max(0, entry.getMaxTopHeight()); if (maxTopHeight == 0) { return 0; @@ -787,7 +748,7 @@ public final class FloatingIslandSample { return switch (entry.getTopShapeMode()) { case FLAT -> maxTopHeight; case NOISE -> { - CNG topCng = entry.getTopShapeCng(baseSeed, data); + CNG topCng = entry.getTopShapeCng(baseSeed, runtime); if (topCng == null) { warnNullCng("topShapeStyle", null); yield maxTopHeight / 2; @@ -801,7 +762,7 @@ public final class FloatingIslandSample { if (target == null) { yield maxTopHeight / 2; } - double h = target.getHeight(engine, wx, wz, baseSeed); + double h = target.getHeight(runtime, wx, wz, baseSeed); int rounded = (int) Math.round(h); if (rounded < 0) { yield 0; @@ -810,21 +771,4 @@ public final class FloatingIslandSample { } }; } - - private static final class ChunkMemo { - private final HashMap samples = new HashMap<>(256); - private MemoContext context; - } - - private record MemoContext(int chunkX, int chunkZ, int height, long seed, IrisData data, Engine engine, - FloatingIslandBoundarySampler boundarySampler) { - private boolean matches(int chunkX, int chunkZ, int height, long seed, IrisData data, Engine engine, - FloatingIslandBoundarySampler boundarySampler) { - return this.chunkX == chunkX && this.chunkZ == chunkZ && this.height == height && this.seed == seed - && this.data == data && this.engine == engine && this.boundarySampler == boundarySampler; - } - } - - private record MemoizedSample(IrisBiome parent, FloatingIslandSample sample) { - } } diff --git a/core/src/main/java/art/arcane/iris/generation/biome/IrisBiome.java b/core/src/main/java/art/arcane/iris/generation/biome/IrisBiome.java index e60073b90..3dde27044 100644 --- a/core/src/main/java/art/arcane/iris/generation/biome/IrisBiome.java +++ b/core/src/main/java/art/arcane/iris/generation/biome/IrisBiome.java @@ -18,6 +18,7 @@ package art.arcane.iris.generation.biome; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.cave.IrisCaveProfile; import art.arcane.iris.generation.decoration.IrisDecorationPart; import art.arcane.iris.generation.decoration.IrisDecorator; @@ -47,7 +48,6 @@ import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.pack.loading.IrisRegistrant; import art.arcane.iris.generation.runtime.IrisComplex; import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.iris.generation.cache.LazyBoundedCache; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.pack.schema.annotation.ArrayType; import art.arcane.iris.pack.schema.annotation.DependsOn; @@ -63,7 +63,6 @@ import art.arcane.volmlib.util.collection.KSet; import art.arcane.iris.generation.block.DataProvider; import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.noise.CNG; -import art.arcane.iris.generation.context.IrisContext; import art.arcane.volmlib.util.stream.ProceduralStream; import lombok.AccessLevel; import lombok.Data; @@ -93,7 +92,6 @@ import java.util.Objects; @EqualsAndHashCode(callSuper = false) public class IrisBiome extends IrisRegistrant implements Rarity { public static final int CHILD_HOPS = 4; - private static final int BIOME_GENERATOR_CACHE_SIZE = 8; private static final int CHILDREN_SEED_SALT = 2137; private final transient AtomicCache> genCache = new AtomicCache<>(); @@ -104,25 +102,10 @@ public class IrisBiome extends IrisRegistrant implements Rarity { private final transient AtomicCache cacheColorDecoratorLoad = new AtomicCache<>(); private final transient AtomicCache cacheColorLayerLoad = new AtomicCache<>(); private final transient AtomicCache cacheColorDepositLoad = new AtomicCache<>(); - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private final transient LazyBoundedCache childrenGenerators = new LazyBoundedCache<>(8); - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private transient volatile CachedChildGenerator recentChildGenerator; - @Getter(AccessLevel.NONE) - private final transient LazyBoundedCache biomeGenerators = - new LazyBoundedCache<>(BIOME_GENERATOR_CACHE_SIZE); - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private transient volatile SeededBiomeGenerator recentBiomeGenerator; private final transient AtomicCache maxHeight = new AtomicCache<>(); private final transient AtomicCache maxWithObjectHeight = new AtomicCache<>(); private final transient AtomicCache realCarveBiome = new AtomicCache<>(); private final transient AtomicCache> realChildren = new AtomicCache<>(); - private final transient IrisBiomeLayerHeightCache layerHeightGenerators = new IrisBiomeLayerHeightCache(); - private final transient IrisBiomeLayerHeightCache layerCeilingHeightGenerators = new IrisBiomeLayerHeightCache(); - private final transient IrisBiomeLayerHeightCache layerSeaHeightGenerators = new IrisBiomeLayerHeightCache(); private final transient AtomicCache> surfaceOreCache = new AtomicCache<>(); private final transient AtomicCache> undergroundOreCache = new AtomicCache<>(); private final transient AtomicCache surfaceOreBandsCache = new AtomicCache<>(); @@ -274,16 +257,16 @@ public class IrisBiome extends IrisRegistrant implements Rarity { return IrisBiomeOres.canReplaceSurfaceOre(this, state); } - public NativeBlockState generateOres(int x, int y, int z, RNG rng, IrisData data, boolean surface) { - return IrisBiomeOres.generateOres(this, x, y, z, rng, data, surface); + public NativeBlockState generateOres(int x, int y, int z, RNG rng, PackRuntime runtime, boolean surface) { + return IrisBiomeOres.generateOres(this, x, y, z, rng, runtime, surface); } - public NativeBlockState generateSurfaceOres(int x, int y, int z, RNG rng, IrisData data) { - return IrisBiomeOres.generateSurfaceOres(this, x, y, z, rng, data); + public NativeBlockState generateSurfaceOres(int x, int y, int z, RNG rng, PackRuntime runtime) { + return IrisBiomeOres.generateSurfaceOres(this, x, y, z, rng, runtime); } - public NativeBlockState generateUndergroundOres(int x, int y, int z, RNG rng, IrisData data) { - return IrisBiomeOres.generateUndergroundOres(this, x, y, z, rng, data); + public NativeBlockState generateUndergroundOres(int x, int y, int z, RNG rng, PackRuntime runtime) { + return IrisBiomeOres.generateUndergroundOres(this, x, y, z, rng, runtime); } public boolean hasSurfaceOres() { @@ -469,68 +452,37 @@ public class IrisBiome extends IrisRegistrant implements Rarity { }); } - public double getHeight(Engine xg, double x, double z, long seed) { + public double getHeight(PackRuntime runtime, double x, double z, long seed) { double height = 0; for (IrisBiomeGeneratorLink i : generators) { - height += i.getHeight(xg, x, z, seed); + height += i.getHeight(runtime, x, z, seed); } - return Math.max(0, Math.min(height, xg.getHeight())); - } - - public CNG getBiomeGenerator(RNG random) { - IrisData loader = getLoader(); - Engine engine = resolveBiomeGeneratorEngine(loader); - return getBiomeGenerator(random, engine); + return Math.max(0, Math.min(height, runtime.engine().getHeight())); } + /** Engines seed the scatter generator from their own biome seed; engine-less tools use the caller's seed. */ public CNG getBiomeGenerator(RNG random, Engine engine) { - IrisData loader = getLoader(); long seed = engine == null ? random.getSeed() : engine.getSeedManager().getBiome(); - SeededBiomeGenerator recent = recentBiomeGenerator; - if (recent != null && recent.seed == seed) { - return recent.generator; - } - - CNG generator = biomeGenerators.computeIfAbsent(seed, ignored -> createBiomeGenerator(seed, loader)); - recentBiomeGenerator = new SeededBiomeGenerator(seed, generator); - return generator; + return PackRuntime.of(engine, getLoader()).biome(this).biomeGenerator(seed); } - private Engine resolveBiomeGeneratorEngine(IrisData loader) { - IrisContext context = IrisContext.get(); - if (context != null) { - Engine contextEngine = context.getEngine(); - if (!contextEngine.isClosed() && (loader == null || contextEngine.getData() == loader)) { - return contextEngine; - } - } - - return loader == null ? null : loader.getEngine(); - } - - private CNG createBiomeGenerator(long seed, IrisData loader) { + CNG createBiomeGenerator(long seed, PackRuntime runtime) { int signature = 213949 + 228888 + getRarity() + getName().length(); - return biomeStyle.createNoCache(new RNG(seed).nextParallelRNG(signature), loader); + return biomeStyle.createNoCache(new RNG(seed).nextParallelRNG(signature), runtime); } - public CNG getChildrenGenerator(RNG random, int sig, double scale) { - return getChildrenGenerator(deriveChildStyleSeed(random, sig).getSeed(), scale); + public CNG getChildrenGenerator(PackRuntime runtime, RNG random, int sig, double scale) { + return getChildrenGenerator(runtime, deriveChildStyleSeed(random, sig).getSeed(), scale); } - public CNG getChildrenGenerator(long seed, double scale) { - IrisData data = getLoader(); - Engine engine = data == null ? null : data.getEngine(); - CachedChildGenerator recent = recentChildGenerator; - if (recent != null && recent.key.matches(seed, scale, data, engine)) { - return recent.generator; - } - ChildGeneratorKey key = new ChildGeneratorKey(seed, scale, data, engine); - CNG generator = childrenGenerators.computeIfAbsent(key, - ignored -> getChildStyle().createScaledGenerator(new RNG(seed), data, scale)); - recentChildGenerator = new CachedChildGenerator(key, generator); - return generator; + public CNG getChildrenGenerator(PackRuntime runtime, long seed, double scale) { + return runtime.biome(this).childrenGenerator(seed, scale); + } + + CNG createChildrenGenerator(long seed, double scale, PackRuntime runtime) { + return getChildStyle().createScaledGenerator(new RNG(seed), runtime, scale); } static RNG deriveChildStyleSeed(RNG random, int signature) { @@ -541,24 +493,24 @@ public class IrisBiome extends IrisRegistrant implements Rarity { return deriveChildStyleSeed(random, signature).getSeed(); } - public KList generateLayers(IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, IrisComplex complex) { - return IrisBiomeLayerGenerator.generateLayers(this, dim, wx, wz, random, maxDepth, height, rdata, complex); + public KList generateLayers(IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, PackRuntime runtime, IrisComplex complex) { + return IrisBiomeLayerGenerator.generateLayers(this, dim, wx, wz, random, maxDepth, height, runtime, complex); } - public KList generateLayersWithSlope(IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, ProceduralStream slopeStream) { - return IrisBiomeLayerGenerator.generateLayers(this, dim, wx, wz, random, maxDepth, height, rdata, slopeStream); + public KList generateLayersWithSlope(IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, PackRuntime runtime, ProceduralStream slopeStream) { + return IrisBiomeLayerGenerator.generateLayers(this, dim, wx, wz, random, maxDepth, height, runtime, slopeStream); } - public KList generateCeilingLayers(IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, IrisComplex complex) { - return IrisBiomeLayerGenerator.generateCeilingLayers(this, dim, wx, wz, random, maxDepth, height, rdata, complex); + public KList generateCeilingLayers(IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, PackRuntime runtime, IrisComplex complex) { + return IrisBiomeLayerGenerator.generateCeilingLayers(this, dim, wx, wz, random, maxDepth, height, runtime, complex); } - public KList generateLockedLayers(double wx, double wz, RNG random, int maxDepthf, int height, IrisData rdata, IrisComplex complex) { - return IrisBiomeLayerGenerator.generateLockedLayers(this, wx, wz, random, maxDepthf, height, rdata, complex); + public KList generateLockedLayers(double wx, double wz, RNG random, int maxDepthf, int height, PackRuntime runtime, IrisComplex complex) { + return IrisBiomeLayerGenerator.generateLockedLayers(this, wx, wz, random, maxDepthf, height, runtime, complex); } - public KList generateSeaLayers(double wx, double wz, RNG random, int maxDepth, IrisData rdata) { - return IrisBiomeLayerGenerator.generateSeaLayers(this, wx, wz, random, maxDepth, rdata); + public KList generateSeaLayers(double wx, double wz, RNG random, int maxDepth, PackRuntime runtime) { + return IrisBiomeLayerGenerator.generateSeaLayers(this, wx, wz, random, maxDepth, runtime); } /** @@ -573,20 +525,20 @@ public class IrisBiome extends IrisRegistrant implements Rarity { return IrisBiomeLayerGenerator.getMaxWithObjectHeight(this, data, engine); } - public KList getLayerHeightGenerators(RNG rng, IrisData rdata) { - return IrisBiomeLayerGenerator.getLayerHeightGenerators(this, rng, rdata); + public KList getLayerHeightGenerators(RNG rng, PackRuntime runtime) { + return runtime.biome(this).layerHeights(rng.getSeed()); } - public KList getLayerSeaHeightGenerators(RNG rng, IrisData data) { - return IrisBiomeLayerGenerator.getLayerSeaHeightGenerators(this, rng, data); + public KList getLayerSeaHeightGenerators(RNG rng, PackRuntime runtime) { + return runtime.biome(this).seaLayerHeights(rng.getSeed()); } - public KList getCaveCeilingLayerHeightGenerators(RNG rng, IrisData data) { - return IrisBiomeLayerGenerator.getCaveCeilingLayerHeightGenerators(this, rng, data); + public KList getCaveCeilingLayerHeightGenerators(RNG rng, PackRuntime runtime) { + return runtime.biome(this).ceilingLayerHeights(rng.getSeed()); } - public NativeBlockState getSurfaceBlock(int x, int z, RNG rng, IrisData idm) { - return IrisBiomeLayerGenerator.getSurfaceBlock(this, x, z, rng, idm); + public NativeBlockState getSurfaceBlock(int x, int z, RNG rng, PackRuntime runtime) { + return IrisBiomeLayerGenerator.getSurfaceBlock(this, x, z, rng, runtime); } public boolean isLand() { @@ -616,18 +568,10 @@ public class IrisBiome extends IrisRegistrant implements Rarity { return inferredType.equals(InferredType.SHORE); } - public Biome getSkyBiome(RNG rng, double x, double y, double z) { - return IrisBiomeDerivatives.getSkyBiome(this, rng, resolveBiomeGeneratorEngine(getLoader()), x, y, z); - } - public Biome getSkyBiome(RNG rng, Engine engine, double x, double y, double z) { return IrisBiomeDerivatives.getSkyBiome(this, rng, engine, x, y, z); } - public IrisBiomeCustom getCustomBiome(RNG rng, double x, double y, double z) { - return IrisBiomeDerivatives.getCustomBiome(this, rng, resolveBiomeGeneratorEngine(getLoader()), x, y, z); - } - public IrisBiomeCustom getCustomBiome(RNG rng, Engine engine, double x, double y, double z) { return IrisBiomeDerivatives.getCustomBiome(this, rng, engine, x, y, z); } @@ -656,27 +600,14 @@ public class IrisBiome extends IrisRegistrant implements Rarity { return new KList<>(m); } - //TODO: Test - public Biome getGroundBiome(RNG rng, double x, double y, double z) { - return IrisBiomeDerivatives.getGroundBiome(this, rng, resolveBiomeGeneratorEngine(getLoader()), x, y, z); - } - public Biome getGroundBiome(RNG rng, Engine engine, double x, double y, double z) { return IrisBiomeDerivatives.getGroundBiome(this, rng, engine, x, y, z); } - public String getSkyBiomeKey(RNG rng, double x, double y, double z) { - return IrisBiomeDerivatives.getSkyBiomeKey(this, rng, resolveBiomeGeneratorEngine(getLoader()), x, y, z); - } - public String getSkyBiomeKey(RNG rng, Engine engine, double x, double y, double z) { return IrisBiomeDerivatives.getSkyBiomeKey(this, rng, engine, x, y, z); } - public String getGroundBiomeKey(RNG rng, double x, double y, double z) { - return IrisBiomeDerivatives.getGroundBiomeKey(this, rng, resolveBiomeGeneratorEngine(getLoader()), x, y, z); - } - public String getGroundBiomeKey(RNG rng, Engine engine, double x, double y, double z) { return IrisBiomeDerivatives.getGroundBiomeKey(this, rng, engine, x, y, z); } @@ -714,37 +645,4 @@ public class IrisBiome extends IrisRegistrant implements Rarity { public String getTypeName() { return "Biome"; } - - private static final class SeededBiomeGenerator { - private final long seed; - private final CNG generator; - - private SeededBiomeGenerator(long seed, CNG generator) { - this.seed = seed; - this.generator = generator; - } - } - - private record ChildGeneratorKey(long seed, double scale, IrisData data, Engine engine) { - private boolean matches(long seed, double scale, IrisData data, Engine engine) { - return this.seed == seed && Double.doubleToLongBits(this.scale) == Double.doubleToLongBits(scale) - && this.data == data && this.engine == engine; - } - - @Override - public boolean equals(Object object) { - return object instanceof ChildGeneratorKey other && matches(other.seed, other.scale, other.data, other.engine); - } - - @Override - public int hashCode() { - int hash = Long.hashCode(seed); - hash = 31 * hash + Double.hashCode(scale); - hash = 31 * hash + System.identityHashCode(data); - return 31 * hash + System.identityHashCode(engine); - } - } - - private record CachedChildGenerator(ChildGeneratorKey key, CNG generator) { - } } diff --git a/core/src/main/java/art/arcane/iris/generation/biome/IrisBiomeGeneratorLink.java b/core/src/main/java/art/arcane/iris/generation/biome/IrisBiomeGeneratorLink.java index df3c081ad..724dcd290 100644 --- a/core/src/main/java/art/arcane/iris/generation/biome/IrisBiomeGeneratorLink.java +++ b/core/src/main/java/art/arcane/iris/generation/biome/IrisBiomeGeneratorLink.java @@ -18,6 +18,7 @@ package art.arcane.iris.generation.biome; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.noise.IrisGenerator; import art.arcane.volmlib.util.cache.AtomicCache; @@ -81,8 +82,8 @@ public class IrisBiomeGeneratorLink { }); } - public double getHeight(DataProvider xg, double x, double z, long seed) { - double g = getCachedGenerator(xg).getHeight(x, z, seed); + public double getHeight(PackRuntime runtime, double x, double z, long seed) { + double g = getCachedGenerator(runtime::data).getHeight(runtime, x, z, seed); g = g < 0 ? 0 : g; g = g > 1 ? 1 : g; diff --git a/core/src/main/java/art/arcane/iris/generation/biome/IrisBiomeLayerGenerator.java b/core/src/main/java/art/arcane/iris/generation/biome/IrisBiomeLayerGenerator.java index 857d8fcf7..03484f70c 100644 --- a/core/src/main/java/art/arcane/iris/generation/biome/IrisBiomeLayerGenerator.java +++ b/core/src/main/java/art/arcane/iris/generation/biome/IrisBiomeLayerGenerator.java @@ -18,6 +18,7 @@ package art.arcane.iris.generation.biome; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.terrain.IrisDimension; import art.arcane.iris.generation.terrain.IrisSlopeClip; import art.arcane.iris.structure.object.IrisObject; @@ -45,18 +46,18 @@ final class IrisBiomeLayerGenerator { private IrisBiomeLayerGenerator() { } - static KList generateLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, IrisComplex complex) { - return generateLayers(biome, dim, wx, wz, random, maxDepth, height, rdata, complex, null); + static KList generateLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, PackRuntime runtime, IrisComplex complex) { + return generateLayers(biome, dim, wx, wz, random, maxDepth, height, runtime, complex, null); } - static KList generateLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, ProceduralStream slopeStream) { - return generateLayers(biome, dim, wx, wz, random, maxDepth, height, rdata, null, slopeStream); + static KList generateLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, PackRuntime runtime, ProceduralStream slopeStream) { + return generateLayers(biome, dim, wx, wz, random, maxDepth, height, runtime, null, slopeStream); } - private static KList generateLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, IrisComplex complex, ProceduralStream slopeStream) { + private static KList generateLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, PackRuntime runtime, IrisComplex complex, ProceduralStream slopeStream) { if (biome.isLockLayers()) { - KList data = generateLockedLayers(biome, wx, wz, random, maxDepth, height, rdata, complex, slopeStream); - appendSurfaceFallback(data, biome, dim, wx, wz, random, Math.min(maxDepth, biome.getLockLayersMax()), rdata); + KList data = generateLockedLayers(biome, wx, wz, random, maxDepth, height, runtime, complex, slopeStream); + appendSurfaceFallback(data, biome, dim, wx, wz, random, Math.min(maxDepth, biome.getLockLayersMax()), runtime); return data; } @@ -73,7 +74,8 @@ final class IrisBiomeLayerGenerator { return data; } - KList heightGenerators = getLayerHeightGenerators(biome, random, rdata); + BiomeRuntime biomeRuntime = runtime.biome(biome); + KList heightGenerators = biomeRuntime.layerHeights(random.getSeed()); double surfaceSlope = 0D; boolean sampledSlope = false; @@ -98,7 +100,7 @@ final class IrisBiomeLayerGenerator { continue; } - appendLayer(data, layer, i, d, wx, wz, random, maxDepth, rdata); + appendLayer(data, layer, biomeRuntime.surfaceLayer(i), i, d, wx, wz, random, maxDepth); if (data.size() >= maxDepth) { break; @@ -115,12 +117,12 @@ final class IrisBiomeLayerGenerator { } } - appendSurfaceFallback(data, biome, dim, wx, wz, random, maxDepth, rdata); + appendSurfaceFallback(data, biome, dim, wx, wz, random, maxDepth, runtime); return data; } private static void appendSurfaceFallback(KList data, IrisBiome biome, IrisDimension dim, - double wx, double wz, RNG random, int maxDepth, IrisData rdata) { + double wx, double wz, RNG random, int maxDepth, PackRuntime runtime) { if (!data.isEmpty() || maxDepth <= 0 || biome.getLayers().isEmpty()) { return; } @@ -129,11 +131,11 @@ final class IrisBiomeLayerGenerator { fallback = dim.getSurfaceLayerFallback(); } if (fallback == IrisSurfaceLayerFallback.TOP_LAYER) { - appendLayer(data, biome.getLayers().get(0), 0, 1, wx, wz, random, maxDepth, rdata); + appendLayer(data, biome.getLayers().get(0), runtime.biome(biome).surfaceLayer(0), 0, 1, wx, wz, random, maxDepth); } } - static KList generateCeilingLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, IrisComplex complex) { + static KList generateCeilingLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, PackRuntime runtime, IrisComplex complex) { KList data = new KList<>(); if (maxDepth <= 0) { @@ -147,7 +149,8 @@ final class IrisBiomeLayerGenerator { return data; } - KList heightGenerators = getCaveCeilingLayerHeightGenerators(biome, random, rdata); + BiomeRuntime biomeRuntime = runtime.biome(biome); + KList heightGenerators = biomeRuntime.ceilingLayerHeights(random.getSeed()); for (int i = 0; i < layerCount; i++) { IrisBiomePaletteLayer layer = ceilingLayers.get(i); @@ -159,7 +162,7 @@ final class IrisBiomeLayerGenerator { continue; } - appendLayer(data, layer, i, d, wx, wz, random, maxDepth, rdata); + appendLayer(data, layer, biomeRuntime.ceilingLayer(i), i, d, wx, wz, random, maxDepth); if (data.size() >= maxDepth) { break; @@ -179,11 +182,11 @@ final class IrisBiomeLayerGenerator { return data; } - static KList generateLockedLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepthf, int height, IrisData rdata, IrisComplex complex) { - return generateLockedLayers(biome, wx, wz, random, maxDepthf, height, rdata, complex, null); + static KList generateLockedLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepthf, int height, PackRuntime runtime, IrisComplex complex) { + return generateLockedLayers(biome, wx, wz, random, maxDepthf, height, runtime, complex, null); } - private static KList generateLockedLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepthf, int height, IrisData rdata, IrisComplex complex, ProceduralStream slopeStream) { + private static KList generateLockedLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepthf, int height, PackRuntime runtime, IrisComplex complex, ProceduralStream slopeStream) { KList data = new KList<>(); int maxDepth = Math.min(maxDepthf, biome.getLockLayersMax()); KList layers = biome.getLayers(); @@ -192,7 +195,8 @@ final class IrisBiomeLayerGenerator { return data; } - KList heightGenerators = getLayerHeightGenerators(biome, random, rdata); + BiomeRuntime biomeRuntime = runtime.biome(biome); + KList heightGenerators = biomeRuntime.layerHeights(random.getSeed()); int[] boundaries = new int[layerCount + 1]; double surfaceSlope = 0D; boolean sampledSlope = false; @@ -230,7 +234,7 @@ final class IrisBiomeLayerGenerator { double zoom = layer.getZoom(); try { data.add(layer.get(random, layerIndex + offset, - (wx + offset) / zoom, offset, (wz - offset) / zoom, rdata)); + (wx + offset) / zoom, offset, (wz - offset) / zoom, biomeRuntime.surfaceLayer(layerIndex))); } catch (Throwable error) { GenerationFailures.skipPlacement(error, "surface layer", "block", (int) wx, height - depth, (int) wz, biome.getLoadKey()); } @@ -274,7 +278,7 @@ final class IrisBiomeLayerGenerator { : complex.getSlopeStream().getDouble(x, z); } - static KList generateSeaLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepth, IrisData rdata) { + static KList generateSeaLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepth, PackRuntime runtime) { KList data = new KList<>(); KList seaLayers = biome.getSeaLayers(); @@ -284,7 +288,8 @@ final class IrisBiomeLayerGenerator { return data; } - KList heightGenerators = getLayerSeaHeightGenerators(biome, random, rdata); + BiomeRuntime biomeRuntime = runtime.biome(biome); + KList heightGenerators = biomeRuntime.seaLayerHeights(random.getSeed()); for (int i = 0; i < layerCount; i++) { IrisBiomePaletteLayer layer = seaLayers.get(i); @@ -296,7 +301,7 @@ final class IrisBiomeLayerGenerator { continue; } - appendLayer(data, layer, i, d, wx, wz, random, maxDepth, rdata); + appendLayer(data, layer, biomeRuntime.seaLayer(i), i, d, wx, wz, random, maxDepth); if (data.size() >= maxDepth) { break; @@ -306,46 +311,51 @@ final class IrisBiomeLayerGenerator { return data; } - static KList getLayerHeightGenerators(IrisBiome biome, RNG rng, IrisData rdata) { - return getHeightGenerators(biome.getLayerHeightGenerators(), biome.getLayers(), 7235, rng, rdata); + static KList getLayerHeightGenerators(IrisBiome biome, RNG rng, PackRuntime runtime) { + return runtime.biome(biome).layerHeights(rng.getSeed()); } - static KList getLayerSeaHeightGenerators(IrisBiome biome, RNG rng, IrisData data) { - return getHeightGenerators(biome.getLayerSeaHeightGenerators(), biome.getSeaLayers(), 7735, rng, data); + static KList getLayerSeaHeightGenerators(IrisBiome biome, RNG rng, PackRuntime runtime) { + return runtime.biome(biome).seaLayerHeights(rng.getSeed()); } - static KList getCaveCeilingLayerHeightGenerators(IrisBiome biome, RNG rng, IrisData data) { - return getHeightGenerators(biome.getLayerCeilingHeightGenerators(), biome.getCaveCeilingLayers(), 7235, rng, data); + static KList getCaveCeilingLayerHeightGenerators(IrisBiome biome, RNG rng, PackRuntime runtime) { + return runtime.biome(biome).ceilingLayerHeights(rng.getSeed()); } - private static KList getHeightGenerators(IrisBiomeLayerHeightCache cache, - KList layers, - int seedOffset, RNG rng, IrisData data) { - return cache.get(layers, seedOffset, rng, data); + static KList createHeightGenerators(KList layers, int seedOffset, long seed, + PackRuntime runtime) { + RNG rng = new RNG(seed); + KList result = new KList<>(); + int offset = seedOffset; + for (IrisBiomePaletteLayer layer : layers) { + result.add(layer.getHeightGenerator(rng.nextParallelRNG((offset++) * offset * offset * offset), runtime)); + } + return result; } private static void appendLayer(KList blocks, IrisBiomePaletteLayer layer, - int layerIndex, int thickness, double x, double z, - RNG random, int maxDepth, IrisData data) { + PaletteLayerRuntime layerRuntime, int layerIndex, int thickness, double x, double z, + RNG random, int maxDepth) { double zoom = layer.getZoom(); for (int offset = 0; offset < thickness && blocks.size() < maxDepth; offset++) { try { blocks.add(layer.get(random, layerIndex + offset, - (x + offset) / zoom, offset, (z - offset) / zoom, data)); + (x + offset) / zoom, offset, (z - offset) / zoom, layerRuntime)); } catch (Throwable error) { GenerationFailures.skipPlacement(error, "surface layer", "block", (int) x, -1, (int) z, "none"); } } } - static NativeBlockState getSurfaceBlock(IrisBiome biome, int x, int z, RNG rng, IrisData idm) { + static NativeBlockState getSurfaceBlock(IrisBiome biome, int x, int z, RNG rng, PackRuntime runtime) { KList layers = biome.getLayers(); if (layers.isEmpty()) { return B.getState("AIR"); } - return layers.get(0).get(rng, x, 0, z, idm); + return layers.get(0).get(rng, x, 0, z, runtime); } static int getMaxHeight(IrisBiome biome, Engine engine) { diff --git a/core/src/main/java/art/arcane/iris/generation/biome/IrisBiomeLayerHeightCache.java b/core/src/main/java/art/arcane/iris/generation/biome/IrisBiomeLayerHeightCache.java deleted file mode 100644 index d62865fbd..000000000 --- a/core/src/main/java/art/arcane/iris/generation/biome/IrisBiomeLayerHeightCache.java +++ /dev/null @@ -1,68 +0,0 @@ -package art.arcane.iris.generation.biome; - -import art.arcane.iris.generation.cache.LazyBoundedCache; -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.pack.loading.IrisData; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; -import art.arcane.volmlib.util.noise.CNG; - -final class IrisBiomeLayerHeightCache { - private final LazyBoundedCache> generators = new LazyBoundedCache<>(32); - private volatile CachedGenerators recent; - - KList get(KList layers, int seedOffset, RNG rng, IrisData data) { - Engine engine = data == null ? null : data.getEngine(); - long seed = rng.getSeed(); - CachedGenerators cached = recent; - if (cached != null && cached.key.matches(data, engine, seed)) { - return cached.generators; - } - - GeneratorKey key = new GeneratorKey(data, engine, seed); - KList result = generators.computeIfAbsent(key, ignored -> create(layers, seedOffset, rng, data)); - recent = new CachedGenerators(key, result); - return result; - } - - private static KList create(KList layers, int seedOffset, RNG rng, IrisData data) { - KList result = new KList<>(); - int offset = seedOffset; - for (IrisBiomePaletteLayer layer : layers) { - result.add(layer.getHeightGenerator(rng.nextParallelRNG((offset++) * offset * offset * offset), data)); - } - return result; - } - - private record CachedGenerators(GeneratorKey key, KList generators) { - } - - private static final class GeneratorKey { - private final IrisData data; - private final Engine engine; - private final long seed; - - private GeneratorKey(IrisData data, Engine engine, long seed) { - this.data = data; - this.engine = engine; - this.seed = seed; - } - - private boolean matches(IrisData data, Engine engine, long seed) { - return this.data == data && this.engine == engine && this.seed == seed; - } - - @Override - public boolean equals(Object object) { - return this == object || object instanceof GeneratorKey other - && matches(other.data, other.engine, other.seed); - } - - @Override - public int hashCode() { - int result = System.identityHashCode(data); - result = 31 * result + System.identityHashCode(engine); - return 31 * result + Long.hashCode(seed); - } - } -} diff --git a/core/src/main/java/art/arcane/iris/generation/biome/IrisBiomeOres.java b/core/src/main/java/art/arcane/iris/generation/biome/IrisBiomeOres.java index 2b1691b8d..8c0bfb698 100644 --- a/core/src/main/java/art/arcane/iris/generation/biome/IrisBiomeOres.java +++ b/core/src/main/java/art/arcane/iris/generation/biome/IrisBiomeOres.java @@ -22,7 +22,7 @@ import art.arcane.iris.generation.decoration.IrisOreGenerator; import art.arcane.iris.generation.decoration.IrisOreBands; import art.arcane.iris.generation.decoration.IrisProceduralBlocks; -import art.arcane.iris.pack.loading.IrisData; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.volmlib.util.cache.AtomicCache; import art.arcane.volmlib.nativelib.terrain.NativeBlockState; import art.arcane.iris.generation.block.B; @@ -39,17 +39,17 @@ final class IrisBiomeOres { private IrisBiomeOres() { } - static NativeBlockState generateOres(IrisBiome biome, int x, int y, int z, RNG rng, IrisData data, boolean surface) { + static NativeBlockState generateOres(IrisBiome biome, int x, int y, int z, RNG rng, PackRuntime runtime, boolean surface) { KList localOres = surface ? getSurfaceOres(biome) : getUndergroundOres(biome); - return generateOres(localOres, x, y, z, rng, data); + return generateOres(localOres, x, y, z, rng, runtime); } - static NativeBlockState generateSurfaceOres(IrisBiome biome, int x, int y, int z, RNG rng, IrisData data) { - return generateOres(getSurfaceOres(biome), x, y, z, rng, data); + static NativeBlockState generateSurfaceOres(IrisBiome biome, int x, int y, int z, RNG rng, PackRuntime runtime) { + return generateOres(getSurfaceOres(biome), x, y, z, rng, runtime); } - static NativeBlockState generateUndergroundOres(IrisBiome biome, int x, int y, int z, RNG rng, IrisData data) { - return generateOres(getUndergroundOres(biome), x, y, z, rng, data); + static NativeBlockState generateUndergroundOres(IrisBiome biome, int x, int y, int z, RNG rng, PackRuntime runtime) { + return generateOres(getUndergroundOres(biome), x, y, z, rng, runtime); } static boolean hasSurfaceOres(IrisBiome biome) { @@ -122,7 +122,7 @@ final class IrisBiomeOres { }); } - private static NativeBlockState generateOres(KList localOres, int x, int y, int z, RNG rng, IrisData data) { + private static NativeBlockState generateOres(KList localOres, int x, int y, int z, RNG rng, PackRuntime runtime) { if (localOres.isEmpty()) { return null; } @@ -130,7 +130,7 @@ final class IrisBiomeOres { int oreCount = localOres.size(); for (int oreIndex = 0; oreIndex < oreCount; oreIndex++) { IrisOreGenerator oreGenerator = localOres.get(oreIndex); - NativeBlockState ore = oreGenerator.generate(x, y, z, rng, data); + NativeBlockState ore = oreGenerator.generate(x, y, z, rng, runtime); if (ore != null) { return ore; } diff --git a/core/src/main/java/art/arcane/iris/generation/biome/IrisBiomePaletteLayer.java b/core/src/main/java/art/arcane/iris/generation/biome/IrisBiomePaletteLayer.java index e9a083b75..f4192a042 100644 --- a/core/src/main/java/art/arcane/iris/generation/biome/IrisBiomePaletteLayer.java +++ b/core/src/main/java/art/arcane/iris/generation/biome/IrisBiomePaletteLayer.java @@ -18,6 +18,7 @@ package art.arcane.iris.generation.biome; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.block.IrisBlockData; import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.NoiseStyle; @@ -25,8 +26,6 @@ import art.arcane.iris.generation.terrain.IrisSlopeClip; import art.arcane.iris.pack.loading.IrisData; import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.iris.generation.cache.LazyBoundedCache; -import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.pack.schema.annotation.ArrayType; import art.arcane.iris.pack.schema.annotation.DependsOn; import art.arcane.volmlib.util.documentation.Description; @@ -37,17 +36,12 @@ import art.arcane.iris.pack.schema.annotation.Snippet; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.noise.CNG; -import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Data; -import lombok.Getter; import lombok.NoArgsConstructor; import art.arcane.volmlib.nativelib.terrain.NativeBlockState; -import lombok.Setter; import lombok.experimental.Accessors; -import java.util.concurrent.atomic.AtomicReference; -import java.util.concurrent.atomic.AtomicReferenceArray; @Snippet("biome-palette") @Accessors(chain = true) @@ -56,24 +50,7 @@ import java.util.concurrent.atomic.AtomicReferenceArray; @Description("A layer of surface / subsurface material in biomes") @Data public class IrisBiomePaletteLayer { - private static final int LAYER_GENERATOR_CACHE_SIZE = 32; - private final transient AtomicCache> blockData = new AtomicCache<>(); - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private final transient LazyBoundedCache layerGenerators = - new LazyBoundedCache<>(LAYER_GENERATOR_CACHE_SIZE); - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private final transient AtomicReferenceArray recentLayerGenerators = - new AtomicReferenceArray<>(LAYER_GENERATOR_CACHE_SIZE); - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private final transient LazyBoundedCache heightGenerators = - new LazyBoundedCache<>(LAYER_GENERATOR_CACHE_SIZE); - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private final transient AtomicReference recentHeightGenerator = new AtomicReference<>(); @Description("The style of noise") private IrisGeneratorStyle style = NoiseStyle.STATIC.style(); @DependsOn({"minHeight", "maxHeight"}) @@ -98,23 +75,17 @@ public class IrisBiomePaletteLayer { @Description("The palette of blocks to be used in this layer") private KList palette = new KList().qadd(new IrisBlockData("GRASS_BLOCK")); - public CNG getHeightGenerator(RNG rng, IrisData data) { - Engine engine = data == null ? null : data.getEngine(); - long generatorSeed = rng.getSeed() + minHeight * maxHeight + getBlockData(data).size(); - CachedLayerGenerator recent = recentHeightGenerator.get(); - if (recent != null && recent.key.matches(data, engine, generatorSeed)) { - return recent.generator; - } - - LayerGeneratorKey key = new LayerGeneratorKey(data, engine, generatorSeed); - CNG generator = heightGenerators.computeIfAbsent(key, - ignored -> CNG.signature(new RNG(generatorSeed))); - recentHeightGenerator.set(new CachedLayerGenerator(key, generator)); - return generator; + public CNG getHeightGenerator(RNG rng, PackRuntime runtime) { + long generatorSeed = rng.getSeed() + minHeight * maxHeight + getBlockData(runtime.data()).size(); + return runtime.paletteLayer(this).heightGenerator(generatorSeed); } - public NativeBlockState get(RNG rng, double x, double y, double z, IrisData data) { - return get(rng, 0, x, y, z, data); + static CNG createHeightGenerator(long generatorSeed) { + return CNG.signature(new RNG(generatorSeed)); + } + + public NativeBlockState get(RNG rng, double x, double y, double z, PackRuntime runtime) { + return get(rng, 0, x, y, z, runtime); } /** @@ -122,44 +93,45 @@ public class IrisBiomePaletteLayer { * only built inside the lazy layer generator initializer, using the exact same seed derivation * as {@code parent.nextParallelRNG(signature)} followed by the generator signature. */ - public NativeBlockState get(RNG parent, int signature, double x, double y, double z, IrisData data) { - KList localBlockData = getBlockData(data); - - if (localBlockData.isEmpty()) { - return null; + public NativeBlockState get(RNG parent, int signature, double x, double y, double z, PackRuntime runtime) { + KList localBlockData = getBlockData(runtime.data()); + if (localBlockData.size() <= 1) { + return localBlockData.isEmpty() ? null : localBlockData.get(0); } + return fit(localBlockData, runtime.paletteLayer(this), parent, signature, x, y, z); + } - if (localBlockData.size() == 1) { - return localBlockData.get(0); + /** {@link #get(RNG, int, double, double, double, PackRuntime)} for a caller that already holds this layer's runtime. */ + public NativeBlockState get(RNG parent, int signature, double x, double y, double z, PaletteLayerRuntime layerRuntime) { + KList localBlockData = getBlockData(layerRuntime.packRuntime().data()); + if (localBlockData.size() <= 1) { + return localBlockData.isEmpty() ? null : localBlockData.get(0); } + return fit(localBlockData, layerRuntime, parent, signature, x, y, z); + } + private NativeBlockState fit(KList localBlockData, PaletteLayerRuntime layerRuntime, + RNG parent, int signature, double x, double y, double z) { double localZoom = zoom; - double scaledX = x / localZoom; - double scaledY = y / localZoom; - double scaledZ = z / localZoom; - return getLayerGenerator(parent, signature, data).fit(localBlockData, scaledX, scaledY, scaledZ); + CNG generator = layerRuntime.layerGenerator(layerGeneratorSeed(parent, signature, localBlockData.size())); + return generator.fit(localBlockData, x / localZoom, y / localZoom, z / localZoom); } - public CNG getLayerGenerator(RNG rng, IrisData data) { - return getLayerGenerator(rng, 0, data); + public CNG getLayerGenerator(RNG rng, PackRuntime runtime) { + return getLayerGenerator(rng, 0, runtime); } - public CNG getLayerGenerator(RNG parent, int signature, IrisData data) { - Engine engine = data == null ? null : data.getEngine(); - long generatorSeed = parent.getSeed() + signature + minHeight + maxHeight + getBlockData(data).size(); - int slot = (int) generatorSeed & (LAYER_GENERATOR_CACHE_SIZE - 1); - CachedLayerGenerator recent = recentLayerGenerators.getAcquire(slot); - if (recent != null && recent.key.matches(data, engine, generatorSeed)) { - return recent.generator; - } + public CNG getLayerGenerator(RNG parent, int signature, PackRuntime runtime) { + long generatorSeed = layerGeneratorSeed(parent, signature, getBlockData(runtime.data()).size()); + return runtime.paletteLayer(this).layerGenerator(generatorSeed); + } - LayerGeneratorKey key = new LayerGeneratorKey(data, engine, generatorSeed); - CNG generator = layerGenerators.computeIfAbsent(key, - ignored -> style.create(new RNG(generatorSeed), data, engine)); - if (generator != null) { - recentLayerGenerators.setRelease(slot, new CachedLayerGenerator(key, generator)); - } - return generator; + private long layerGeneratorSeed(RNG parent, int signature, int blockCount) { + return parent.getSeed() + signature + minHeight + maxHeight + blockCount; + } + + CNG createLayerGenerator(long generatorSeed, PackRuntime runtime) { + return style.createNoCache(new RNG(generatorSeed), runtime); } public KList add(String b) { @@ -195,49 +167,4 @@ public class IrisBiomePaletteLayer { palette.clear(); return this; } - - private static final class LayerGeneratorKey { - private final IrisData data; - private final Engine engine; - private final long seed; - - private LayerGeneratorKey(IrisData data, Engine engine, long seed) { - this.data = data; - this.engine = engine; - this.seed = seed; - } - - private boolean matches(IrisData data, Engine engine, long seed) { - return this.data == data && this.engine == engine && this.seed == seed; - } - - @Override - public boolean equals(Object object) { - if (this == object) { - return true; - } - if (!(object instanceof LayerGeneratorKey other)) { - return false; - } - return data == other.data && engine == other.engine && seed == other.seed; - } - - @Override - public int hashCode() { - int result = System.identityHashCode(data); - result = 31 * result + System.identityHashCode(engine); - result = 31 * result + Long.hashCode(seed); - return result; - } - } - - private static final class CachedLayerGenerator { - private final LayerGeneratorKey key; - private final CNG generator; - - private CachedLayerGenerator(LayerGeneratorKey key, CNG generator) { - this.key = key; - this.generator = generator; - } - } } diff --git a/core/src/main/java/art/arcane/iris/generation/biome/IrisFloatingChildBiomes.java b/core/src/main/java/art/arcane/iris/generation/biome/IrisFloatingChildBiomes.java index 55111cad3..aa66a2a0d 100644 --- a/core/src/main/java/art/arcane/iris/generation/biome/IrisFloatingChildBiomes.java +++ b/core/src/main/java/art/arcane/iris/generation/biome/IrisFloatingChildBiomes.java @@ -18,6 +18,7 @@ package art.arcane.iris.generation.biome; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.cave.IrisCaveProfileSampler; import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.NoiseStyle; @@ -33,10 +34,6 @@ import art.arcane.volmlib.util.math.Rarity; import art.arcane.iris.pack.loading.IrisData; import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.iris.generation.cache.LazyBoundedCache; -import lombok.AccessLevel; -import lombok.Getter; -import lombok.Setter; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.pack.schema.annotation.ArrayType; import art.arcane.volmlib.util.documentation.Description; @@ -62,97 +59,72 @@ import lombok.experimental.Accessors; @Data public class IrisFloatingChildBiomes implements Rarity { private final transient AtomicCache resolvedBiome = new AtomicCache<>(); - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private final transient LazyBoundedCache edgeTaperProfiles = new LazyBoundedCache<>(8); - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private transient volatile CachedEdgeProfile recentEdgeProfile; - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private final transient LazyBoundedCache carvingProfileSamplers = new LazyBoundedCache<>(8); - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private transient volatile CachedCarvingProfile recentCarvingProfile; private final transient AtomicCache shrinkScaleCache = new AtomicCache<>(); - public CNG getFootprintCng(long baseSeed, IrisData data) { - return getFootprintStyle().create(baseSeed ^ 0xF007B17DL, data); + public CNG getFootprintCng(long baseSeed, PackRuntime runtime) { + return getFootprintStyle().create(baseSeed ^ 0xF007B17DL, runtime); } - public FloatingIslandEdgeProfile getEdgeTaperProfile(long baseSeed, IrisData data) { - Engine engine = data == null ? null : data.getEngine(); - CachedEdgeProfile recent = recentEdgeProfile; - if (recent != null && recent.key.matches(baseSeed, data, engine)) { - return recent.profile; - } - RuntimeKey key = new RuntimeKey(baseSeed, data, engine); - FloatingIslandEdgeProfile profile = edgeTaperProfiles.computeIfAbsent(key, ignored -> { - int width = FloatingIslandEdgeProfile.clampWidth(getEdgeTaperWidth()); - double amplitude = FloatingIslandEdgeProfile.clampVariationAmplitude( - getEdgeTaperVariationAmplitude(), width); - IrisGeneratorStyle style = getEdgeTaperVariationStyle(); - CNG variation = amplitude > 0.0D && style != null - ? style.create(baseSeed ^ 0xED6E7A9E5L, data) - : null; - return new FloatingIslandEdgeProfile(width, getEdgeTaperExponent(), amplitude, variation); - }); - recentEdgeProfile = new CachedEdgeProfile(key, profile); - return profile; + public FloatingIslandEdgeProfile getEdgeTaperProfile(long baseSeed, PackRuntime runtime) { + return runtime.floatingChild(this).edgeTaperProfile(baseSeed); } - public CNG getPickerCng(long baseSeed, IrisData data) { - return getPickerStyle().create(baseSeed ^ 0x91C4E72DL, data); + FloatingIslandEdgeProfile createEdgeTaperProfile(long baseSeed, PackRuntime runtime) { + int width = FloatingIslandEdgeProfile.clampWidth(getEdgeTaperWidth()); + double amplitude = FloatingIslandEdgeProfile.clampVariationAmplitude(getEdgeTaperVariationAmplitude(), width); + IrisGeneratorStyle style = getEdgeTaperVariationStyle(); + CNG variation = amplitude > 0.0D && style != null + ? style.create(baseSeed ^ 0xED6E7A9E5L, runtime) + : null; + return new FloatingIslandEdgeProfile(width, getEdgeTaperExponent(), amplitude, variation); } - public CNG getAltitudeCng(long baseSeed, IrisData data) { - return getAltitudeStyle().create(baseSeed ^ 0xA17DEBBL, data); + public CNG getPickerCng(long baseSeed, PackRuntime runtime) { + return getPickerStyle().create(baseSeed ^ 0x91C4E72DL, runtime); } - public CNG getTopShapeCng(long baseSeed, IrisData data) { - return getTopShapeStyle().create(baseSeed ^ 0x70970601DEFL, data); + public CNG getAltitudeCng(long baseSeed, PackRuntime runtime) { + return getAltitudeStyle().create(baseSeed ^ 0xA17DEBBL, runtime); } - public CNG getBottomCng(long baseSeed, IrisData data) { - return getBottomStyle().create(baseSeed ^ 0xB0770075CAFEL, data); + public CNG getTopShapeCng(long baseSeed, PackRuntime runtime) { + return getTopShapeStyle().create(baseSeed ^ 0x70970601DEFL, runtime); } - public CNG getWallWarpCng(long baseSeed, IrisData data) { + public CNG getBottomCng(long baseSeed, PackRuntime runtime) { + return getBottomStyle().create(baseSeed ^ 0xB0770075CAFEL, runtime); + } + + public CNG getWallWarpCng(long baseSeed, PackRuntime runtime) { IrisGeneratorStyle style = getWallWarpStyle(); if (style == null) { return null; } - return style.create(baseSeed ^ 0xA117BA17E0FL, data); + return style.create(baseSeed ^ 0xA117BA17E0FL, runtime); } - public CNG getCarveCng(long baseSeed, IrisData data) { + public CNG getCarveCng(long baseSeed, PackRuntime runtime) { IrisGeneratorStyle style = getCarveStyle(); if (style == null) { return null; } - return style.create(baseSeed ^ 0xCA5EC1EE5EL, data); + return style.create(baseSeed ^ 0xCA5EC1EE5EL, runtime); } - public IrisCaveProfileSampler getCarvingProfileSampler(Engine engine, IrisData data) { + public IrisCaveProfileSampler getCarvingProfileSampler(PackRuntime runtime) { if (!hasCarvingReference()) { return null; } + return runtime.floatingChild(this).carvingProfileSampler(); + } - CachedCarvingProfile recent = recentCarvingProfile; - if (recent != null && recent.key.matches(0L, data, engine)) { - return recent.sampler; + IrisCaveProfileSampler createCarvingProfileSampler(PackRuntime runtime) { + Engine engine = runtime.engine(); + IrisBiome resolved = resolveCarvingBiome(carving, engine, runtime.data()); + if (resolved == null || resolved.getCaveProfile() == null || !resolved.getCaveProfile().isEnabled()) { + return null; } - RuntimeKey key = new RuntimeKey(0L, data, engine); - IrisCaveProfileSampler sampler = carvingProfileSamplers.computeIfAbsent(key, ignored -> { - IrisBiome resolved = resolveCarvingBiome(carving, engine, data); - if (resolved == null || resolved.getCaveProfile() == null || !resolved.getCaveProfile().isEnabled()) { - return null; - } - - return new IrisCaveProfileSampler(engine, resolved.getCaveProfile()); - }); - recentCarvingProfile = new CachedCarvingProfile(key, sampler); - return sampler; + return new IrisCaveProfileSampler(engine, resolved.getCaveProfile()); } public boolean hasCarvingReference() { @@ -400,28 +372,4 @@ public class IrisFloatingChildBiomes implements Rarity { return loaded; }); } - - private record RuntimeKey(long seed, IrisData data, Engine engine) { - private boolean matches(long seed, IrisData data, Engine engine) { - return this.seed == seed && this.data == data && this.engine == engine; - } - - @Override - public boolean equals(Object object) { - return object instanceof RuntimeKey other && matches(other.seed, other.data, other.engine); - } - - @Override - public int hashCode() { - int hash = Long.hashCode(seed); - hash = 31 * hash + System.identityHashCode(data); - return 31 * hash + System.identityHashCode(engine); - } - } - - private record CachedEdgeProfile(RuntimeKey key, FloatingIslandEdgeProfile profile) { - } - - private record CachedCarvingProfile(RuntimeKey key, IrisCaveProfileSampler sampler) { - } } diff --git a/core/src/main/java/art/arcane/iris/generation/biome/PaletteLayerRuntime.java b/core/src/main/java/art/arcane/iris/generation/biome/PaletteLayerRuntime.java new file mode 100644 index 000000000..2f9383f04 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/biome/PaletteLayerRuntime.java @@ -0,0 +1,57 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.generation.biome; + +import art.arcane.iris.generation.runtime.PackRuntime; +import art.arcane.iris.generation.runtime.SeedTable; +import art.arcane.volmlib.util.noise.CNG; + +/** + * What one engine derives from an {@link IrisBiomePaletteLayer}: the block selection and depth generators of the + * seeds that sample it. + */ +public final class PaletteLayerRuntime { + private static final int LAYER_SEED_CAPACITY = 32; + private static final int LAYER_RECENT_SLOTS = 32; + private static final int HEIGHT_SEED_CAPACITY = 32; + + private final PackRuntime runtime; + private final SeedTable layerGenerators; + private final SeedTable heightGenerators; + + public PaletteLayerRuntime(IrisBiomePaletteLayer layer, PackRuntime runtime) { + this.runtime = runtime; + this.layerGenerators = new SeedTable<>(LAYER_SEED_CAPACITY, LAYER_RECENT_SLOTS, + seed -> layer.createLayerGenerator(seed, runtime)); + this.heightGenerators = new SeedTable<>(HEIGHT_SEED_CAPACITY, IrisBiomePaletteLayer::createHeightGenerator); + } + + /** The scope this runtime was built in, whose pack data resolves the layer's palette. */ + public PackRuntime packRuntime() { + return runtime; + } + + public CNG layerGenerator(long seed) { + return layerGenerators.get(seed); + } + + public CNG heightGenerator(long seed) { + return heightGenerators.get(seed); + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/cache/LazyBoundedCache.java b/core/src/main/java/art/arcane/iris/generation/cache/LazyBoundedCache.java deleted file mode 100644 index 05a79e4ff..000000000 --- a/core/src/main/java/art/arcane/iris/generation/cache/LazyBoundedCache.java +++ /dev/null @@ -1,49 +0,0 @@ -package art.arcane.iris.generation.cache; - -import java.util.LinkedHashMap; -import java.util.Objects; -import java.util.function.Function; - -public final class LazyBoundedCache { - private final int maximumSize; - private transient LinkedHashMap entries; - - public LazyBoundedCache(int maximumSize) { - if (maximumSize <= 0) { - throw new IllegalArgumentException("Maximum cache size must be positive"); - } - this.maximumSize = maximumSize; - } - - public synchronized V computeIfAbsent(K key, Function mappingFunction) { - K requiredKey = Objects.requireNonNull(key, "Cache key"); - Function requiredMapping = Objects.requireNonNull(mappingFunction, "Cache mapping function"); - if (entries != null) { - V cached = entries.get(requiredKey); - if (cached != null) { - return cached; - } - } - - V computed = requiredMapping.apply(requiredKey); - if (computed == null) { - return null; - } - if (entries == null) { - entries = new LinkedHashMap<>(maximumSize, 1F, true); - } - entries.put(requiredKey, computed); - if (entries.size() > maximumSize) { - entries.sequencedKeySet().removeFirst(); - } - return computed; - } - - synchronized boolean isInitialized() { - return entries != null; - } - - synchronized int size() { - return entries == null ? 0 : entries.size(); - } -} diff --git a/core/src/main/java/art/arcane/iris/generation/cave/IrisCaveProfileSampler.java b/core/src/main/java/art/arcane/iris/generation/cave/IrisCaveProfileSampler.java index a78b2250e..2e41aee21 100644 --- a/core/src/main/java/art/arcane/iris/generation/cave/IrisCaveProfileSampler.java +++ b/core/src/main/java/art/arcane/iris/generation/cave/IrisCaveProfileSampler.java @@ -22,7 +22,7 @@ import art.arcane.iris.pack.value.IrisRange; import art.arcane.iris.generation.noise.IrisStyledRange; import art.arcane.volmlib.util.math.M; -import art.arcane.iris.pack.loading.IrisData; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.runtime.Engine; import art.arcane.volmlib.util.noise.CNG; import art.arcane.volmlib.util.math.RNG; @@ -52,18 +52,18 @@ public final class IrisCaveProfileSampler { private final boolean hasModules; public IrisCaveProfileSampler(Engine engine, IrisCaveProfile profile) { - IrisData data = engine.getData(); + PackRuntime runtime = PackRuntime.of(engine, engine.getData()); this.profile = profile; List moduleStates = new ArrayList<>(); RNG baseRng = new RNG(engine.getSeedManager().getCarve()); - this.baseDensity = profile.getBaseDensityStyle().create(baseRng.nextParallelRNG(934_447), data); - this.detailDensity = profile.getDetailDensityStyle().create(baseRng.nextParallelRNG(612_991), data); - this.warpDensity = profile.getWarpStyle().create(baseRng.nextParallelRNG(770_713), data); + this.baseDensity = profile.getBaseDensityStyle().create(baseRng.nextParallelRNG(934_447), runtime); + this.detailDensity = profile.getDetailDensityStyle().create(baseRng.nextParallelRNG(612_991), runtime); + this.warpDensity = profile.getWarpStyle().create(baseRng.nextParallelRNG(770_713), runtime); IrisStyledRange threshold = profile.getDensityThreshold(); thresholdMin = threshold.getMin(); thresholdMax = threshold.getMax(); thresholdHasNoise = thresholdMin != thresholdMax && !threshold.getStyle().isFlat(); - thresholdDensity = thresholdHasNoise ? threshold.getStyle().create(baseRng.nextParallelRNG(489_112), data) : null; + thresholdDensity = thresholdHasNoise ? threshold.getStyle().create(baseRng.nextParallelRNG(489_112), runtime) : null; constantThreshold = thresholdMin == thresholdMax ? thresholdMin : M.lerp(thresholdMin, thresholdMax, 0.5D); this.baseWeight = profile.getBaseWeight(); this.detailWeight = profile.getDetailWeight(); @@ -73,7 +73,7 @@ public final class IrisCaveProfileSampler { double weight = Math.abs(baseWeight) + Math.abs(detailWeight); int index = 0; for (IrisCaveFieldModule module : profile.getModules()) { - CNG moduleDensity = module.getStyle().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), data); + CNG moduleDensity = module.getStyle().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), runtime); ModuleState state = new ModuleState(module, moduleDensity); moduleStates.add(state); weight += Math.abs(state.weight); diff --git a/core/src/main/java/art/arcane/iris/generation/decoration/DecoratorCore.java b/core/src/main/java/art/arcane/iris/generation/decoration/DecoratorCore.java index e517ee561..6864ca242 100644 --- a/core/src/main/java/art/arcane/iris/generation/decoration/DecoratorCore.java +++ b/core/src/main/java/art/arcane/iris/generation/decoration/DecoratorCore.java @@ -18,6 +18,7 @@ package art.arcane.iris.generation.decoration; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.runtime.GenerationFailures; import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.generation.mantle.EngineMantle; @@ -46,6 +47,7 @@ final class DecoratorCore { private static volatile NativeBlockState twistingVines; private static volatile NativeBlockState twistingVinesPlant; + /** Per-thread placement options; callers clear the mantle reference once a placement returns. */ static final ThreadLocal SCRATCH_OPTS = ThreadLocal.withInitial(PlaceOpts::new); @@ -92,25 +94,27 @@ final class DecoratorCore { } static IrisDecorator pickDecorator(IrisBiome biome, IrisDecorationPart part, RNG gRNG, - RNG colRng, IrisData data, double realX, double realZ) { + RNG colRng, PackRuntime runtime, double realX, double realZ) { IrisDecorator[] bucket = biome.getDecoratorBucket(part); if (bucket.length == 0) { return null; } + DecoratorRuntime[] decoratorRuntimes = runtime.biome(biome).decorators(part); IrisDecorator picked = null; int count = 0; - for (IrisDecorator d : bucket) { + for (int index = 0; index < bucket.length; index++) { + IrisDecorator d = bucket[index]; try { - if (d.passesChanceGate(gRNG, realX, realZ, data)) { + if (d.passesChanceGate(gRNG, realX, realZ, decoratorRuntimes[index])) { count++; if (count == 1 || colRng.nextInt(count) == 0) { picked = d; } } } catch (Throwable e) { - skip(e, d, data, (int) realX, -1, (int) realZ, biome); + skip(e, d, runtime.data(), (int) realX, -1, (int) realZ, biome); } } @@ -119,14 +123,14 @@ final class DecoratorCore { static void placeSurfaceSingle(IrisDecorator decorator, int x, int z, int realX, int height, int realZ, - Hunk data, RNG rng, IrisData irisData, + Hunk data, RNG rng, PackRuntime runtime, boolean underwater, boolean caveSkipFluid, EngineMantle mantle) { if (height < 0 || height >= data.getHeight()) { return; } NativeBlockState bdx = data.get(x, height, z); - NativeBlockState bd = decorator.pickBlockData(rng, irisData, realX, realZ); + NativeBlockState bd = decorator.pickBlockData(rng, runtime, realX, realZ); if (!IrisSpeleothems.isSpike(bd) && !underwater && !canGoOn(bd, bdx) && !decorator.isForcePlace() && decorator.getForceBlock() == null) { @@ -138,14 +142,14 @@ final class DecoratorCore { return; } data.set(x, height, z, fixFacesForHunk( - decorator.getForceBlock().getBlockData(irisData), data, x, z, realX, height, realZ, mantle)); + decorator.getForceBlock().getBlockData(runtime.data()), data, x, z, realX, height, realZ, mantle)); } if (!decorator.isForcePlace()) { - if (decorator.getWhitelist() != null && !matchesPalette(decorator.getWhitelistArray(irisData), bdx)) { + if (decorator.getWhitelist() != null && !matchesPalette(decorator.getWhitelistArray(runtime.data()), bdx)) { return; } - if (decorator.getBlacklist() != null && matchesPalette(decorator.getBlacklistArray(irisData), bdx)) { + if (decorator.getBlacklist() != null && matchesPalette(decorator.getBlacklistArray(runtime.data()), bdx)) { return; } } @@ -176,7 +180,7 @@ final class DecoratorCore { data.set(x, lowerY, z, lower); data.set(x, upperY, z, IrisProceduralBlocks.normalizeWaterlogging(upper, data.get(x, upperY, z), true)); } catch (Throwable e) { - skip(e, decorator, irisData, realX, lowerY, realZ, null); + skip(e, decorator, runtime.data(), realX, lowerY, realZ, null); } return; } @@ -202,8 +206,8 @@ final class DecoratorCore { static void placeSingleAt(IrisDecorator decorator, int x, int z, int realX, int height, int realZ, Hunk data, - RNG rng, IrisData irisData, boolean applyFixFaces, EngineMantle mantle) { - NativeBlockState bd = decorator.pickBlockData(rng, irisData, realX, realZ); + RNG rng, PackRuntime runtime, boolean applyFixFaces, EngineMantle mantle) { + NativeBlockState bd = decorator.pickBlockData(rng, runtime, realX, realZ); if (bd == null) { return; } @@ -212,7 +216,7 @@ final class DecoratorCore { return; } if (IrisSpeleothems.isSpike(bd)) { - if (height + 1 < data.getHeight() && allowsSurface(decorator, data.get(x, height + 1, z), irisData)) { + if (height + 1 < data.getHeight() && allowsSurface(decorator, data.get(x, height + 1, z), runtime.data())) { placeSingleSpike(bd, data, x, z, height, false, false); } return; @@ -225,17 +229,17 @@ final class DecoratorCore { static void placeStackUp(IrisDecorator decorator, int x, int z, int realX, int realZ, int height, int max, Hunk data, - RNG rng, IrisData irisData, PlaceOpts opts) { + RNG rng, PackRuntime runtime, PlaceOpts opts) { if (height < 0 || height >= data.getHeight()) { return; } NativeBlockState support = data.get(x, height, z); - if (!allowsSurface(decorator, support, irisData)) { + if (!allowsSurface(decorator, support, runtime.data())) { return; } int effectiveMax = opts.underwater ? Math.min(max, opts.fluidHeight - height) : max; - int stack = computeStack(decorator, rng, realX, realZ, irisData, effectiveMax); + int stack = computeStack(decorator, rng, realX, realZ, runtime, effectiveMax); int placed = 0; boolean hasSpikes = false; NativeBlockState sampledBlock = null; @@ -254,8 +258,8 @@ final class DecoratorCore { boolean top = threshold >= decorator.getTopThreshold(); if (sampledBlock == null || top != sampledTop) { sampledBlock = top - ? decorator.pickBlockDataTop(rng, irisData, realX, realZ) - : decorator.pickBlockData(rng, irisData, realX, realZ); + ? decorator.pickBlockDataTop(rng, runtime, realX, realZ) + : decorator.pickBlockData(rng, runtime, realX, realZ); sampledTop = top; } NativeBlockState block = sampledBlock; @@ -288,15 +292,15 @@ final class DecoratorCore { static void placeStackDown(IrisDecorator decorator, int x, int z, int realX, int realZ, int height, int minHeight, Hunk data, - RNG rng, IrisData irisData, int max, PlaceOpts opts, EngineMantle mantle) { + RNG rng, PackRuntime runtime, int max, PlaceOpts opts, EngineMantle mantle) { if (height < 0 || height >= data.getHeight()) { return; } NativeBlockState support = height + 1 < data.getHeight() ? data.get(x, height + 1, z) : null; - if (!allowsSurface(decorator, support, irisData)) { + if (!allowsSurface(decorator, support, runtime.data())) { return; } - int stack = computeStack(decorator, rng, realX, realZ, irisData, max); + int stack = computeStack(decorator, rng, realX, realZ, runtime, max); int placed = 0; boolean hasSpikes = false; NativeBlockState sampledBlock = null; @@ -315,8 +319,8 @@ final class DecoratorCore { boolean top = threshold >= decorator.getTopThreshold(); if (sampledBlock == null || top != sampledTop) { sampledBlock = top - ? decorator.pickBlockDataTop(rng, irisData, realX, realZ) - : decorator.pickBlockData(rng, irisData, realX, realZ); + ? decorator.pickBlockDataTop(rng, runtime, realX, realZ) + : decorator.pickBlockData(rng, runtime, realX, realZ); sampledTop = top; } NativeBlockState block = sampledBlock; @@ -349,11 +353,11 @@ final class DecoratorCore { static void placeFloatingSimple(IrisDecorator decorator, int xf, int zf, int realX, int realZ, int height, int max, Hunk data, - RNG rng, IrisData irisData, EngineMantle mantle) { + RNG rng, PackRuntime runtime, EngineMantle mantle) { if (!hasFloatingSurface(data, xf, height, zf)) { return; } - NativeBlockState bd = decorator.pickBlockData(rng, irisData, realX, realZ); + NativeBlockState bd = decorator.pickBlockData(rng, runtime, realX, realZ); if (bd == null) { return; } @@ -363,7 +367,7 @@ final class DecoratorCore { } if (IrisSpeleothems.isSpike(bd)) { - if (max > 1 && allowsSurface(decorator, data.get(xf, height, zf), irisData)) { + if (max > 1 && allowsSurface(decorator, data.get(xf, height, zf), runtime.data())) { placeSingleSpike(bd, data, xf, zf, height + 1, true, false); } return; @@ -383,7 +387,7 @@ final class DecoratorCore { data.set(xf, lowerY, zf, IrisProceduralBlocks.normalizeWaterlogging(lower, data.get(xf, lowerY, zf), true)); data.set(xf, upperY, zf, IrisProceduralBlocks.normalizeWaterlogging(upper, data.get(xf, upperY, zf), true)); } catch (Throwable e) { - skip(e, decorator, irisData, realX, lowerY, realZ, null); + skip(e, decorator, runtime.data(), realX, lowerY, realZ, null); } return; } @@ -396,11 +400,11 @@ final class DecoratorCore { static int placeFloatingStacked(IrisDecorator decorator, int xf, int zf, int realX, int realZ, int height, int max, Hunk data, - RNG rng, IrisData irisData, EngineMantle mantle) { + RNG rng, PackRuntime runtime, EngineMantle mantle) { if (!hasFloatingSurface(data, xf, height, zf)) { return 0; } - int stack = decorator.getHeight(rng, realX, realZ, irisData); + int stack = decorator.getHeight(rng, realX, realZ, runtime); if (decorator.isScaleStack()) { stack = Math.min((int) Math.ceil((double) max * ((double) stack / 100)), decorator.getAbsoluteMaxStack()); } else { @@ -420,8 +424,8 @@ final class DecoratorCore { boolean top = threshold >= decorator.getTopThreshold(); if (sampledBlock == null || top != sampledTop) { sampledBlock = top - ? decorator.pickBlockDataTop(rng, irisData, realX, realZ) - : decorator.pickBlockData(rng, irisData, realX, realZ); + ? decorator.pickBlockDataTop(rng, runtime, realX, realZ) + : decorator.pickBlockData(rng, runtime, realX, realZ); sampledTop = top; } NativeBlockState bd = sampledBlock; @@ -433,7 +437,7 @@ final class DecoratorCore { break; } if (IrisSpeleothems.isSpike(bd)) { - if (!allowsSurface(decorator, data.get(xf, height, zf), irisData) + if (!allowsSurface(decorator, data.get(xf, height, zf), runtime.data()) || !IrisSpeleothems.canPlace(bd, data, xf, zf, h, true, false)) { break; } @@ -581,8 +585,8 @@ final class DecoratorCore { } static int computeStack(IrisDecorator decorator, RNG rng, double realX, double realZ, - IrisData irisData, int max) { - int stack = decorator.getHeight(rng, realX, realZ, irisData); + PackRuntime runtime, int max) { + int stack = decorator.getHeight(rng, realX, realZ, runtime); if (decorator.isScaleStack()) { stack = Math.min((int) Math.ceil((double) max * ((double) stack / 100)), decorator.getAbsoluteMaxStack()); } else { diff --git a/core/src/main/java/art/arcane/iris/generation/decoration/DecoratorRuntime.java b/core/src/main/java/art/arcane/iris/generation/decoration/DecoratorRuntime.java new file mode 100644 index 000000000..87af5b68f --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/decoration/DecoratorRuntime.java @@ -0,0 +1,57 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.generation.decoration; + +import art.arcane.iris.generation.runtime.PackRuntime; +import art.arcane.iris.generation.runtime.SeedTable; +import art.arcane.volmlib.util.noise.CNG; + +/** What one engine derives from an {@link IrisDecorator}: the stack, placement and variance generators of each seed. */ +public final class DecoratorRuntime { + private static final int SEED_CAPACITY = 32; + + private final PackRuntime runtime; + private final SeedTable heightGenerators; + private final SeedTable layerGenerators; + private final SeedTable varianceGenerators; + + public DecoratorRuntime(IrisDecorator decorator, PackRuntime runtime) { + this.runtime = runtime; + this.heightGenerators = new SeedTable<>(SEED_CAPACITY, seed -> decorator.createHeightGenerator(seed, runtime)); + this.layerGenerators = new SeedTable<>(SEED_CAPACITY, seed -> decorator.createLayerGenerator(seed, runtime)); + this.varianceGenerators = new SeedTable<>(SEED_CAPACITY, seed -> decorator.createVarianceGenerator(seed, runtime)); + } + + /** The scope this runtime was built in, whose pack data resolves the decorator's palettes. */ + public PackRuntime packRuntime() { + return runtime; + } + + public CNG heightGenerator(long seed) { + return heightGenerators.get(seed); + } + + public CNG layerGenerator(long seed) { + return layerGenerators.get(seed); + } + + public CNG varianceGenerator(long seed) { + return varianceGenerators.get(seed); + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/decoration/DepositRuntime.java b/core/src/main/java/art/arcane/iris/generation/decoration/DepositRuntime.java new file mode 100644 index 000000000..aa5617cf1 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/decoration/DepositRuntime.java @@ -0,0 +1,75 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.generation.decoration; + +import art.arcane.iris.generation.runtime.PackRuntime; +import art.arcane.iris.generation.runtime.SeedTable; +import art.arcane.iris.structure.object.IrisObject; +import art.arcane.volmlib.util.collection.KList; + +/** + * What one engine derives from an {@link IrisDepositGenerator}: the clump variants of the engine's deposit seed, at + * the configured size and at each scaled size the deposit modifier asks for. + */ +public final class DepositRuntime { + private static final int SCALED_SIZE_CAPACITY = 64; + + private final IrisDepositGenerator deposit; + private final PackRuntime runtime; + private final long depositSeed; + private final SeedTable> scaledClumps; + private volatile KList clumps; + + public DepositRuntime(IrisDepositGenerator deposit, PackRuntime runtime) { + this.deposit = deposit; + this.runtime = runtime; + this.depositSeed = runtime.engine().getSeedManager().getDeposit(); + this.scaledClumps = new SeedTable<>(SCALED_SIZE_CAPACITY, sizes -> deposit.createScaledClumps( + depositSeed, minSize(sizes), maxSize(sizes), runtime.data())); + } + + public KList clumps() { + KList built = clumps; + if (built != null) { + return built; + } + synchronized (this) { + if (clumps == null) { + clumps = deposit.createClumps(depositSeed, runtime.data()); + } + return clumps; + } + } + + public KList scaledClumps(int minSize, int maxSize) { + return scaledClumps.get(sizeKey(minSize, maxSize)); + } + + private static long sizeKey(int minSize, int maxSize) { + return ((long) minSize << 32) | (maxSize & 0xffffffffL); + } + + private static int minSize(long sizeKey) { + return (int) (sizeKey >>> 32); + } + + private static int maxSize(long sizeKey) { + return (int) sizeKey; + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/decoration/FloatingDecorator.java b/core/src/main/java/art/arcane/iris/generation/decoration/FloatingDecorator.java index 5aec93b86..f01a0f803 100644 --- a/core/src/main/java/art/arcane/iris/generation/decoration/FloatingDecorator.java +++ b/core/src/main/java/art/arcane/iris/generation/decoration/FloatingDecorator.java @@ -18,6 +18,7 @@ package art.arcane.iris.generation.decoration; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.volmlib.util.hunk.Hunk; @@ -36,7 +37,8 @@ public class FloatingDecorator { int height, int max, Hunk data, RNG rng, Runnable candidatesNullCallback) { RNG gRNG = new RNG(DecoratorCore.partSeed(engine.getSeedManager().getComponent(), part)); - IrisDecorator decorator = DecoratorCore.pickDecorator(target, part, gRNG, rng, engine.getData(), realX, realZ); + PackRuntime runtime = PackRuntime.of(engine); + IrisDecorator decorator = DecoratorCore.pickDecorator(target, part, gRNG, rng, runtime, realX, realZ); if (decorator == null) { candidatesNullCallback.run(); @@ -45,11 +47,11 @@ public class FloatingDecorator { if (!decorator.isStacking()) { DecoratorCore.placeFloatingSimple(decorator, xf, zf, realX, realZ, height, max, data, - gRNG, engine.getData(), engine.getMantle()); + gRNG, runtime, engine.getMantle()); return max > 1 ? 1 : 0; } return DecoratorCore.placeFloatingStacked(decorator, xf, zf, realX, realZ, height, max, data, - gRNG, engine.getData(), engine.getMantle()); + gRNG, runtime, engine.getMantle()); } } diff --git a/core/src/main/java/art/arcane/iris/generation/decoration/HydrologyVegetation.java b/core/src/main/java/art/arcane/iris/generation/decoration/HydrologyVegetation.java index 132b45718..60d8b2985 100644 --- a/core/src/main/java/art/arcane/iris/generation/decoration/HydrologyVegetation.java +++ b/core/src/main/java/art/arcane/iris/generation/decoration/HydrologyVegetation.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.decoration; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.block.B; import art.arcane.iris.generation.block.IrisBlockData; import art.arcane.iris.generation.hydrology.plan.HydrologySettings; @@ -32,7 +33,7 @@ public final class HydrologyVegetation { this.shoreRng = new RNG(DecoratorCore.partSeed(this.seed, IrisDecorationPart.SHORE_LINE)); } - public void decorate(Hunk output, int localX, int localZ, int x, int z, WaterRole role, Water water, IrisData data) { + public void decorate(Hunk output, int localX, int localZ, int x, int z, WaterRole role, Water water, PackRuntime runtime) { Placement placement = placement(role); if (placement == Placement.NONE) { return; @@ -45,7 +46,7 @@ public final class HydrologyVegetation { if (ground < 0 || ground + 1 >= output.getHeight()) { return; } - Column column = new Column(output, localX, localZ, x, z, ground, water, data); + Column column = new Column(output, localX, localZ, x, z, ground, water, runtime); if (placement == Placement.SHORE) { decorateShore(column, decorators.shore); return; @@ -112,7 +113,7 @@ public final class HydrologyVegetation { int count = 0; for (IrisDecorator decorator : bucket) { try { - if (!decorator.passesChanceGate(partRng, column.x, column.z, column.data)) { + if (!decorator.passesChanceGate(partRng, column.x, column.z, column.runtime)) { continue; } } catch (Throwable e) { @@ -213,9 +214,10 @@ public final class HydrologyVegetation { private final int z; private final int ground; private final Water water; + private final PackRuntime runtime; private final IrisData data; - private Column(Hunk output, int localX, int localZ, int x, int z, int ground, Water water, IrisData data) { + private Column(Hunk output, int localX, int localZ, int x, int z, int ground, Water water, PackRuntime runtime) { this.output = output; this.localX = localX; this.localZ = localZ; @@ -223,7 +225,8 @@ public final class HydrologyVegetation { this.z = z; this.ground = ground; this.water = water; - this.data = data; + this.runtime = runtime; + this.data = runtime.data(); } private boolean accepts(IrisDecorator decorator, NativeBlockState support) { @@ -231,7 +234,7 @@ public final class HydrologyVegetation { } private int stack(IrisDecorator decorator, RNG rng, int room) { - return decorator.isStacking() ? Math.min(room, DecoratorCore.computeStack(decorator, rng, x, z, data, room)) : 1; + return decorator.isStacking() ? Math.min(room, DecoratorCore.computeStack(decorator, rng, x, z, runtime, room)) : 1; } private void place(IrisDecorator decorator, RNG rng, int baseY, int room, Slot slot, NativeBlockState support) { @@ -243,7 +246,7 @@ public final class HydrologyVegetation { } private void placePicked(IrisDecorator decorator, RNG rng, int baseY, int room, Slot slot, NativeBlockState support) { - NativeBlockState first = decorator.pickBlockData(rng, data, x, z); + NativeBlockState first = decorator.pickBlockData(rng, runtime, x, z); if (first == null) { return; } @@ -260,7 +263,7 @@ public final class HydrologyVegetation { int y = baseY + index; boolean top = (stack == 1 ? 1D : (double) index / (stack - 1)) >= decorator.getTopThreshold(); if (top != sampledTop) { - sampled = top ? decorator.pickBlockDataTop(rng, data, x, z) : decorator.pickBlockData(rng, data, x, z); + sampled = top ? decorator.pickBlockDataTop(rng, runtime, x, z) : decorator.pickBlockData(rng, runtime, x, z); sampledTop = top; } NativeBlockState block = sampled == null ? null : fit(sampled, y, slot, decorator, index == 0 ? support : null); diff --git a/core/src/main/java/art/arcane/iris/generation/decoration/IrisCeilingDecorator.java b/core/src/main/java/art/arcane/iris/generation/decoration/IrisCeilingDecorator.java index 8ff2c645f..acc65c562 100644 --- a/core/src/main/java/art/arcane/iris/generation/decoration/IrisCeilingDecorator.java +++ b/core/src/main/java/art/arcane/iris/generation/decoration/IrisCeilingDecorator.java @@ -18,6 +18,7 @@ package art.arcane.iris.generation.decoration; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.terrain.InferredType; import art.arcane.iris.generation.biome.IrisBiome; @@ -47,21 +48,22 @@ public class IrisCeilingDecorator extends IrisEngineDecorator { Hunk data, IrisBiome biome, InferredType inferredType, int height, int max) { boolean caveSkipFluid = IrisSurfaceDecorator.skipsFluid(inferredType); RNG rng = getRNG(realX, realZ); - IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ); + PackRuntime runtime = PackRuntime.of(getEngine(), getData()); + IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, runtime, realX, realZ); if (decorator == null) { return; } try { - place(decorator, x, z, realX, realZ, data, height, max, caveSkipFluid); + place(decorator, x, z, realX, realZ, data, height, max, caveSkipFluid, runtime); } catch (Throwable e) { DecoratorCore.skip(e, decorator, getData(), realX, height, realZ, biome); } } private void place(IrisDecorator decorator, int x, int z, int realX, int realZ, Hunk data, - int height, int max, boolean caveSkipFluid) { + int height, int max, boolean caveSkipFluid, PackRuntime runtime) { if (!decorator.isStacking()) { if (caveSkipFluid) { NativeBlockState state = data.get(x, height, z); @@ -69,13 +71,13 @@ public class IrisCeilingDecorator extends IrisEngineDecorator { return; } } - DecoratorCore.placeSingleAt(decorator, x, z, realX, height, realZ, data, partRNG, getData(), true, getEngine().getMantle()); + DecoratorCore.placeSingleAt(decorator, x, z, realX, height, realZ, data, partRNG, runtime, true, getEngine().getMantle()); return; } DecoratorCore.PlaceOpts opts = DecoratorCore.SCRATCH_OPTS.get(); opts.reset(); opts.caveSkipFluid = caveSkipFluid; - DecoratorCore.placeStackDown(decorator, x, z, realX, realZ, height, 0, data, partRNG, getData(), max, opts, getEngine().getMantle()); + DecoratorCore.placeStackDown(decorator, x, z, realX, realZ, height, 0, data, partRNG, runtime, max, opts, getEngine().getMantle()); } } diff --git a/core/src/main/java/art/arcane/iris/generation/decoration/IrisDecorator.java b/core/src/main/java/art/arcane/iris/generation/decoration/IrisDecorator.java index 44f4da55e..70574f844 100644 --- a/core/src/main/java/art/arcane/iris/generation/decoration/IrisDecorator.java +++ b/core/src/main/java/art/arcane/iris/generation/decoration/IrisDecorator.java @@ -18,9 +18,9 @@ package art.arcane.iris.generation.decoration; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.generation.cache.LazyBoundedCache; import art.arcane.iris.generation.block.IrisBlockData; import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.NoiseStyle; @@ -52,8 +52,6 @@ import lombok.experimental.Accessors; @Description("A biome decorator is used for placing flowers, grass, cacti and so on") @Data public class IrisDecorator { - private final transient LazyBoundedCache generators = new LazyBoundedCache<>(32); - private transient volatile Generators recentGenerators; private final transient AtomicCache> blockData = new AtomicCache<>(); private final transient AtomicCache> blockDataTops = new AtomicCache<>(); private final transient AtomicCache blockDataArray = new AtomicCache<>(); @@ -118,50 +116,39 @@ public class IrisDecorator { @Description("When the stack passes the top threshold, the top palette will start being used instead of the normal palette.") private double topThreshold = 1.0; - public int getHeight(RNG rng, double x, double z, IrisData data) { + public int getHeight(RNG rng, double x, double z, PackRuntime runtime) { if (stackMin == stackMax) { return stackMin; } - return getHeightGenerator(rng, data) + return getHeightGenerator(rng, runtime) .fit(stackMin, stackMax, x / heightVariance.getZoom(), z / heightVariance.getZoom()); } - public CNG getHeightGenerator(RNG rng, IrisData data) { - AtomicCache cache = generators(rng, data).height; - CNG cached = cache.getIfPresent(); - return cached != null ? cached : cache.aquire(() -> - heightVariance.create(rng.nextParallelRNG(getBlockData(data).size() + stackMax + stackMin), data)); + public CNG getHeightGenerator(RNG rng, PackRuntime runtime) { + return runtime.decorator(this).heightGenerator(rng.getSeed()); } - public CNG getGenerator(RNG rng, IrisData data) { - AtomicCache cache = generators(rng, data).layer; - CNG cached = cache.getIfPresent(); - return cached != null ? cached : cache.aquire(() -> style.create(rng.nextParallelRNG(getBlockData(data).size()), data)); + public CNG getGenerator(RNG rng, PackRuntime runtime) { + return runtime.decorator(this).layerGenerator(rng.getSeed()); } - public CNG getVarianceGenerator(RNG rng, IrisData data) { - AtomicCache cache = generators(rng, data).variance; - CNG cached = cache.getIfPresent(); - return cached != null ? cached : cache.aquire(() -> createVarianceGenerator(rng, data)); + public CNG getVarianceGenerator(RNG rng, PackRuntime runtime) { + return runtime.decorator(this).varianceGenerator(rng.getSeed()); } - private Generators generators(RNG rng, IrisData data) { - long seed = rng.getSeed(); - Engine engine = data == null ? null : data.getEngine(); - Generators recent = recentGenerators; - if (recent != null && recent.key.seed == seed && recent.key.data == data && recent.key.engine == engine) { - return recent; - } - Generators selected = generators.computeIfAbsent(new GeneratorKey(seed, data, engine), Generators::new); - recentGenerators = selected; - return selected; + public CNG createHeightGenerator(long seed, PackRuntime runtime) { + return heightVariance.create(new RNG(seed).nextParallelRNG(getBlockData(runtime.data()).size() + stackMax + stackMin), runtime); } - private CNG createVarianceGenerator(RNG rng, IrisData data) { - return variance.createNoCache(deriveVarianceSeed(rng, data), data).scale(1D / variance.getZoom()); + public CNG createLayerGenerator(long seed, PackRuntime runtime) { + return style.create(new RNG(seed).nextParallelRNG(getBlockData(runtime.data()).size()), runtime); + } + + public CNG createVarianceGenerator(long seed, PackRuntime runtime) { + return variance.createNoCache(deriveVarianceSeed(new RNG(seed), runtime.data()), runtime).scale(1D / variance.getZoom()); } RNG deriveVarianceSeed(RNG rng, IrisData data) { @@ -173,27 +160,32 @@ public class IrisDecorator { return palette; } - public boolean passesChanceGate(RNG rng, double x, double z, IrisData data) { - if (getBlockData(data).isEmpty()) { + public boolean passesChanceGate(RNG rng, double x, double z, PackRuntime runtime) { + return passesChanceGate(rng, x, z, runtime.decorator(this)); + } + + /** {@link #passesChanceGate(RNG, double, double, PackRuntime)} for a caller that already holds this decorator's runtime. */ + public boolean passesChanceGate(RNG rng, double x, double z, DecoratorRuntime decoratorRuntime) { + if (getBlockData(decoratorRuntime.packRuntime().data()).isEmpty()) { return false; } double xx = x / style.getZoom(); double zz = z / style.getZoom(); - return getGenerator(rng, data).fitDouble(0D, 1D, xx, zz) <= chance; + return decoratorRuntime.layerGenerator(rng.getSeed()).fitDouble(0D, 1D, xx, zz) <= chance; } - public NativeBlockState getBlockData(IrisBiome b, RNG rng, double x, double z, IrisData data) { - if (!passesChanceGate(rng, x, z, data)) { + public NativeBlockState getBlockData(IrisBiome b, RNG rng, double x, double z, PackRuntime runtime) { + if (!passesChanceGate(rng, x, z, runtime)) { return null; } - if (getBlockData(data).size() == 1) { - return getBlockData(data).get(0); + if (getBlockData(runtime.data()).size() == 1) { + return getBlockData(runtime.data()).get(0); } - return getVarianceGenerator(rng, data).fit(getBlockData(data), z, x); + return getVarianceGenerator(rng, runtime).fit(getBlockData(runtime.data()), z, x); } - public NativeBlockState getBlockData100(IrisBiome b, RNG rng, double x, double y, double z, IrisData data) { - KList palette = getBlockData(data); + public NativeBlockState getBlockData100(IrisBiome b, RNG rng, double x, double y, double z, PackRuntime runtime) { + KList palette = getBlockData(runtime.data()); if (palette.isEmpty()) { IrisLogging.warnOnce("decorator-empty:" + b.getName(), "Empty Block Data for " + b.getName()); return null; @@ -203,24 +195,24 @@ public class IrisDecorator { return palette.get(0); } - return getVarianceGenerator(rng, data).fit(palette, z, y, x); //X and Z must be switched + return getVarianceGenerator(rng, runtime).fit(palette, z, y, x); //X and Z must be switched } - public NativeBlockState getBlockDataForTop(IrisBiome b, RNG rng, double x, double y, double z, IrisData data) { - KList topPalette = getBlockDataTops(data); + public NativeBlockState getBlockDataForTop(IrisBiome b, RNG rng, double x, double y, double z, PackRuntime runtime) { + KList topPalette = getBlockDataTops(runtime.data()); if (topPalette.isEmpty()) { - return getBlockData100(b, rng, x, y, z, data); + return getBlockData100(b, rng, x, y, z, runtime); } double xx = x / style.getZoom(); double zz = z / style.getZoom(); - if (getGenerator(rng, data).fitDouble(0D, 1D, xx, zz) <= chance) { //Exclude y from here + if (getGenerator(rng, runtime).fitDouble(0D, 1D, xx, zz) <= chance) { //Exclude y from here if (topPalette.size() == 1) { return topPalette.get(0); } - return getVarianceGenerator(rng, data).fit(topPalette, z, y, x); //X and Z must be switched + return getVarianceGenerator(rng, runtime).fit(topPalette, z, y, x); //X and Z must be switched } return null; @@ -336,55 +328,30 @@ public class IrisDecorator { return resolved; } - public NativeBlockState pickBlockData(RNG rng, IrisData data, double x, double z) { - NativeBlockState[] arr = getBlockDataArray(data); + public NativeBlockState pickBlockData(RNG rng, PackRuntime runtime, double x, double z) { + NativeBlockState[] arr = getBlockDataArray(runtime.data()); if (arr.length == 0) { return null; } if (arr.length == 1) { return arr[0]; } - return arr[Math.abs((int) getVarianceGenerator(rng, data).fit(0, arr.length - 1, z, x))]; + return arr[Math.abs((int) getVarianceGenerator(rng, runtime).fit(0, arr.length - 1, z, x))]; } - public NativeBlockState pickBlockDataTop(RNG rng, IrisData data, double x, double z) { - NativeBlockState[] arr = getBlockDataTopsArray(data); + public NativeBlockState pickBlockDataTop(RNG rng, PackRuntime runtime, double x, double z) { + NativeBlockState[] arr = getBlockDataTopsArray(runtime.data()); if (arr.length == 0) { - return pickBlockData(rng, data, x, z); + return pickBlockData(rng, runtime, x, z); } if (arr.length == 1) { return arr[0]; } - return arr[Math.abs((int) getVarianceGenerator(rng, data).fit(0, arr.length - 1, z, x))]; + return arr[Math.abs((int) getVarianceGenerator(rng, runtime).fit(0, arr.length - 1, z, x))]; } @SuppressWarnings("BooleanMethodIsAlwaysInverted") public boolean isStacking() { return getStackMax() > 1; } - - private static final class Generators { - private final GeneratorKey key; - private final AtomicCache layer = new AtomicCache<>(); - private final AtomicCache variance = new AtomicCache<>(); - private final AtomicCache height = new AtomicCache<>(); - - private Generators(GeneratorKey key) { - this.key = key; - } - } - - private record GeneratorKey(long seed, IrisData data, Engine engine) { - @Override - public boolean equals(Object other) { - return other instanceof GeneratorKey key - && seed == key.seed && data == key.data && engine == key.engine; - } - - @Override - public int hashCode() { - return 31 * (31 * Long.hashCode(seed) + System.identityHashCode(data)) - + System.identityHashCode(engine); - } - } } diff --git a/core/src/main/java/art/arcane/iris/generation/decoration/IrisDepositGenerator.java b/core/src/main/java/art/arcane/iris/generation/decoration/IrisDepositGenerator.java index bb1d8b36d..7de669077 100644 --- a/core/src/main/java/art/arcane/iris/generation/decoration/IrisDepositGenerator.java +++ b/core/src/main/java/art/arcane/iris/generation/decoration/IrisDepositGenerator.java @@ -18,6 +18,7 @@ package art.arcane.iris.generation.decoration; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.block.IrisBlockData; import art.arcane.iris.structure.object.IrisObject; @@ -62,12 +63,10 @@ public class IrisDepositGenerator { private static final long FNV_OFFSET_BASIS = 0xcbf29ce484222325L; private static final long FNV_PRIME = 0x100000001b3L; - private final transient ConcurrentMap> objects = new ConcurrentHashMap<>(); private final transient AtomicCache> blockData = new AtomicCache<>(); private final transient AtomicCache ore = new AtomicCache<>(); private final transient AtomicCache> replaceableBlockData = new AtomicCache<>(); private final transient AtomicCache> surfaceReplaceableBlockData = new AtomicCache<>(); - private final transient ConcurrentMap> scaledObjects = new ConcurrentHashMap<>(); @Required @MinNumber(-8192) @MaxNumber(8192) @@ -145,54 +144,47 @@ public class IrisDepositGenerator { @Description("If set to true, this deposit will replace bedrock") private boolean replaceBedrock = false; - public IrisObject getClump(Engine engine, RNG rng, IrisData rdata) { + public IrisObject getClump(PackRuntime runtime, RNG rng) { if (shape != IrisDepositShape.IRIS) { - return generateConfiguredClumpObject(rng, rdata, minSize, maxSize); + return generateConfiguredClumpObject(rng, runtime.data(), minSize, maxSize); } - ClumpCacheKey cacheKey = new ClumpCacheKey(engine.getSeedManager().getDeposit(), minSize, maxSize); - KList objects = this.objects.computeIfAbsent(cacheKey, key -> { - RNG rngv = new RNG(key.depositSeed() + stableClumpSalt(rdata)); - KList objectsf = new KList<>(); - - for (int i = 0; i < varience; i++) { - objectsf.add(generateClumpObject( - rngv.nextParallelRNG(2349 * i + 3598), rdata, key.minSize(), key.maxSize())); - } - - return objectsf; - }); + KList objects = runtime.deposit(this).clumps(); return objects.get(rng.i(0, objects.size())); } - public IrisObject getClump(Engine engine, RNG rng, IrisData rdata, double sizeMultiplier) { + public IrisObject getClump(PackRuntime runtime, RNG rng, double sizeMultiplier) { if (sizeMultiplier == 1D) { - return getClump(engine, rng, rdata); + return getClump(runtime, rng); } int scaledMinSize = scaledDepositSize(minSize, sizeMultiplier); int scaledMaxSize = scaledDepositSize(maxSize, sizeMultiplier); if (shape != IrisDepositShape.IRIS) { - return generateConfiguredClumpObject(rng, rdata, scaledMinSize, scaledMaxSize); + return generateConfiguredClumpObject(rng, runtime.data(), scaledMinSize, scaledMaxSize); } - ClumpCacheKey cacheKey = new ClumpCacheKey( - engine.getSeedManager().getDeposit(), scaledMinSize, scaledMaxSize); - KList objects = scaledObjects.computeIfAbsent(cacheKey, key -> { - long sizeSeed = ((long) key.minSize() << 32) ^ (key.maxSize() & 0xffffffffL); - RNG rngv = new RNG(key.depositSeed() + stableClumpSalt(rdata) + sizeSeed); - KList generated = new KList<>(); - - for (int i = 0; i < varience; i++) { - generated.add(generateClumpObject( - rngv.nextParallelRNG(2349 * i + 3598), rdata, key.minSize(), key.maxSize())); - } - - return generated; - }); + KList objects = runtime.deposit(this).scaledClumps(scaledMinSize, scaledMaxSize); return objects.get(rng.i(0, objects.size())); } + public KList createClumps(long depositSeed, IrisData rdata) { + return createClumpVariants(new RNG(depositSeed + stableClumpSalt(rdata)), rdata, minSize, maxSize); + } + + public KList createScaledClumps(long depositSeed, int scaledMinSize, int scaledMaxSize, IrisData rdata) { + long sizeSeed = ((long) scaledMinSize << 32) ^ (scaledMaxSize & 0xffffffffL); + return createClumpVariants(new RNG(depositSeed + stableClumpSalt(rdata) + sizeSeed), rdata, scaledMinSize, scaledMaxSize); + } + + private KList createClumpVariants(RNG rngv, IrisData rdata, int clumpMinSize, int clumpMaxSize) { + KList variants = new KList<>(); + for (int i = 0; i < varience; i++) { + variants.add(generateClumpObject(rngv.nextParallelRNG(2349 * i + 3598), rdata, clumpMinSize, clumpMaxSize)); + } + return variants; + } + public int getMaxDimension() { return Math.min(11, (int) Math.ceil(Math.cbrt(maxSize))); } @@ -279,7 +271,7 @@ public class IrisDepositGenerator { } /** - * Advances {@code rng} exactly as {@link #getClump(Engine, RNG, IrisData)} would and reports the clump's width + * Advances {@code rng} exactly as {@link #getClump(PackRuntime, RNG)} would and reports the clump's width * and lowest block offset without building it, so a caller can reject the clump first and replay the build * only for clumps it keeps. Returns null without drawing when the shape has no footprint path. */ @@ -682,9 +674,6 @@ public class IrisDepositGenerator { return false; } - record ClumpCacheKey(long depositSeed, int minSize, int maxSize) { - } - @FunctionalInterface interface CellSink { void add(int x, int y, int z); diff --git a/core/src/main/java/art/arcane/iris/generation/decoration/IrisOreBands.java b/core/src/main/java/art/arcane/iris/generation/decoration/IrisOreBands.java index 875e60ea2..5f91c6a83 100644 --- a/core/src/main/java/art/arcane/iris/generation/decoration/IrisOreBands.java +++ b/core/src/main/java/art/arcane/iris/generation/decoration/IrisOreBands.java @@ -1,7 +1,6 @@ package art.arcane.iris.generation.decoration; -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.pack.loading.IrisData; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.pack.value.IrisRange; import art.arcane.volmlib.nativelib.terrain.NativeBlockState; import art.arcane.volmlib.util.collection.KList; @@ -11,20 +10,24 @@ import java.util.Arrays; /** * One ore list (a biome's, region's or dimension's surface or underground ores) indexed by Y. Each Y - * holds the generators whose range contains it, in list order, so resolving a block tries exactly - * the generators that could place there and still returns the first one that does. + * holds the indices of the generators whose range contains it, in list order, so resolving a block tries exactly + * the generators that could place there and still returns the first one that does. The seeded chance fields live in + * an {@link OreBandsRuntime}, aligned with {@link #generators()}. */ public final class IrisOreBands { public static final IrisOreBands EMPTY = new IrisOreBands(new IrisOreGenerator[0], 0, -1, null); private static final int MAXIMUM_INDEXED_HEIGHT = 8192; private final IrisOreGenerator[] generators; + private final int[] everyGenerator; private final int minY; private final int maxY; - private final IrisOreGenerator[][] byY; + private final int[][] byY; - private IrisOreBands(IrisOreGenerator[] generators, int minY, int maxY, IrisOreGenerator[][] byY) { + private IrisOreBands(IrisOreGenerator[] generators, int minY, int maxY, int[][] byY) { this.generators = generators; + this.everyGenerator = new int[generators.length]; + Arrays.setAll(everyGenerator, index -> index); this.minY = minY; this.maxY = maxY; this.byY = byY; @@ -57,19 +60,19 @@ public final class IrisOreBands { height > MAXIMUM_INDEXED_HEIGHT ? null : index(generators, minY, (int) height)); } - private static IrisOreGenerator[][] index(IrisOreGenerator[] generators, int minY, int height) { - IrisOreGenerator[][] byY = new IrisOreGenerator[height][]; - IrisOreGenerator[] scratch = new IrisOreGenerator[generators.length]; - IrisOreGenerator[] previous = null; + private static int[][] index(IrisOreGenerator[] generators, int minY, int height) { + int[][] byY = new int[height][]; + int[] scratch = new int[generators.length]; + int[] previous = null; for (int offset = 0; offset < height; offset++) { int y = minY + offset; int count = 0; - for (IrisOreGenerator generator : generators) { - if (generator.getRange().contains(y)) { - scratch[count++] = generator; + for (int index = 0; index < generators.length; index++) { + if (generators[index].getRange().contains(y)) { + scratch[count++] = index; } } - IrisOreGenerator[] candidates = Arrays.copyOf(scratch, count); + int[] candidates = Arrays.copyOf(scratch, count); byY[offset] = previous != null && Arrays.equals(previous, candidates) ? previous : candidates; previous = byY[offset]; } @@ -92,13 +95,18 @@ public final class IrisOreBands { return y >= minY && y <= maxY; } + /** The banded generators in list order; chance fields built for them must keep this order. */ + public IrisOreGenerator[] generators() { + return generators.clone(); + } + /** * The ore placed at a Y inside {@link #contains(int)}, or null when no generator places one. */ - public NativeBlockState generate(int x, int y, int z, RNG rng, IrisData data, Engine engine) { - IrisOreGenerator[] candidates = byY == null ? generators : byY[y - minY]; - for (IrisOreGenerator candidate : candidates) { - NativeBlockState ore = candidate.generate(x, y, z, rng, data, engine); + NativeBlockState generate(int x, int y, int z, RNG rng, IrisOreGenerator.OreChance[] chances, PackRuntime runtime) { + int[] candidates = byY == null ? everyGenerator : byY[y - minY]; + for (int index : candidates) { + NativeBlockState ore = generators[index].generate(x, y, z, rng, chances[index], runtime); if (ore != null) { return ore; } diff --git a/core/src/main/java/art/arcane/iris/generation/decoration/IrisOreGenerator.java b/core/src/main/java/art/arcane/iris/generation/decoration/IrisOreGenerator.java index 3c78c4c82..f0c5b1ce6 100644 --- a/core/src/main/java/art/arcane/iris/generation/decoration/IrisOreGenerator.java +++ b/core/src/main/java/art/arcane/iris/generation/decoration/IrisOreGenerator.java @@ -18,13 +18,13 @@ package art.arcane.iris.generation.decoration; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.NoiseStyle; import art.arcane.iris.generation.terrain.IrisMaterialPalette; import art.arcane.iris.pack.value.IrisRange; import art.arcane.iris.pack.loading.IrisData; -import art.arcane.iris.generation.cache.LazyBoundedCache; import art.arcane.iris.generation.runtime.Engine; import art.arcane.volmlib.util.documentation.Description; import art.arcane.iris.pack.schema.annotation.MaxNumber; @@ -56,72 +56,46 @@ public class IrisOreGenerator { @Description("Vertical band (min, max) this ore can generate in, in engine-local Y where 0 is the bottom of the dimension, not world Y.") private IrisRange range = new IrisRange(30, 80); - private final transient LazyBoundedCache chanceCache = new LazyBoundedCache<>(32); - private transient volatile CachedChance recentChance; - - public void warm(RNG rng, IrisData data) { - chance(rng, data); - palette.getLayerGenerator(rng, data); + public void warm(RNG rng, PackRuntime runtime) { + runtime.oreChance(this, rng.getSeed()); + palette.getLayerGenerator(rng, runtime); } - public NativeBlockState generate(int x, int y, int z, RNG rng, IrisData data) { - return generate(x, y, z, rng, data, data == null ? null : data.getEngine()); - } - - public NativeBlockState generate(int x, int y, int z, RNG rng, IrisData data, Engine engine) { - if (threshold <= 0 || !range.contains(y)) { + public NativeBlockState generate(int x, int y, int z, RNG rng, PackRuntime runtime) { + if (!canPlaceAt(y)) { return null; } + return placeByChance(x, y, z, rng, runtime.oreChance(this, rng.getSeed()), runtime); + } - if (palette.getPalette().isEmpty()) { + /** Places with a chance field already resolved for {@code rng}'s seed, as {@link OreBandsRuntime} holds them. */ + public NativeBlockState generate(int x, int y, int z, RNG rng, OreChance chance, PackRuntime runtime) { + if (!canPlaceAt(y)) { return null; } + return placeByChance(x, y, z, rng, chance, runtime); + } - if (chance(rng, data, engine).sample(x, y, z) > threshold) { + private boolean canPlaceAt(int y) { + return threshold > 0 && range.contains(y) && !palette.getPalette().isEmpty(); + } + + private NativeBlockState placeByChance(int x, int y, int z, RNG rng, OreChance chance, PackRuntime runtime) { + if (chance.sample(x, y, z) > threshold) { return null; } - - return palette.get(rng, x, y, z, data); + return palette.get(rng, x, y, z, runtime); } - private OreChance chance(RNG rng, IrisData data) { - return chance(rng, data, data == null ? null : data.getEngine()); - } - - private OreChance chance(RNG rng, IrisData data, Engine engine) { - long seed = rng.getSeed(); - CachedChance recent = recentChance; - if (recent != null && recent.key.seed == seed && recent.key.data == data && recent.key.engine == engine) { - return recent.chance; - } - ChanceKey key = new ChanceKey(seed, data, engine); - OreChance selected = chanceCache.computeIfAbsent(key, ignored -> OreChance.of(chanceStyle.create(rng, data))); - recentChance = new CachedChance(key, selected); - return selected; - } - - private record ChanceKey(long seed, IrisData data, Engine engine) { - @Override - public boolean equals(Object other) { - return other instanceof ChanceKey key - && seed == key.seed && data == key.data && engine == key.engine; - } - - @Override - public int hashCode() { - return 31 * (31 * Long.hashCode(seed) + System.identityHashCode(data)) - + System.identityHashCode(engine); - } - } - - private record CachedChance(ChanceKey key, OreChance chance) { + public OreChance createChance(long seed, PackRuntime runtime) { + return OreChance.of(chanceStyle.create(new RNG(seed), runtime)); } /** * The chance field, with its single value resolved once when it is constant (a FLAT style), * which bands such as a full deepslate layer sample at every block. */ - private record OreChance(CNG noise, boolean constant, double value) { + public record OreChance(CNG noise, boolean constant, double value) { private static OreChance of(CNG noise) { boolean constant = noise.isConstant(); return new OreChance(noise, constant, constant ? noise.noise(0D, 0D, 0D) : 0D); diff --git a/core/src/main/java/art/arcane/iris/generation/decoration/IrisProceduralBlocks.java b/core/src/main/java/art/arcane/iris/generation/decoration/IrisProceduralBlocks.java index 2c0d5cc9d..d9e947beb 100644 --- a/core/src/main/java/art/arcane/iris/generation/decoration/IrisProceduralBlocks.java +++ b/core/src/main/java/art/arcane/iris/generation/decoration/IrisProceduralBlocks.java @@ -18,6 +18,7 @@ package art.arcane.iris.generation.decoration; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.terrain.IrisMaterialPalette; import art.arcane.iris.structure.object.IrisObject; @@ -59,7 +60,7 @@ public final class IrisProceduralBlocks { public static NativeBlockState resolve(String block, IrisMaterialPalette palette, IrisData data, int x, int y, int z, RNG paletteRng) { if (paletteSet(palette)) { - return palette.get(paletteRng, x, y, z, data); + return palette.get(paletteRng, x, y, z, PackRuntime.forPack(data)); } if (block != null && !block.isEmpty()) { return B.getStateOrNull(block, false); diff --git a/core/src/main/java/art/arcane/iris/generation/decoration/IrisSeaFloorDecorator.java b/core/src/main/java/art/arcane/iris/generation/decoration/IrisSeaFloorDecorator.java index 042a98b65..f4734180a 100644 --- a/core/src/main/java/art/arcane/iris/generation/decoration/IrisSeaFloorDecorator.java +++ b/core/src/main/java/art/arcane/iris/generation/decoration/IrisSeaFloorDecorator.java @@ -18,6 +18,7 @@ package art.arcane.iris.generation.decoration; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.volmlib.util.hunk.Hunk; @@ -42,27 +43,28 @@ public class IrisSeaFloorDecorator extends IrisEngineDecorator { return; } RNG rng = getRNG(realX, realZ); - IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ); + PackRuntime runtime = PackRuntime.of(getEngine(), getData()); + IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, runtime, realX, realZ); if (decorator == null) { return; } try { - place(decorator, x, z, realX, realZ, data, biome, height, max, limit); + place(decorator, x, z, realX, realZ, data, biome, height, max, limit, runtime); } catch (Throwable e) { DecoratorCore.skip(e, decorator, getData(), realX, height, realZ, biome); } } private void place(IrisDecorator decorator, int x, int z, int realX, int realZ, Hunk data, - IrisBiome biome, int height, int max, int limit) { + IrisBiome biome, int height, int max, int limit, PackRuntime runtime) { if (!decorator.isStacking()) { if (!decorator.isForcePlace() && !decorator.getSlopeCondition().isDefault() && !decorator.getSlopeCondition().isValid(getComplex().getSlopeStream().get(realX, realZ))) { return; } - NativeBlockState block = decorator.getBlockData100(biome, partRNG, realX, height, realZ, getData()); + NativeBlockState block = decorator.getBlockData100(biome, partRNG, realX, height, realZ, runtime); if (block != null) { data.set(x, height, z, block); } @@ -70,13 +72,13 @@ public class IrisSeaFloorDecorator extends IrisEngineDecorator { } int stack = Math.min(limit - height, - DecoratorCore.computeStack(decorator, partRNG, realX, realZ, getData(), max - height)); + DecoratorCore.computeStack(decorator, partRNG, realX, realZ, runtime, max - height)); for (int i = 0; i < stack; i++) { int h = height + i; double threshold = stack == 1 ? 1.0 : ((double) i) / (stack - 1); NativeBlockState block = threshold >= decorator.getTopThreshold() - ? decorator.getBlockDataForTop(biome, partRNG, realX, h, realZ, getData()) - : decorator.getBlockData100(biome, partRNG, realX, h, realZ, getData()); + ? decorator.getBlockDataForTop(biome, partRNG, realX, h, realZ, runtime) + : decorator.getBlockData100(biome, partRNG, realX, h, realZ, runtime); if (block == null) { break; } diff --git a/core/src/main/java/art/arcane/iris/generation/decoration/IrisSeaSurfaceDecorator.java b/core/src/main/java/art/arcane/iris/generation/decoration/IrisSeaSurfaceDecorator.java index cae6708e6..40111a93b 100644 --- a/core/src/main/java/art/arcane/iris/generation/decoration/IrisSeaSurfaceDecorator.java +++ b/core/src/main/java/art/arcane/iris/generation/decoration/IrisSeaSurfaceDecorator.java @@ -18,6 +18,7 @@ package art.arcane.iris.generation.decoration; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.volmlib.util.hunk.Hunk; @@ -42,25 +43,26 @@ public class IrisSeaSurfaceDecorator extends IrisEngineDecorator { return; } RNG rng = getRNG(realX, realZ); - IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ); + PackRuntime runtime = PackRuntime.of(getEngine(), getData()); + IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, runtime, realX, realZ); if (decorator == null) { return; } try { - place(decorator, x, z, realX, realZ, data, biome, height, max, maxBaseY); + place(decorator, x, z, realX, realZ, data, biome, height, max, maxBaseY, runtime); } catch (Throwable e) { DecoratorCore.skip(e, decorator, getData(), realX, height, realZ, biome); } } private void place(IrisDecorator decorator, int x, int z, int realX, int realZ, Hunk data, - IrisBiome biome, int height, int max, int maxBaseY) { + IrisBiome biome, int height, int max, int maxBaseY, PackRuntime runtime) { if (!decorator.isStacking()) { int targetY = height + 1; if (DecoratorCore.canReplaceStackTarget(data.get(x, targetY, z), false)) { - NativeBlockState block = decorator.getBlockData100(biome, partRNG, realX, height, realZ, getData()); + NativeBlockState block = decorator.getBlockData100(biome, partRNG, realX, height, realZ, runtime); if (block != null) { data.set(x, targetY, z, block); } @@ -69,7 +71,7 @@ public class IrisSeaSurfaceDecorator extends IrisEngineDecorator { } int stack = Math.min(maxBaseY - height, - DecoratorCore.computeStack(decorator, partRNG, realX, realZ, getData(), max - height)); + DecoratorCore.computeStack(decorator, partRNG, realX, realZ, runtime, max - height)); for (int i = 0; i < stack; i++) { int h = height + i; int targetY = h + 1; @@ -78,8 +80,8 @@ public class IrisSeaSurfaceDecorator extends IrisEngineDecorator { } double threshold = stack == 1 ? 1.0 : ((double) i) / (stack - 1); NativeBlockState block = threshold >= decorator.getTopThreshold() - ? decorator.getBlockDataForTop(biome, partRNG, realX, h, realZ, getData()) - : decorator.getBlockData100(biome, partRNG, realX, h, realZ, getData()); + ? decorator.getBlockDataForTop(biome, partRNG, realX, h, realZ, runtime) + : decorator.getBlockData100(biome, partRNG, realX, h, realZ, runtime); if (block == null) { break; } diff --git a/core/src/main/java/art/arcane/iris/generation/decoration/IrisShoreLineDecorator.java b/core/src/main/java/art/arcane/iris/generation/decoration/IrisShoreLineDecorator.java index 3a1ca969b..07e3da76b 100644 --- a/core/src/main/java/art/arcane/iris/generation/decoration/IrisShoreLineDecorator.java +++ b/core/src/main/java/art/arcane/iris/generation/decoration/IrisShoreLineDecorator.java @@ -18,6 +18,7 @@ package art.arcane.iris.generation.decoration; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.volmlib.util.hunk.Hunk; @@ -78,7 +79,8 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator { int max ) { RNG rng = getRNG(realX, realZ); - IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ); + PackRuntime runtime = PackRuntime.of(getEngine(), getData()); + IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, runtime, realX, realZ); if (decorator == null) { return; @@ -90,14 +92,14 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator { } try { - placePicked(decorator, x, z, realX, realZ, data, biome, height, max); + placePicked(decorator, x, z, realX, realZ, data, biome, height, max, runtime); } catch (Throwable e) { DecoratorCore.skip(e, decorator, getData(), realX, height, realZ, biome); } } private void placePicked(IrisDecorator decorator, int x, int z, int realX, int realZ, Hunk data, - IrisBiome biome, int height, int max) { + IrisBiome biome, int height, int max, PackRuntime runtime) { NativeBlockState support = data.get(x, height, z); if (support == null || !support.isSolid()) { return; @@ -111,7 +113,7 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator { || !DecoratorCore.canReplaceStackTarget(data.get(x, targetY, z), false)) { return; } - NativeBlockState block = decorator.getBlockData100(biome, partRNG, realX, height, realZ, getData()); + NativeBlockState block = decorator.getBlockData100(biome, partRNG, realX, height, realZ, runtime); if (block != null && DecoratorCore.isValidShorelineSupport(decorator, block, support) && IrisSugarCane.canPlace(block, data, x, targetY, z, realX, realZ, getEngine())) { data.set(x, targetY, z, block); @@ -120,7 +122,7 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator { return; } - int stack = DecoratorCore.computeStack(decorator, partRNG, realX, realZ, getData(), max - height); + int stack = DecoratorCore.computeStack(decorator, partRNG, realX, realZ, runtime, max - height); if (stack == 1) { int targetY = height + 1; @@ -128,7 +130,7 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator { return; } - NativeBlockState block = decorator.getBlockDataForTop(biome, partRNG, realX, height, realZ, getData()); + NativeBlockState block = decorator.getBlockDataForTop(biome, partRNG, realX, height, realZ, runtime); if (block != null && DecoratorCore.isValidShorelineSupport(decorator, block, support) && IrisSugarCane.canPlace(block, data, x, targetY, z, realX, realZ, getEngine())) { data.set(x, targetY, z, block); @@ -146,8 +148,8 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator { } double threshold = ((double) i) / (stack - 1); NativeBlockState block = threshold >= decorator.getTopThreshold() - ? decorator.getBlockDataForTop(biome, partRNG, realX, h, realZ, getData()) - : decorator.getBlockData100(biome, partRNG, realX, h, realZ, getData()); + ? decorator.getBlockDataForTop(biome, partRNG, realX, h, realZ, runtime) + : decorator.getBlockData100(biome, partRNG, realX, h, realZ, runtime); if (block == null) { break; } diff --git a/core/src/main/java/art/arcane/iris/generation/decoration/IrisSugarCane.java b/core/src/main/java/art/arcane/iris/generation/decoration/IrisSugarCane.java index d22d0bcfa..62366c26a 100644 --- a/core/src/main/java/art/arcane/iris/generation/decoration/IrisSugarCane.java +++ b/core/src/main/java/art/arcane/iris/generation/decoration/IrisSugarCane.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.decoration; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.runtime.IrisComplex; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.biome.IrisBiome; @@ -79,7 +80,7 @@ final class IrisSugarCane { } IrisBiome biome = complex.getTrueBiomeStream().get(x, z); KList layers = biome.generateSeaLayers(x, z, - new RNG(engine.getSeedManager().getTerrain()), fluidHeight - terrainHeight, engine.getData()); + new RNG(engine.getSeedManager().getTerrain()), fluidHeight - terrainHeight, PackRuntime.of(engine)); int depth = fluidHeight - y; return supportsAdjacent(layers.hasIndex(depth) ? layers.get(depth) : complex.resolveSeaFluid(x, z)); } diff --git a/core/src/main/java/art/arcane/iris/generation/decoration/IrisSurfaceDecorator.java b/core/src/main/java/art/arcane/iris/generation/decoration/IrisSurfaceDecorator.java index ac8e96c26..5b08acd27 100644 --- a/core/src/main/java/art/arcane/iris/generation/decoration/IrisSurfaceDecorator.java +++ b/core/src/main/java/art/arcane/iris/generation/decoration/IrisSurfaceDecorator.java @@ -18,6 +18,7 @@ package art.arcane.iris.generation.decoration; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.context.ChunkContext; @@ -73,21 +74,22 @@ public class IrisSurfaceDecorator extends IrisEngineDecorator { } boolean caveSkipFluid = skipsFluid(inferredType); RNG rng = getRNG(realX, realZ); - IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ); + PackRuntime runtime = PackRuntime.of(getEngine(), getData()); + IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, runtime, realX, realZ); if (decorator == null || !isSlopeValid(decorator, realX, height, realZ)) { return; } try { - place(decorator, x, z, realX, realZ, data, height, max, underwater, fluidHeight, caveSkipFluid); + place(decorator, x, z, realX, realZ, data, height, max, underwater, fluidHeight, caveSkipFluid, runtime); } catch (Throwable e) { DecoratorCore.skip(e, decorator, getData(), realX, height, realZ, biome); } } private void place(IrisDecorator decorator, int x, int z, int realX, int realZ, Hunk data, - int height, int max, boolean underwater, int fluidHeight, boolean caveSkipFluid) { + int height, int max, boolean underwater, int fluidHeight, boolean caveSkipFluid, PackRuntime runtime) { AquaticPlacementSnapshot aquaticSnapshot = captureAquaticPlacement( decorator, getData(), data, x, z, height, max); if (decorator.isStacking()) { @@ -97,13 +99,17 @@ public class IrisSurfaceDecorator extends IrisEngineDecorator { opts.fluidHeight = fluidHeight; opts.caveSkipFluid = caveSkipFluid; opts.mantle = getEngine().getMantle(); - DecoratorCore.placeStackUp(decorator, x, z, realX, realZ, height, max, data, partRNG, getData(), opts); + try { + DecoratorCore.placeStackUp(decorator, x, z, realX, realZ, height, max, data, partRNG, runtime, opts); + } finally { + opts.mantle = null; + } aquaticSnapshot.restoreIfUnsupported(data, x, z); return; } DecoratorCore.placeSurfaceSingle(decorator, x, z, realX, height, realZ, - data, partRNG, getData(), underwater, caveSkipFluid, getEngine().getMantle()); + data, partRNG, runtime, underwater, caveSkipFluid, getEngine().getMantle()); aquaticSnapshot.restoreIfUnsupported(data, x, z); } diff --git a/core/src/main/java/art/arcane/iris/generation/decoration/OreBandsRuntime.java b/core/src/main/java/art/arcane/iris/generation/decoration/OreBandsRuntime.java new file mode 100644 index 000000000..31fa33e14 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/decoration/OreBandsRuntime.java @@ -0,0 +1,68 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.generation.decoration; + +import art.arcane.iris.generation.runtime.PackRuntime; +import art.arcane.volmlib.nativelib.terrain.NativeBlockState; +import art.arcane.volmlib.util.math.RNG; + +/** + * What one engine derives from an {@link IrisOreBands} for one seed: the chance field of every banded generator, + * resolved once so placing ores block by block reads plain fields instead of looking each generator up. + */ +public final class OreBandsRuntime { + private final IrisOreBands bands; + private final PackRuntime runtime; + private final IrisOreGenerator.OreChance[] chances; + + public OreBandsRuntime(IrisOreBands bands, long seed, PackRuntime runtime) { + this.bands = bands; + this.runtime = runtime; + IrisOreGenerator[] generators = bands.generators(); + this.chances = new IrisOreGenerator.OreChance[generators.length]; + for (int index = 0; index < generators.length; index++) { + chances[index] = runtime.oreChance(generators[index], seed); + } + } + + public IrisOreBands bands() { + return bands; + } + + public boolean hasOres() { + return bands.hasOres(); + } + + public int lowestY() { + return bands.lowestY(); + } + + public int highestY() { + return bands.highestY(); + } + + public boolean contains(int y) { + return bands.contains(y); + } + + /** The ore placed at a Y inside {@link #contains(int)}, or null when no generator places one. */ + public NativeBlockState generate(int x, int y, int z, RNG rng) { + return bands.generate(x, y, z, rng, chances, runtime); + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/decoration/formation/FormationBlockResolver.java b/core/src/main/java/art/arcane/iris/generation/decoration/formation/FormationBlockResolver.java index ca5f8253a..8f6fe41f1 100644 --- a/core/src/main/java/art/arcane/iris/generation/decoration/formation/FormationBlockResolver.java +++ b/core/src/main/java/art/arcane/iris/generation/decoration/formation/FormationBlockResolver.java @@ -18,6 +18,7 @@ package art.arcane.iris.generation.decoration.formation; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.generation.terrain.IrisMaterialPalette; import art.arcane.iris.generation.decoration.IrisProceduralBlocks; @@ -59,7 +60,7 @@ public final class FormationBlockResolver { strataRng = new RNG(formation.getSeed() + band * 31L); strataRngs.put(band, strataRng); } - NativeBlockState strataState = strata.get(strataRng, x, band, z, data); + NativeBlockState strataState = strata.get(strataRng, x, band, z, PackRuntime.forPack(data)); if (strataState != null) { return strataState; } diff --git a/core/src/main/java/art/arcane/iris/generation/decoration/tree/TreeBlockResolver.java b/core/src/main/java/art/arcane/iris/generation/decoration/tree/TreeBlockResolver.java index 9695e0d0b..cceaa49d3 100644 --- a/core/src/main/java/art/arcane/iris/generation/decoration/tree/TreeBlockResolver.java +++ b/core/src/main/java/art/arcane/iris/generation/decoration/tree/TreeBlockResolver.java @@ -18,6 +18,7 @@ package art.arcane.iris.generation.decoration.tree; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.generation.terrain.IrisMaterialPalette; import art.arcane.iris.generation.decoration.IrisProceduralBlocks; @@ -84,7 +85,7 @@ public final class TreeBlockResolver { private static NativeBlockState resolveSecondaryLeaf(IrisProceduralTree tree, IrisData data, TreeBlockCanvas.Vec pos, RNG paletteRng) { if (IrisProceduralBlocks.paletteSet(tree.getSecondaryLeavesPalette())) { - return tree.getSecondaryLeavesPalette().get(paletteRng, pos.x(), pos.y(), pos.z(), data); + return tree.getSecondaryLeavesPalette().get(paletteRng, pos.x(), pos.y(), pos.z(), PackRuntime.forPack(data)); } if (tree.getWeightedSecondaryLeaves() != null && !tree.getWeightedSecondaryLeaves().isEmpty()) { String picked = pickWeighted(tree, new RNG(tree.getSeed() ^ positionHash(pos))); @@ -117,7 +118,7 @@ public final class TreeBlockResolver { private static NativeBlockState resolveBlock(String block, IrisMaterialPalette palette, IrisData data, TreeBlockCanvas.Vec pos, RNG paletteRng) { if (IrisProceduralBlocks.paletteSet(palette)) { - return palette.get(paletteRng, pos.x(), pos.y(), pos.z(), data); + return palette.get(paletteRng, pos.x(), pos.y(), pos.z(), PackRuntime.forPack(data)); } if (block != null && !block.isEmpty()) { return B.getStateOrNull(block, false); diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/engine/HydrologyRuntime.java b/core/src/main/java/art/arcane/iris/generation/hydrology/engine/HydrologyRuntime.java index 1d82cf6fa..5d00056f5 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/engine/HydrologyRuntime.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/engine/HydrologyRuntime.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.hydrology.engine; +import art.arcane.iris.generation.runtime.ThreadSlots; import art.arcane.iris.generation.runtime.HydrologyPlanException; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.concurrent.MultiBurst; @@ -78,7 +79,7 @@ public final class HydrologyRuntime { private final NaturalHeights naturalHeight; private final BooleanSupplier mainThread; private final RasterLru rasters; - private final ThreadLocal last; + private final ThreadSlots last; private final Set queued; private final ConcurrentHashMap> building; private final RasterFailures failures; @@ -132,7 +133,7 @@ public final class HydrologyRuntime { this.naturalHeight = Objects.requireNonNull(naturalHeight, "naturalHeight"); this.mainThread = Objects.requireNonNull(mainThread, "mainThread"); this.rasters = new RasterLru(); - this.last = ThreadLocal.withInitial(LastRaster::new); + this.last = new ThreadSlots<>(LastRaster::new); this.queued = ConcurrentHashMap.newKeySet(); this.building = new ConcurrentHashMap<>(); this.failures = new RasterFailures(ticker); diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/engine/IrisHydrologyTerrainSource.java b/core/src/main/java/art/arcane/iris/generation/hydrology/engine/IrisHydrologyTerrainSource.java index a32aaa9af..07785a612 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/engine/IrisHydrologyTerrainSource.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/engine/IrisHydrologyTerrainSource.java @@ -60,7 +60,7 @@ public final class IrisHydrologyTerrainSource implements HydrologyTerrainSource, this.focus = complex.getFocusBiome(); this.binding = Objects.requireNonNull(binding, "binding"); this.climate = settings.climate(); - this.wetness = climate.enabled() ? climate.style().create(settings.seed() ^ SALT_CLIMATE, complex.getData()) : null; + this.wetness = climate.enabled() ? climate.style().create(settings.seed() ^ SALT_CLIMATE, complex.getPackRuntime()) : null; } @Override diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/FloatingIslandSampleResolver.java b/core/src/main/java/art/arcane/iris/generation/mantle/FloatingIslandSampleResolver.java index 536a70ae3..8fc357de3 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/FloatingIslandSampleResolver.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/FloatingIslandSampleResolver.java @@ -18,6 +18,7 @@ package art.arcane.iris.generation.mantle; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.generation.cache.Cache; import art.arcane.iris.generation.runtime.Engine; @@ -32,6 +33,7 @@ import org.jetbrains.annotations.Nullable; final class FloatingIslandSampleResolver implements IslandObjectPlacer.SampleProvider { private final IrisData data; private final Engine engine; + private final PackRuntime runtime; private final int chunkHeight; private final long baseSeed; private final FloatingIslandBoundarySampler boundarySampler; @@ -41,6 +43,7 @@ final class FloatingIslandSampleResolver implements IslandObjectPlacer.SamplePro FloatingIslandSampleResolver(EngineMantle engineMantle, FloatingIslandBoundarySampler boundarySampler) { this.data = engineMantle.getData(); this.engine = engineMantle.getEngine(); + this.runtime = PackRuntime.of(engine, data); this.chunkHeight = engine.getHeight(); this.baseSeed = engine.getSeedManager().getTerrain() ^ IrisFloatingChildBiomeModifier.FLOATING_BASE_SEED_SALT; this.boundarySampler = boundarySampler; @@ -48,6 +51,10 @@ final class FloatingIslandSampleResolver implements IslandObjectPlacer.SamplePro this.resolvedSamples = new LongOpenHashSet(); } + PackRuntime runtime() { + return runtime; + } + @Override public @Nullable FloatingIslandSample sample(int x, int z) { long key = Cache.key(x, z); @@ -59,7 +66,7 @@ final class FloatingIslandSampleResolver implements IslandObjectPlacer.SamplePro resolvedSamples.add(key); return null; } - FloatingIslandSample sample = FloatingIslandSample.sample(parent, x, z, chunkHeight, baseSeed, data, engine, boundarySampler); + FloatingIslandSample sample = FloatingIslandSample.sample(parent, x, z, chunkHeight, baseSeed, runtime, boundarySampler); resolvedSamples.add(key); if (sample != null) { sampleCache.put(key, sample); diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/IrisCaveCarver3D.java b/core/src/main/java/art/arcane/iris/generation/mantle/IrisCaveCarver3D.java index bf8868823..5948a03ba 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/IrisCaveCarver3D.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/IrisCaveCarver3D.java @@ -18,6 +18,8 @@ package art.arcane.iris.generation.mantle; +import art.arcane.iris.generation.runtime.ThreadSlots; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.GenerationCounter; @@ -78,6 +80,7 @@ public class IrisCaveCarver3D { private final Engine engine; private final IrisData data; + private final PackRuntime runtime; private final IrisCaveProfile profile; private final NoiseProgram baseDensity; private final NoiseProgram detailDensity; @@ -108,8 +111,8 @@ public class IrisCaveCarver3D { private final int verticalDensityStep; private final int worldMinimumY; private final int densityMaximumY; - private final ThreadLocal carving = ThreadLocal.withInitial(() -> false); - private final ThreadLocal scratchCache = ThreadLocal.withInitial(CaveCarveScratch::new); + private final ThreadSlots carving = new ThreadSlots<>(() -> false); + private final ThreadSlots scratchCache = new ThreadSlots<>(CaveCarveScratch::new); private final CaveDensityGrid densityGrid; private final CaveDensityGrid.Owner densityOwner; private final CaveDensityGrid.Owner warpOwner; @@ -122,6 +125,7 @@ public class IrisCaveCarver3D { this.engine = engine; this.densityGrid = densityGrid; this.data = engine.getData(); + this.runtime = PackRuntime.of(engine, data); this.profile = profile; this.carveAir = new MatterCavern(true, "", LIQUID_AIR); this.carveFluid = new MatterCavern(true, "", LIQUID_FLUID); @@ -130,10 +134,10 @@ public class IrisCaveCarver3D { List moduleStates = new ArrayList<>(); RNG baseRng = new RNG(engine.getSeedManager().getCarve()); - this.baseDensity = NoiseProgram.compileSigned3D(profile.getBaseDensityStyle().create(baseRng.nextParallelRNG(934_447), data)); - this.detailDensity = NoiseProgram.compileSigned3D(profile.getDetailDensityStyle().create(baseRng.nextParallelRNG(612_991), data)); - this.warpDensity = NoiseProgram.compileSigned3D(profile.getWarpStyle().create(baseRng.nextParallelRNG(770_713), data)); - this.surfaceBreakDensity = profile.getSurfaceBreakStyle().create(baseRng.nextParallelRNG(341_219), data); + this.baseDensity = NoiseProgram.compileSigned3D(profile.getBaseDensityStyle().create(baseRng.nextParallelRNG(934_447), runtime)); + this.detailDensity = NoiseProgram.compileSigned3D(profile.getDetailDensityStyle().create(baseRng.nextParallelRNG(612_991), runtime)); + this.warpDensity = NoiseProgram.compileSigned3D(profile.getWarpStyle().create(baseRng.nextParallelRNG(770_713), runtime)); + this.surfaceBreakDensity = profile.getSurfaceBreakStyle().create(baseRng.nextParallelRNG(341_219), runtime); this.thresholdRng = baseRng.nextParallelRNG(489_112); this.baseWeight = profile.getBaseWeight(); this.detailWeight = profile.getDetailWeight(); @@ -149,7 +153,7 @@ public class IrisCaveCarver3D { double weight = Math.abs(baseWeight) + Math.abs(detailWeight); int index = 0; for (IrisCaveFieldModule module : profile.getModules()) { - CNG moduleDensity = module.getStyle().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), data); + CNG moduleDensity = module.getStyle().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), runtime); CaveFieldModuleState state = new CaveFieldModuleState(module, NoiseProgram.compileSigned3D(moduleDensity)); moduleStates.add(state); weight += Math.abs(state.weight); @@ -342,7 +346,7 @@ public class IrisCaveCarver3D { } else if (densityThreshold.getStyle().isFlat()) { constantThreshold = M.lerp(thresholdMin, thresholdMax, 0.5); } else { - thresholdDensity = densityThreshold.getStyle().create(thresholdRng, data); + thresholdDensity = densityThreshold.getStyle().create(thresholdRng, runtime); } for (int lx = 0; lx < 16; lx++) { diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/IrisStructureComponent.java b/core/src/main/java/art/arcane/iris/generation/mantle/IrisStructureComponent.java index ecd841fb6..c4db0f367 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/IrisStructureComponent.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/IrisStructureComponent.java @@ -26,7 +26,7 @@ import art.arcane.volmlib.util.structure.StructureCarveEnvelope; import art.arcane.volmlib.nativelib.terrain.structure.StructureWaterRules; import art.arcane.iris.configuration.IrisSettings; -import art.arcane.iris.pack.loading.IrisData; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.cache.Cache; import art.arcane.iris.generation.runtime.IrisComplex; import art.arcane.iris.generation.runtime.GenerationFailures; @@ -197,6 +197,7 @@ public class IrisStructureComponent extends IrisMantleComponent { settings.getPalette(), "Structure stilt palette must not be null"); int mantleOffset = getEngineMantle().getEngine().getMinHeight(); int maxDepth = Math.max(1, settings.getMaxDepth()); + PackRuntime runtime = PackRuntime.of(getEngineMantle().getEngine(), getData()); for (Long2IntMap.Entry column : columns.long2IntEntrySet()) { int worldX = StructureFoundationPlanner.unpackX(column.getLongKey()); int worldZ = StructureFoundationPlanner.unpackZ(column.getLongKey()); @@ -225,16 +226,16 @@ public class IrisStructureComponent extends IrisMantleComponent { } StructureFoundationPlanner.fillSupportColumn(foundationY, groundY, y -> { writeFoundationSupport( - writer, palette, rng, getData(), worldX, y, worldZ, mantleOffset); + writer, palette, rng, runtime, worldX, y, worldZ, mantleOffset); }); } } static void writeFoundationSupport(MantleWriter writer, IrisMaterialPalette palette, RNG rng, - IrisData data, int worldX, int mantleY, int worldZ, + PackRuntime runtime, int worldX, int mantleY, int worldZ, int mantleOffset) { int worldY = mantleY + mantleOffset; - NativeBlockState support = palette.get(rng, worldX, worldY, worldZ, data); + NativeBlockState support = palette.get(rng, worldX, worldY, worldZ, runtime); if (support == null) { throw new IllegalStateException("Structure stilt palette resolved no block at " + worldX + "," + worldY + "," + worldZ); diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/MantleCarvingComponent.java b/core/src/main/java/art/arcane/iris/generation/mantle/MantleCarvingComponent.java index 7250cfbb8..fdc201c7c 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/MantleCarvingComponent.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/MantleCarvingComponent.java @@ -152,7 +152,7 @@ public class MantleCarvingComponent extends IrisMantleComponent { private void generateLayer(MantleWriter writer, int x, int z, ChunkContext context, BlendScratch blendScratch) { IrisComplex complex = context.getComplex(); - IrisDimensionCarvingResolver.State resolverState = blendScratch.resolverState; + IrisDimensionCarvingResolver.State resolverState = IrisDimensionCarvingResolver.threadState(getEngineMantle().getEngine()); int[] chunkSurfaceHeights = prepareChunkSurfaceHeights(x, z, context, blendScratch.chunkSurfaceHeights); PrecisionStopwatch resolveStopwatch = PrecisionStopwatch.start(); List weightedProfiles = resolveWeightedProfiles(x, z, complex, resolverState); @@ -766,7 +766,6 @@ public class MantleCarvingComponent extends IrisMantleComponent { private final double[][] neighbourHeights = new double[NEIGHBOURS][CHUNK_AREA]; private final Object[][] neighbourObjects = new Object[NEIGHBOURS][CHUNK_AREA]; private final long[][] neighbourSubmerged = new long[NEIGHBOURS][4]; - private final IrisDimensionCarvingResolver.State resolverState = new IrisDimensionCarvingResolver.State(); private int nextWeightBuffer; private boolean inUse; diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/MantleFloatingObjectComponent.java b/core/src/main/java/art/arcane/iris/generation/mantle/MantleFloatingObjectComponent.java index 8c5c7a5db..3ef6b0600 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/MantleFloatingObjectComponent.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/MantleFloatingObjectComponent.java @@ -18,6 +18,7 @@ package art.arcane.iris.generation.mantle; +import art.arcane.iris.generation.runtime.PackRuntime; import java.io.UncheckedIOException; import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.generation.runtime.GenerationFailures; @@ -76,7 +77,7 @@ public class MantleFloatingObjectComponent extends IrisMantleComponent { RNG chunkRng = new RNG(Cache.key(x, z) + seed() + 0x0FA710BEL); FloatingIslandSampleResolver sampleResolver = new FloatingIslandSampleResolver(getEngineMantle(), context.getFloatingIslandBoundarySampler()); - FloatingIslandSample.clearChunkMemo(); + FloatingIslandSample.clearChunkMemo(sampleResolver.runtime()); FloatingIslandSample[] samples = new FloatingIslandSample[256]; for (int xf = 0; xf < 16; xf++) { @@ -180,7 +181,7 @@ public class MantleFloatingObjectComponent extends IrisMantleComponent { if (placement.isCompatExcluded(data)) { return; } - int density = placement.getDensity(rng, minX, minZ, data); + int density = placement.getDensity(rng, minX, minZ, PackRuntime.of(getEngineMantle().getEngine(), data)); double perAttempt = placement.getChance(); for (int i = 0; i < density; i++) { if (!rng.chance(perAttempt + rng.d(-0.005, 0.005))) { @@ -249,7 +250,7 @@ public class MantleFloatingObjectComponent extends IrisMantleComponent { if (placement.isCompatExcluded(data)) { return; } - int density = placement.getDensity(rng, minX, minZ, data); + int density = placement.getDensity(rng, minX, minZ, PackRuntime.of(getEngineMantle().getEngine(), data)); double perAttempt = placement.getChance(); for (int i = 0; i < density; i++) { @@ -345,7 +346,7 @@ public class MantleFloatingObjectComponent extends IrisMantleComponent { if (placement.isCompatExcluded(data)) { return; } - int density = placement.getDensity(rng, minX, minZ, data); + int density = placement.getDensity(rng, minX, minZ, PackRuntime.of(getEngineMantle().getEngine(), data)); double perAttempt = placement.getChance(); for (int i = 0; i < density; i++) { diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/MantleObjectComponent.java b/core/src/main/java/art/arcane/iris/generation/mantle/MantleObjectComponent.java index ac53f6af3..176ee80d6 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/MantleObjectComponent.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/MantleObjectComponent.java @@ -19,6 +19,7 @@ package art.arcane.iris.generation.mantle; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.configuration.IrisSettings; import art.arcane.iris.generation.block.B; import art.arcane.iris.generation.cache.Cache; @@ -959,7 +960,7 @@ public class MantleObjectComponent extends IrisMantleComponent { int rejected = 0; int nullObjects = 0; int errors = 0; - int density = objectPlacement.getDensity(rng, x, z, getData()); + int density = objectPlacement.getDensity(rng, x, z, PackRuntime.of(getEngineMantle().getEngine(), getData())); boolean golden = GoldenDebugObjectPlacer.isGoldenDebugChunk(chunkX, chunkZ); for (int i = 0; i < density; i++) { @@ -1094,7 +1095,7 @@ public class MantleObjectComponent extends IrisMantleComponent { int errors = 0; int minX = chunkX << 4; int minZ = chunkZ << 4; - int density = objectPlacement.getDensity(rng, minX, minZ, getData()); + int density = objectPlacement.getDensity(rng, minX, minZ, PackRuntime.of(getEngineMantle().getEngine(), getData())); IrisCaveAnchorMode anchorMode = resolveAnchorMode(objectPlacement, caveProfile); if (objectPlacement.getMode() == ObjectPlaceMode.CEILING_HANG) { anchorMode = IrisCaveAnchorMode.CEILING; @@ -1328,7 +1329,7 @@ public class MantleObjectComponent extends IrisMantleComponent { int chunkHeight = getEngineMantle().getEngine().getHeight(); int minX = chunkX << 4; int minZ = chunkZ << 4; - int density = objectPlacement.getDensity(rng, minX, minZ, getData()); + int density = objectPlacement.getDensity(rng, minX, minZ, PackRuntime.of(getEngineMantle().getEngine(), getData())); for (int i = 0; i < density; i++) { IrisObject v = objectPlacement.scaleObject(rng, objectPlacement.getObject(upperCtx, rng), upperCtx.getDimension()); @@ -1734,7 +1735,7 @@ public class MantleObjectComponent extends IrisMantleComponent { @BlockCoordinates private Set guessPlacedKeys(RNG rng, int x, int z, IrisObjectPlacement objectPlacement) { Set f = new KSet<>(); - for (int i = 0; i < objectPlacement.getDensity(rng, x, z, getData()); i++) { + for (int i = 0; i < objectPlacement.getDensity(rng, x, z, PackRuntime.of(getEngineMantle().getEngine(), getData())); i++) { IrisObject v = objectPlacement.scaleObject(rng, objectPlacement.getObject(getComplex(), rng), getDimension()); if (v == null) { continue; diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/MantleWriter.java b/core/src/main/java/art/arcane/iris/generation/mantle/MantleWriter.java index 29630cb94..a35ce4373 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/MantleWriter.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/MantleWriter.java @@ -19,6 +19,7 @@ package art.arcane.iris.generation.mantle; +import art.arcane.iris.generation.runtime.ThreadSlots; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.structure.object.ObjectWaterRule; import art.arcane.iris.world.storage.matter.TileWrapper; @@ -84,14 +85,14 @@ public class MantleWriter implements ObjectPassPlacer, AutoCloseable { @Setter(AccessLevel.NONE) @EqualsAndHashCode.Exclude @ToString.Exclude - private final ThreadLocal activeComponentPriority = new ThreadLocal<>(); + private final ThreadSlots activeComponentPriority = ThreadSlots.bindings(); @Getter(AccessLevel.NONE) - private final ThreadLocal objectPlacementCapture = new ThreadLocal<>(); + private final ThreadSlots objectPlacementCapture = ThreadSlots.bindings(); @Getter(AccessLevel.NONE) @Setter(AccessLevel.NONE) @EqualsAndHashCode.Exclude @ToString.Exclude - private final ThreadLocal objectWater = new ThreadLocal<>(); + private final ThreadSlots objectWater = ThreadSlots.bindings(); @Getter(AccessLevel.NONE) @Setter(AccessLevel.NONE) @EqualsAndHashCode.Exclude diff --git a/core/src/main/java/art/arcane/iris/generation/noise/ExpressionNoise.java b/core/src/main/java/art/arcane/iris/generation/noise/ExpressionNoise.java index b9e2f091f..737978952 100644 --- a/core/src/main/java/art/arcane/iris/generation/noise/ExpressionNoise.java +++ b/core/src/main/java/art/arcane/iris/generation/noise/ExpressionNoise.java @@ -24,9 +24,9 @@ import art.arcane.volmlib.util.math.RNG; public class ExpressionNoise implements NoiseGenerator { private final RNG rng; - private final IrisExpression expression; + private final ExpressionRuntime expression; - public ExpressionNoise(RNG rng, IrisExpression expression) { + public ExpressionNoise(RNG rng, ExpressionRuntime expression) { this.rng = rng; this.expression = expression; } diff --git a/core/src/main/java/art/arcane/iris/generation/noise/ExpressionRuntime.java b/core/src/main/java/art/arcane/iris/generation/noise/ExpressionRuntime.java new file mode 100644 index 000000000..3432cc5ef --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/noise/ExpressionRuntime.java @@ -0,0 +1,258 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.generation.noise; + +import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.generation.runtime.PackRuntime; +import art.arcane.iris.generation.runtime.SeedTable; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.noise.CNG; +import art.arcane.volmlib.util.stream.ProceduralStream; +import art.arcane.volmlib.util.stream.interpolation.Interpolated; +import com.dfsek.paralithic.Expression; +import com.dfsek.paralithic.functions.dynamic.Context; +import com.dfsek.paralithic.functions.dynamic.DynamicFunction; +import com.dfsek.paralithic.node.Statefulness; +import lombok.NonNull; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Objects; + +/** + * An {@link IrisExpression} parsed for one runtime scope: its functions and variables read that scope's engine + * streams and seeded styles, so the parsed expression belongs to the scope and not to the pack object. + */ +public final class ExpressionRuntime { + private static final int SEED_CAPACITY = 8; + private static final int MAX_RETAINED_EVALUATION_DEPTH = 8; + private static final int MAX_RETAINED_ARGUMENTS = 256; + private static final ThreadLocal EVALUATION_SCRATCH = + ThreadLocal.withInitial(EvaluationScratch::new); + + private final VariableRuntime[] variables; + private final Expression parsed; + private final SeedTable> streams; + + public ExpressionRuntime(IrisExpression expression, PackRuntime runtime) { + this.variables = expression.getVariables().stream() + .map(variable -> new VariableRuntime(variable, runtime)) + .toArray(VariableRuntime[]::new); + this.parsed = expression.parse(function -> new FunctionRuntime(function, runtime)); + this.streams = new SeedTable<>(SEED_CAPACITY, seed -> { + RNG streamRng = new RNG(seed); + return ProceduralStream.of((x, z) -> evaluate(streamRng, x, z), + (x, y, z) -> evaluate(streamRng, x, y, z), Interpolated.DOUBLE); + }); + } + + public ProceduralStream stream(RNG rng) { + return streams.get(rng.getSeed()); + } + + public double evaluate(RNG rng, double x, double z) { + EvaluationScratch scratch = EVALUATION_SCRATCH.get(); + double[] arguments = scratch.acquire(3 + variables.length); + try { + int index = 0; + for (VariableRuntime variable : variables) { + arguments[index++] = variable.value(rng, x, z); + } + arguments[index++] = x; + arguments[index++] = z; + arguments[index] = -1; + return parsed.evaluate(new FunctionContext(rng), arguments); + } finally { + scratch.release(); + } + } + + public double evaluate(RNG rng, double x, double y, double z) { + EvaluationScratch scratch = EVALUATION_SCRATCH.get(); + double[] arguments = scratch.acquire(3 + variables.length); + try { + int index = 0; + for (VariableRuntime variable : variables) { + arguments[index++] = variable.value(rng, x, y, z); + } + arguments[index++] = x; + arguments[index++] = y; + arguments[index] = z; + return parsed.evaluate(new FunctionContext(rng), arguments); + } finally { + scratch.release(); + } + } + + public record FunctionContext(@NonNull RNG rng) implements Context { + @Override + public boolean equals(Object o) { + if (o == null || getClass() != o.getClass()) return false; + FunctionContext that = (FunctionContext) o; + return rng.getSeed() == that.rng.getSeed(); + } + + @Override + public int hashCode() { + return Long.hashCode(rng.getSeed()); + } + } + + private static Engine requireEngine(PackRuntime runtime, String kind, String name) { + Engine engine = runtime.engine(); + if (engine == null) { + throw new IllegalStateException("Expression " + kind + " '" + name + "' requires an active Iris engine."); + } + return engine; + } + + private static final class FunctionRuntime implements DynamicFunction { + private final IrisExpressionFunction function; + private final PackRuntime runtime; + private final SeedTable providers; + + private FunctionRuntime(IrisExpressionFunction function, PackRuntime runtime) { + this.function = function; + this.runtime = runtime; + this.providers = new SeedTable<>(SEED_CAPACITY, this::createProvider); + } + + @Override + public int getArgNumber() { + return function.argumentCount(); + } + + @NotNull + @Override + public Statefulness statefulness() { + return Statefulness.STATEFUL; + } + + @Override + public double eval(double... doubles) { + return 0; + } + + @Override + public double eval(@Nullable Context raw, double... args) { + FunctionContext context = Objects.requireNonNull((FunctionContext) raw, "Expression context"); + return providers.get(context.rng().getSeed()).eval(args); + } + + private Provider createProvider(long seed) { + if (function.getEngineStreamValue() != null) { + Engine engine = requireEngine(runtime, "function", function.getName()); + ProceduralStream stream = function.getEngineStreamValue().get(engine); + return coordinates -> stream.get(coordinates[0], coordinates[1]); + } + if (function.getStyleValue() != null) { + return function.getStyleValue().create(seed, runtime)::noise; + } + return coordinates -> Double.NaN; + } + } + + @FunctionalInterface + private interface Provider { + double eval(double... args); + } + + private static final class VariableRuntime { + private final IrisExpressionLoad variable; + private final PackRuntime runtime; + private final SeedTable styles; + private volatile ProceduralStream engineStream; + private volatile Double engineValue; + + private VariableRuntime(IrisExpressionLoad variable, PackRuntime runtime) { + this.variable = variable; + this.runtime = runtime; + this.styles = new SeedTable<>(SEED_CAPACITY, + seed -> variable.getStyleValue().createNoCache(new RNG(seed), runtime)); + } + + private double value(RNG rng, double x, double z) { + if (variable.getEngineValue() != null) { + return engineValue(); + } + if (variable.getEngineStreamValue() != null) { + return engineStream().get(x, z); + } + if (variable.getStyleValue() != null) { + return styles.get(rng.getSeed()).noise(x, z); + } + return variable.getStaticValue(); + } + + private double value(RNG rng, double x, double y, double z) { + if (variable.getEngineValue() != null) { + return engineValue(); + } + if (variable.getEngineStreamValue() != null) { + return engineStream().get(x, z); + } + if (variable.getStyleValue() != null) { + return styles.get(rng.getSeed()).noise(x, y, z); + } + return variable.getStaticValue(); + } + + private double engineValue() { + Double value = engineValue; + if (value == null) { + value = variable.getEngineValue().get(requireEngine(runtime, "variable", variable.getName())); + engineValue = value; + } + return value; + } + + private ProceduralStream engineStream() { + ProceduralStream stream = engineStream; + if (stream == null) { + stream = variable.getEngineStreamValue().get(requireEngine(runtime, "variable", variable.getName())); + engineStream = stream; + } + return stream; + } + } + + private static final class EvaluationScratch { + private final double[][] retained = new double[MAX_RETAINED_EVALUATION_DEPTH][]; + private int depth; + + private double[] acquire(int length) { + double[] arguments; + if (depth >= retained.length || length > MAX_RETAINED_ARGUMENTS) { + arguments = new double[length]; + } else { + arguments = retained[depth]; + if (arguments == null || arguments.length != length) { + arguments = new double[length]; + retained[depth] = arguments; + } + } + depth++; + return arguments; + } + + private void release() { + depth--; + } + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/noise/GeneratorProgram.java b/core/src/main/java/art/arcane/iris/generation/noise/GeneratorProgram.java index 9d6cc266c..bc4daf274 100644 --- a/core/src/main/java/art/arcane/iris/generation/noise/GeneratorProgram.java +++ b/core/src/main/java/art/arcane/iris/generation/noise/GeneratorProgram.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.noise; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.volmlib.util.interpolation.IrisInterpolation; import java.util.Arrays; @@ -21,9 +22,14 @@ public final class GeneratorProgram { private final double cliffHeightMin; private final double cliffHeightMax; private final boolean cellCracks; + private final PackRuntime runtime; + private final IrisGenerator.SurfaceCacheStripe[] surfaceStripes; - GeneratorProgram(IrisGenerator generator, long superSeed, NoiseLayerProgram[] layers, double totalOpacity, NoiseLayerProgram cliffs) { + GeneratorProgram(IrisGenerator generator, long superSeed, NoiseLayerProgram[] layers, double totalOpacity, + NoiseLayerProgram cliffs, PackRuntime runtime) { this.generator = generator; + this.runtime = runtime; + this.surfaceStripes = runtime.generator(generator).surfaceStripes(); this.superSeed = superSeed; this.layers = layers; this.totalOpacity = totalOpacity; @@ -69,7 +75,7 @@ public final class GeneratorProgram { double lowerZ = Math.floor(z / SURFACE_GRID) * SURFACE_GRID; double dx = (x - lowerX) / SURFACE_GRID; double dz = (z - lowerZ) / SURFACE_GRID; - IrisGenerator.SurfaceCacheStripe[] stripes = generator.surfaceStripes(); + IrisGenerator.SurfaceCacheStripe[] stripes = surfaceStripes; double northWest = lattice(scratch, stripes, lowerX, lowerZ); if (dx == 0D && dz == 0D) { return northWest; @@ -124,7 +130,7 @@ public final class GeneratorProgram { double height = IrisInterpolation.lerp(cliffHeightMin, cliffHeightMax, cliffs.sample(scratch, sampleX, sampleZ)); value = (Math.round((value * 255D) / height) * height) / 255D; } - return cellCracks ? generator.cell(x, z, value, 0D) : value; + return cellCracks ? generator.cell(runtime, x, z, value, 0D) : value; } private void surfaceHeights(TerrainBatchScratch scratch, double[] xs, double[] zs, int count, double[] out) { @@ -226,7 +232,7 @@ public final class GeneratorProgram { } private void resolveLattice(TerrainBatchScratch scratch, int nodes, double[] lattice) { - IrisGenerator.SurfaceCacheStripe[] stripes = generator.surfaceStripes(); + IrisGenerator.SurfaceCacheStripe[] stripes = surfaceStripes; int indexMark = scratch.indexMark(); int mark = scratch.mark(); try { @@ -308,7 +314,7 @@ public final class GeneratorProgram { } if (cellCracks) { for (int index = 0; index < count; index++) { - out[index] = generator.cell(xs[index], zs[index], out[index], 0D); + out[index] = generator.cell(runtime, xs[index], zs[index], out[index], 0D); } } } diff --git a/core/src/main/java/art/arcane/iris/generation/noise/GeneratorRuntime.java b/core/src/main/java/art/arcane/iris/generation/noise/GeneratorRuntime.java new file mode 100644 index 000000000..a5bfb99bc --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/noise/GeneratorRuntime.java @@ -0,0 +1,45 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.generation.noise; + +import art.arcane.iris.generation.runtime.SeedTable; +import art.arcane.volmlib.util.noise.CellGenerator; + +/** + * What one engine derives from an {@link IrisGenerator}: the lattice of smoothed surface heights it has sampled and + * the cell generators of its crack seeds. + */ +public final class GeneratorRuntime { + private static final int CELL_SEED_CAPACITY = 8; + + private final IrisGenerator.SurfaceCacheStripe[] surfaceStripes = IrisGenerator.createSurfaceStripes(); + private final SeedTable cellGenerators; + + public GeneratorRuntime(IrisGenerator generator) { + this.cellGenerators = new SeedTable<>(CELL_SEED_CAPACITY, generator::buildCellGenerator); + } + + IrisGenerator.SurfaceCacheStripe[] surfaceStripes() { + return surfaceStripes; + } + + public CellGenerator cellGenerator(long seed) { + return cellGenerators.get(seed); + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/noise/IrisExpression.java b/core/src/main/java/art/arcane/iris/generation/noise/IrisExpression.java index eb96d30f0..6dd0e4a15 100644 --- a/core/src/main/java/art/arcane/iris/generation/noise/IrisExpression.java +++ b/core/src/main/java/art/arcane/iris/generation/noise/IrisExpression.java @@ -20,28 +20,22 @@ package art.arcane.iris.generation.noise; import art.arcane.iris.spi.IrisLogging; import com.dfsek.paralithic.Expression; +import com.dfsek.paralithic.functions.dynamic.DynamicFunction; import com.dfsek.paralithic.eval.parser.Parser; import com.dfsek.paralithic.eval.parser.Scope; import art.arcane.iris.pack.loading.IrisRegistrant; -import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.iris.generation.cache.LazyBoundedCache; -import lombok.AccessLevel; -import lombok.Getter; -import lombok.Setter; -import art.arcane.iris.generation.noise.IrisExpressionFunction.FunctionContext; import art.arcane.iris.pack.schema.annotation.ArrayType; import art.arcane.volmlib.util.documentation.Description; import art.arcane.iris.pack.schema.annotation.Required; import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; -import art.arcane.volmlib.util.stream.ProceduralStream; -import art.arcane.volmlib.util.stream.interpolation.Interpolated; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; +import java.util.function.Function; + @Accessors(chain = true) @NoArgsConstructor @AllArgsConstructor @@ -49,9 +43,6 @@ import lombok.experimental.Accessors; @Data @EqualsAndHashCode(callSuper = false) public class IrisExpression extends IrisRegistrant { - private static final int MAX_RETAINED_EVALUATION_DEPTH = 8; - private static final int MAX_RETAINED_ARGUMENTS = 256; - @ArrayType(type = IrisExpressionLoad.class, min = 1) @Description("Variables to use in this expression") private KList variables = new KList<>(); @@ -64,88 +55,38 @@ public class IrisExpression extends IrisRegistrant { @Description("The expression. Inherited variables are x, y and z. Avoid using those variable names.") private String expression; - private transient AtomicCache expressionCache = new AtomicCache<>(); - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private final transient LazyBoundedCache> streams = new LazyBoundedCache<>(8); + /** + * Parses this expression with each valid function bound to the runtime object the caller built for it. + * Returns null when the expression does not parse; the failure is reported. + */ + public Expression parse(Function functionRuntime) { + Scope scope = new Scope(); // Create variable scope. This scope can hold both constants and invocation variables. + Parser parser = new Parser(); - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private final transient ThreadLocal evaluationScratch = ThreadLocal.withInitial(EvaluationScratch::new); - - private Expression expression() { - return expressionCache.aquire(() -> { - Scope scope = new Scope(); // Create variable scope. This scope can hold both constants and invocation variables. - Parser parser = new Parser(); - - try { - for (IrisExpressionLoad i : variables) { - scope.addInvocationVariable(i.getName()); - } - - scope.addInvocationVariable("x"); - scope.addInvocationVariable("y"); - scope.addInvocationVariable("z"); - } catch (Throwable e) { - IrisLogging.reportError("Script variable load failed in " + getLoadFile().getPath() + ".", e); - } - - for (IrisExpressionFunction f : functions) { - if (!f.isValid()) continue; - f.setData(getLoader()); - parser.registerFunction(f.getName(), f); - } - - try { - return parser.parse(getExpression(), scope); - } catch (Throwable e) { - IrisLogging.reportError("Script load failed in " + getLoadFile().getPath() + ".", e); - } - - return null; - }); - } - - public ProceduralStream stream(RNG rng) { - return streams.computeIfAbsent(rng.getSeed(), seed -> { - RNG streamRng = new RNG(seed); - return ProceduralStream.of((x, z) -> evaluate(streamRng, x, z), - (x, y, z) -> evaluate(streamRng, x, y, z), Interpolated.DOUBLE); - }); - } - - public double evaluate(RNG rng, double x, double z) { - EvaluationScratch scratch = evaluationScratch.get(); - double[] arguments = scratch.acquire(3 + getVariables().size()); try { - int index = 0; - for (IrisExpressionLoad variable : getVariables()) { - arguments[index++] = variable.getValue(rng, getLoader(), x, z); + for (IrisExpressionLoad i : variables) { + scope.addInvocationVariable(i.getName()); } - arguments[index++] = x; - arguments[index++] = z; - arguments[index] = -1; - return expression().evaluate(new FunctionContext(rng), arguments); - } finally { - scratch.release(); - } - } - public double evaluate(RNG rng, double x, double y, double z) { - EvaluationScratch scratch = evaluationScratch.get(); - double[] arguments = scratch.acquire(3 + getVariables().size()); - try { - int index = 0; - for (IrisExpressionLoad variable : getVariables()) { - arguments[index++] = variable.getValue(rng, getLoader(), x, y, z); - } - arguments[index++] = x; - arguments[index++] = y; - arguments[index] = z; - return expression().evaluate(new FunctionContext(rng), arguments); - } finally { - scratch.release(); + scope.addInvocationVariable("x"); + scope.addInvocationVariable("y"); + scope.addInvocationVariable("z"); + } catch (Throwable e) { + IrisLogging.reportError("Script variable load failed in " + getLoadFile().getPath() + ".", e); } + + for (IrisExpressionFunction f : functions) { + if (!f.isValid()) continue; + parser.registerFunction(f.getName(), functionRuntime.apply(f)); + } + + try { + return parser.parse(getExpression(), scope); + } catch (Throwable e) { + IrisLogging.reportError("Script load failed in " + getLoadFile().getPath() + ".", e); + } + + return null; } @Override @@ -157,28 +98,4 @@ public class IrisExpression extends IrisRegistrant { public String getTypeName() { return "Expression"; } - - private static final class EvaluationScratch { - private final double[][] retained = new double[MAX_RETAINED_EVALUATION_DEPTH][]; - private int depth; - - private double[] acquire(int length) { - double[] arguments; - if (depth >= retained.length || length > MAX_RETAINED_ARGUMENTS) { - arguments = new double[length]; - } else { - arguments = retained[depth]; - if (arguments == null || arguments.length != length) { - arguments = new double[length]; - retained[depth] = arguments; - } - } - depth++; - return arguments; - } - - private void release() { - depth--; - } - } } diff --git a/core/src/main/java/art/arcane/iris/generation/noise/IrisExpressionFunction.java b/core/src/main/java/art/arcane/iris/generation/noise/IrisExpressionFunction.java index d831ec99b..93d88587e 100644 --- a/core/src/main/java/art/arcane/iris/generation/noise/IrisExpressionFunction.java +++ b/core/src/main/java/art/arcane/iris/generation/noise/IrisExpressionFunction.java @@ -2,31 +2,15 @@ package art.arcane.iris.generation.noise; import art.arcane.iris.generation.runtime.IrisEngineStreamType; -import com.dfsek.paralithic.functions.dynamic.Context; -import com.dfsek.paralithic.functions.dynamic.DynamicFunction; -import com.dfsek.paralithic.node.Statefulness; -import art.arcane.iris.pack.loading.IrisData; import art.arcane.volmlib.util.documentation.Description; import art.arcane.iris.pack.schema.annotation.MinNumber; import art.arcane.iris.pack.schema.annotation.Required; import art.arcane.iris.pack.schema.annotation.Snippet; -import art.arcane.iris.generation.cache.LazyBoundedCache; -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.volmlib.util.stream.ProceduralStream; - -import java.util.Objects; -import art.arcane.volmlib.util.math.RNG; -import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; -import lombok.Getter; import lombok.NoArgsConstructor; -import lombok.NonNull; -import lombok.Setter; import lombok.experimental.Accessors; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; @Snippet("expression-function") @Accessors(chain = true) @@ -35,7 +19,7 @@ import org.jetbrains.annotations.Nullable; @Description("Represents a function to use in your expression. Do not set the name to x, y, or z, also don't duplicate names.") @Data @EqualsAndHashCode(callSuper = false) -public class IrisExpressionFunction implements DynamicFunction { +public class IrisExpressionFunction { @Required @Description("The function to assign this value to. Do not set the name to x, y, or z") private String name; @@ -50,102 +34,12 @@ public class IrisExpressionFunction implements DynamicFunction { @Description("Number of arguments for the function") private int args = 2; - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private transient final LazyBoundedCache providers = new LazyBoundedCache<>(8); - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private transient volatile CachedProvider recentProvider; - private transient IrisData data; - public boolean isValid() { return styleValue != null || engineStreamValue != null; } - @Override - public int getArgNumber() { + public int argumentCount() { if (engineStreamValue != null) return 2; return Math.max(args, 2); } - - @NotNull - @Override - public Statefulness statefulness() { - return Statefulness.STATEFUL; - } - - @Override - public double eval(double... doubles) { - return 0; - } - - @Override - public double eval(@Nullable Context raw, double... args) { - FunctionContext context = Objects.requireNonNull((FunctionContext) raw, "Expression context"); - IrisData currentData = data; - Engine engine = currentData == null ? null : currentData.getEngine(); - long seed = context.rng.getSeed(); - CachedProvider recent = recentProvider; - if (recent != null && recent.key.matches(seed, currentData, engine)) { - return recent.provider.eval(args); - } - FunctionKey key = new FunctionKey(seed, currentData, engine); - Provider provider = providers.computeIfAbsent(key, ignored -> createProvider(key)); - recentProvider = new CachedProvider(key, provider); - return provider.eval(args); - } - - private Provider createProvider(FunctionKey key) { - if (engineStreamValue != null) { - if (key.engine == null) { - throw new IllegalStateException("Expression function '" + name + "' requires an active Iris engine."); - } - ProceduralStream stream = engineStreamValue.get(key.engine); - return coordinates -> stream.get(coordinates[0], coordinates[1]); - } - if (styleValue != null) { - return styleValue.create(new RNG(key.seed), key.data, key.engine)::noise; - } - return coordinates -> Double.NaN; - } - - private record FunctionKey(long seed, IrisData data, Engine engine) { - private boolean matches(long seed, IrisData data, Engine engine) { - return this.seed == seed && this.data == data && this.engine == engine; - } - - @Override - public boolean equals(Object object) { - return object instanceof FunctionKey other && matches(other.seed, other.data, other.engine); - } - - @Override - public int hashCode() { - int hash = Long.hashCode(seed); - hash = 31 * hash + System.identityHashCode(data); - return 31 * hash + System.identityHashCode(engine); - } - } - - private record CachedProvider(FunctionKey key, Provider provider) { - } - - public record FunctionContext(@NonNull RNG rng) implements Context { - @Override - public boolean equals(Object o) { - if (o == null || getClass() != o.getClass()) return false; - FunctionContext that = (FunctionContext) o; - return rng.getSeed() == that.rng.getSeed(); - } - - @Override - public int hashCode() { - return Long.hashCode(rng.getSeed()); - } - } - - @FunctionalInterface - private interface Provider { - double eval(double... args); - } } diff --git a/core/src/main/java/art/arcane/iris/generation/noise/IrisExpressionLoad.java b/core/src/main/java/art/arcane/iris/generation/noise/IrisExpressionLoad.java index d624ce293..5a7cfdcba 100644 --- a/core/src/main/java/art/arcane/iris/generation/noise/IrisExpressionLoad.java +++ b/core/src/main/java/art/arcane/iris/generation/noise/IrisExpressionLoad.java @@ -21,30 +21,15 @@ package art.arcane.iris.generation.noise; import art.arcane.iris.generation.runtime.IrisEngineStreamType; import art.arcane.iris.generation.runtime.IrisEngineValueType; -import art.arcane.iris.pack.loading.IrisData; -import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.iris.generation.cache.LazyBoundedCache; -import art.arcane.iris.generation.runtime.Engine; import art.arcane.volmlib.util.documentation.Description; import art.arcane.iris.pack.schema.annotation.Required; import art.arcane.iris.pack.schema.annotation.Snippet; -import art.arcane.volmlib.util.math.RNG; -import art.arcane.volmlib.util.noise.CNG; -import art.arcane.volmlib.util.stream.ProceduralStream; -import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; -import lombok.Getter; import lombok.NoArgsConstructor; -import lombok.Setter; import lombok.experimental.Accessors; -import java.util.Collections; -import java.util.IdentityHashMap; -import java.util.Iterator; -import java.util.Map; - @Snippet("expression-load") @Accessors(chain = true) @NoArgsConstructor @@ -53,7 +38,6 @@ import java.util.Map; @Data @EqualsAndHashCode(callSuper = false) public class IrisExpressionLoad { - private static final int STYLE_CACHE_SIZE = 8; @Required @Description("The variable to assign this value to. Do not set the name to x, y, or z") private String name = ""; @@ -69,119 +53,4 @@ public class IrisExpressionLoad { @Description("If defined, iris will use an internal value from the engine as it's value") private IrisEngineValueType engineValue = null; - - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private transient final Map engineCaches = - Collections.synchronizedMap(new IdentityHashMap<>()); - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private transient final LazyBoundedCache standaloneStyleCache = - new LazyBoundedCache<>(STYLE_CACHE_SIZE); - - public double getValue(RNG rng, IrisData data, double x, double z) { - if (engineValue != null) { - Engine engine = requireEngine(data); - return cacheFor(engine).value.aquire(() -> engineValue.get(engine)); - } - - if (engineStreamValue != null) { - Engine engine = requireEngine(data); - return cacheFor(engine).stream.aquire(() -> engineStreamValue.get(engine)).get(x, z); - } - - if (styleValue != null) { - return style(data, rng).noise(x, z); - } - - return staticValue; - } - - public double getValue(RNG rng, IrisData data, double x, double y, double z) { - if (engineValue != null) { - Engine engine = requireEngine(data); - return cacheFor(engine).value.aquire(() -> engineValue.get(engine)); - } - - if (engineStreamValue != null) { - Engine engine = requireEngine(data); - return cacheFor(engine).stream.aquire(() -> engineStreamValue.get(engine)).get(x, z); - } - - if (styleValue != null) { - return style(data, rng).noise(x, y, z); - } - - return staticValue; - } - - private Engine requireEngine(IrisData data) { - Engine engine = data.getEngine(); - if (engine == null) { - throw new IllegalStateException("Expression variable '" + name + "' requires an active Iris engine."); - } - return engine; - } - - private EngineCache cacheFor(Engine engine) { - synchronized (engineCaches) { - Iterator> iterator = engineCaches.entrySet().iterator(); - while (iterator.hasNext()) { - if (iterator.next().getKey().isClosed()) { - iterator.remove(); - } - } - EngineCache cache = engineCaches.get(engine); - if (cache != null) { - return cache; - } - EngineCache created = new EngineCache(); - engineCaches.put(engine, created); - return created; - } - } - - private CNG style(IrisData data, RNG rng) { - Engine engine = data.getEngine(); - long seed = rng.getSeed(); - if (engine != null) { - return cacheFor(engine).styles.computeIfAbsent(seed, - ignored -> styleValue.createNoCache(new RNG(seed), data)); - } - StandaloneStyleKey key = new StandaloneStyleKey(data, seed); - return standaloneStyleCache.computeIfAbsent(key, - ignored -> styleValue.createNoCache(new RNG(seed), data)); - } - - private static final class EngineCache { - private final AtomicCache> stream = new AtomicCache<>(); - private final AtomicCache value = new AtomicCache<>(); - private final LazyBoundedCache styles = new LazyBoundedCache<>(STYLE_CACHE_SIZE); - } - - private static final class StandaloneStyleKey { - private final IrisData data; - private final long seed; - - private StandaloneStyleKey(IrisData data, long seed) { - this.data = data; - this.seed = seed; - } - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (!(other instanceof StandaloneStyleKey key)) { - return false; - } - return data == key.data && seed == key.seed; - } - - @Override - public int hashCode() { - return 31 * System.identityHashCode(data) + Long.hashCode(seed); - } - } } diff --git a/core/src/main/java/art/arcane/iris/generation/noise/IrisGenerator.java b/core/src/main/java/art/arcane/iris/generation/noise/IrisGenerator.java index dd5ebd912..300a3fa20 100644 --- a/core/src/main/java/art/arcane/iris/generation/noise/IrisGenerator.java +++ b/core/src/main/java/art/arcane/iris/generation/noise/IrisGenerator.java @@ -19,9 +19,7 @@ package art.arcane.iris.generation.noise; import art.arcane.iris.pack.loading.IrisRegistrant; -import art.arcane.iris.generation.cache.LazyBoundedCache; -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.pack.loading.IrisData; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.pack.schema.annotation.ArrayType; import art.arcane.volmlib.util.documentation.Description; import art.arcane.iris.pack.schema.annotation.MaxNumber; @@ -32,13 +30,10 @@ import art.arcane.volmlib.util.interpolation.IrisInterpolation; import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.noise.CellGenerator; import java.util.concurrent.atomic.AtomicReferenceArray; -import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; -import lombok.Getter; -import lombok.Setter; import lombok.experimental.Accessors; import java.util.List; @@ -54,15 +49,6 @@ public class IrisGenerator extends IrisRegistrant { private static final int SURFACE_CACHE_STRIPES = 16; private static final int SURFACE_CACHE_STRIPE_SIZE = 1024; - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private final transient LazyBoundedCache cellGenerators = new LazyBoundedCache<>(8); - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private transient volatile CachedCellGenerator recentCellGenerator; - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private transient volatile SurfaceCache surfaceSamples; @MinNumber(0.001) @Description("The zoom or frequency.") private double zoom = 1; @@ -119,21 +105,13 @@ public class IrisGenerator extends IrisRegistrant { return cliffHeightMax > 0; } - public CellGenerator getCellGenerator(long seed) { - CachedCellGenerator recent = recentCellGenerator; - if (recent != null && recent.seed == seed) { - return recent.generator; - } - CellGenerator generator = cellGenerators.computeIfAbsent(seed, ignored -> { - CellGenerator created = new CellGenerator(new RNG(seed + 239466)); - created.setShuffle(getCellFractureShuffle()); - return created; - }); - recentCellGenerator = new CachedCellGenerator(seed, generator); - return generator; + CellGenerator buildCellGenerator(long seed) { + CellGenerator created = new CellGenerator(new RNG(seed + 239466)); + created.setShuffle(getCellFractureShuffle()); + return created; } - public T fit(T[] v, long superSeed, double rx, double rz) { + public T fit(PackRuntime runtime, T[] v, long superSeed, double rx, double rz) { if (v.length == 0) { return null; } @@ -142,10 +120,10 @@ public class IrisGenerator extends IrisRegistrant { return v[0]; } - return v[fit(0, v.length - 1, superSeed, rx, rz)]; + return v[fit(runtime, 0, v.length - 1, superSeed, rx, rz)]; } - public T fit(List v, long superSeed, double rx, double rz) { + public T fit(PackRuntime runtime, List v, long superSeed, double rx, double rz) { if (v.size() == 0) { return null; } @@ -154,61 +132,59 @@ public class IrisGenerator extends IrisRegistrant { return v.get(0); } - return v.get(fit(0, v.size() - 1, superSeed, rx, rz)); + return v.get(fit(runtime, 0, v.size() - 1, superSeed, rx, rz)); } - public int fit(int min, int max, long superSeed, double rx, double rz) { + public int fit(PackRuntime runtime, int min, int max, long superSeed, double rx, double rz) { if (min == max) { return min; } - double noise = getHeight(rx, rz, superSeed); + double noise = getHeight(runtime, rx, rz, superSeed); return (int) Math.round(IrisInterpolation.lerp(min, max, noise)); } - public int fit(double min, double max, long superSeed, double rx, double rz) { + public int fit(PackRuntime runtime, double min, double max, long superSeed, double rx, double rz) { if (min == max) { return (int) Math.round(min); } - double noise = getHeight(rx, rz, superSeed); + double noise = getHeight(runtime, rx, rz, superSeed); return (int) Math.round(IrisInterpolation.lerp(min, max, noise)); } - public double fitDouble(double min, double max, long superSeed, double rx, double rz) { + public double fitDouble(PackRuntime runtime, double min, double max, long superSeed, double rx, double rz) { if (min == max) { return min; } - double noise = getHeight(rx, rz, superSeed); + double noise = getHeight(runtime, rx, rz, superSeed); return IrisInterpolation.lerp(min, max, noise); } - public double getHeight(double rx, double rz, long superSeed) { - return getHeight(rx, 0, rz, superSeed, true); + public double getHeight(PackRuntime runtime, double rx, double rz, long superSeed) { + return getHeight(runtime, rx, 0, rz, superSeed, true); } - public double getHeight(double rx, double ry, double rz, long superSeed) { - return getHeight(rx, ry, rz, superSeed, false); + public double getHeight(PackRuntime runtime, double rx, double ry, double rz, long superSeed) { + return getHeight(runtime, rx, ry, rz, superSeed, false); } - public double getHeight(double rx, double ry, double rz, long superSeed, boolean no3d) { + public double getHeight(PackRuntime runtime, double rx, double ry, double rz, long superSeed, boolean no3d) { if (!Double.isFinite(surfaceDetail) || surfaceDetail < 0D || surfaceDetail > 1D) { throw new IllegalArgumentException("Generator surfaceDetail must be finite and between 0 and 1"); } if (composite.isEmpty()) { return 0D; } - IrisData data = getLoader(); - Engine engine = data == null ? null : data.getEngine(); if (surfaceDetail == 1D) { - return sampleHeight(rx, rz, superSeed, data, engine); + return sampleHeight(rx, rz, superSeed, runtime); } - return surfaceHeight(rx, rz, superSeed, data, engine); + return surfaceHeight(rx, rz, superSeed, runtime); } public boolean supportsBatch() { @@ -224,35 +200,28 @@ public class IrisGenerator extends IrisRegistrant { return !hasCliffs() || cliffHeightGenerator.supportsBatch(); } - public GeneratorProgram compileProgram(long superSeed) { + public GeneratorProgram compileProgram(PackRuntime runtime, long superSeed) { if (!Double.isFinite(surfaceDetail) || surfaceDetail < 0D || surfaceDetail > 1D) { throw new IllegalArgumentException("Generator surfaceDetail must be finite and between 0 and 1"); } if (!supportsBatch()) { throw new IllegalStateException("Generator " + getLoadKey() + " cannot be compiled into a batch program"); } - IrisData data = getLoader(); - Engine engine = data == null ? null : data.getEngine(); int hc = (int) ((cliffHeightMin * 10) + 10 + cliffHeightMax * getSeed() + offsetX + offsetZ); NoiseLayerProgram[] layers = new NoiseLayerProgram[composite.size()]; double totalOpacity = 0D; for (int index = 0; index < layers.length; index++) { IrisNoiseGenerator layer = composite.get(index); - layers[index] = layer.compileProgram(getSeed() + superSeed + hc, data, engine); + layers[index] = layer.compileProgram(getSeed() + superSeed + hc, runtime); if (!multiplicitive) { totalOpacity += layer.getOpacity(); } } double cliffSeed = (double) (superSeed + 294596 + hc) - 34857; NoiseLayerProgram cliffs = hasCliffs() - ? cliffHeightGenerator.compileProgram((long) (getSeed() + cliffSeed + hc), data, engine) + ? cliffHeightGenerator.compileProgram((long) (getSeed() + cliffSeed + hc), runtime) : null; - return new GeneratorProgram(this, superSeed, layers, totalOpacity, cliffs); - } - - SurfaceCacheStripe[] surfaceStripes() { - IrisData data = getLoader(); - return surfaceCache(data, data == null ? null : data.getEngine()).stripes(); + return new GeneratorProgram(this, superSeed, layers, totalOpacity, cliffs, runtime); } static boolean cachedSurface(SurfaceCacheStripe[] stripes, double x, double z, long superSeed, double[] target, int index) { @@ -281,30 +250,30 @@ public class IrisGenerator extends IrisRegistrant { return mixed; } - private double surfaceHeight(double rx, double rz, long superSeed, IrisData data, Engine engine) { - SurfaceCacheStripe[] stripes = surfaceCache(data, engine).stripes(); + private double surfaceHeight(double rx, double rz, long superSeed, PackRuntime runtime) { + SurfaceCacheStripe[] stripes = runtime.generator(this).surfaceStripes(); double lowerX = Math.floor(rx / SURFACE_GRID) * SURFACE_GRID; double lowerZ = Math.floor(rz / SURFACE_GRID) * SURFACE_GRID; double dx = (rx - lowerX) / SURFACE_GRID; double dz = (rz - lowerZ) / SURFACE_GRID; - double northWest = cachedSurfaceHeight(lowerX, lowerZ, superSeed, stripes, data, engine); + double northWest = cachedSurfaceHeight(lowerX, lowerZ, superSeed, stripes, runtime); if (dx == 0D && dz == 0D) { return northWest; } double north = dx == 0D ? northWest : IrisInterpolation.lerp(northWest, - cachedSurfaceHeight(lowerX + SURFACE_GRID, lowerZ, superSeed, stripes, data, engine), dx); + cachedSurfaceHeight(lowerX + SURFACE_GRID, lowerZ, superSeed, stripes, runtime), dx); double smooth = north; if (dz != 0D) { - double southWest = cachedSurfaceHeight(lowerX, lowerZ + SURFACE_GRID, superSeed, stripes, data, engine); + double southWest = cachedSurfaceHeight(lowerX, lowerZ + SURFACE_GRID, superSeed, stripes, runtime); double south = dx == 0D ? southWest : IrisInterpolation.lerp(southWest, - cachedSurfaceHeight(lowerX + SURFACE_GRID, lowerZ + SURFACE_GRID, superSeed, stripes, data, engine), dx); + cachedSurfaceHeight(lowerX + SURFACE_GRID, lowerZ + SURFACE_GRID, superSeed, stripes, runtime), dx); smooth = IrisInterpolation.lerp(north, south, dz); } return surfaceDetail == 0D ? smooth - : smooth + (sampleHeight(rx, rz, superSeed, data, engine) - smooth) * surfaceDetail; + : smooth + (sampleHeight(rx, rz, superSeed, runtime) - smooth) * surfaceDetail; } - private double sampleHeight(double rx, double rz, long superSeed, IrisData data, Engine engine) { + private double sampleHeight(double rx, double rz, long superSeed, PackRuntime runtime) { int hc = (int) ((cliffHeightMin * 10) + 10 + cliffHeightMax * getSeed() + offsetX + offsetZ); double h = multiplicitive ? 1 : 0; double tp = 0; @@ -313,18 +282,18 @@ public class IrisGenerator extends IrisRegistrant { if (composite.size() == 1) { if (multiplicitive) { - h *= composite.get(0).getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, data, engine); + h *= composite.get(0).getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, runtime); } else { tp += composite.get(0).getOpacity(); - h += composite.get(0).getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, data, engine); + h += composite.get(0).getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, runtime); } } else { for (IrisNoiseGenerator i : composite) { if (multiplicitive) { - h *= i.getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, data, engine); + h *= i.getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, runtime); } else { tp += i.getOpacity(); - h += i.getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, data, engine); + h += i.getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, runtime); } } } @@ -335,15 +304,15 @@ public class IrisGenerator extends IrisRegistrant { v = 0; } - v = hasCliffs() ? cliff(rx, rz, v, superSeed + 294596 + hc, data, engine) : v; - v = hasCellCracks() ? cell(rx, rz, v, superSeed + 48622 + hc) : v; + v = hasCliffs() ? cliff(runtime, rx, rz, v, superSeed + 294596 + hc) : v; + v = hasCellCracks() ? cell(runtime, rx, rz, v, superSeed + 48622 + hc) : v; return v; } - private double cachedSurfaceHeight(double x, double z, long superSeed, SurfaceCacheStripe[] stripes, IrisData data, Engine engine) { + private double cachedSurfaceHeight(double x, double z, long superSeed, SurfaceCacheStripe[] stripes, PackRuntime runtime) { if (x != (int) x || z != (int) z) { - return sampleHeight(x, z, superSeed, data, engine); + return sampleHeight(x, z, superSeed, runtime); } long key = ((long) (int) x << 32) | ((int) z & 0xffffffffL); long mixed = surfaceMix(key); @@ -353,27 +322,12 @@ public class IrisGenerator extends IrisRegistrant { if (cached != null) { return cached.height(); } - double height = sampleHeight(x, z, superSeed, data, engine); + double height = sampleHeight(x, z, superSeed, runtime); stripe.put(slot, new SurfaceSample(key, superSeed, height)); return height; } - private SurfaceCache surfaceCache(IrisData data, Engine engine) { - SurfaceCache cached = surfaceSamples; - if (cached != null && cached.data() == data && cached.engine() == engine) { - return cached; - } - synchronized (this) { - cached = surfaceSamples; - if (cached == null || cached.data() != data || cached.engine() != engine) { - cached = new SurfaceCache(data, engine, createSurfaceCache()); - surfaceSamples = cached; - } - return cached; - } - } - - private static SurfaceCacheStripe[] createSurfaceCache() { + static SurfaceCacheStripe[] createSurfaceStripes() { SurfaceCacheStripe[] stripes = new SurfaceCacheStripe[SURFACE_CACHE_STRIPES]; for (int i = 0; i < stripes.length; i++) { stripes[i] = new SurfaceCacheStripe(); @@ -381,45 +335,29 @@ public class IrisGenerator extends IrisRegistrant { return stripes; } - public double cell(double rx, double rz, double v, double superSeed) { + public double cell(PackRuntime runtime, double rx, double rz, double v, double superSeed) { double fractureX = rx / getCellFractureZoom(); double fractureZ = rz / getCellFractureZoom(); - return getCellGenerator(getSeed() + 46222).getDistance(fractureX, fractureZ) > getCellPercentSize() ? (v * getCellFractureHeight()) : v; + return runtime.generator(this).cellGenerator(getSeed() + 46222).getDistance(fractureX, fractureZ) > getCellPercentSize() ? (v * getCellFractureHeight()) : v; } private boolean hasCellCracks() { return getCellFractureHeight() != 0; } - public double getCliffHeight(double rx, double rz, double superSeed) { - IrisData data = getLoader(); - return getCliffHeight(rx, rz, superSeed, data, data == null ? null : data.getEngine()); - } - - private double getCliffHeight(double rx, double rz, double superSeed, IrisData data, Engine engine) { + public double getCliffHeight(PackRuntime runtime, double rx, double rz, double superSeed) { int hc = (int) ((cliffHeightMin * 10) + 10 + cliffHeightMax * getSeed() + offsetX + offsetZ); double sampleX = (rx + offsetX) / zoom; double sampleZ = (rz + offsetZ) / zoom; - double h = cliffHeightGenerator.getNoise((long) (getSeed() + superSeed + hc), sampleX, sampleZ, data, engine); + double h = cliffHeightGenerator.getNoise((long) (getSeed() + superSeed + hc), sampleX, sampleZ, runtime); return IrisInterpolation.lerp(cliffHeightMin, cliffHeightMax, h); } - public double cliff(double rx, double rz, double v, double superSeed) { - IrisData data = getLoader(); - return cliff(rx, rz, v, superSeed, data, data == null ? null : data.getEngine()); - } - - private double cliff(double rx, double rz, double v, double superSeed, IrisData data, Engine engine) { - double cliffHeight = getCliffHeight(rx, rz, superSeed - 34857, data, engine); + public double cliff(PackRuntime runtime, double rx, double rz, double v, double superSeed) { + double cliffHeight = getCliffHeight(runtime, rx, rz, superSeed - 34857); return (Math.round((v * 255D) / cliffHeight) * cliffHeight) / 255D; } - public IrisGenerator rescale(double scale) { - zoom /= scale; - surfaceSamples = null; - return this; - } - public KList getAllComposites() { KList g = new KList<>(); @@ -440,9 +378,6 @@ public class IrisGenerator extends IrisRegistrant { return "Generator"; } - private record SurfaceCache(IrisData data, Engine engine, SurfaceCacheStripe[] stripes) { - } - private record SurfaceSample(long key, long seed, double height) { } @@ -458,7 +393,4 @@ public class IrisGenerator extends IrisRegistrant { entries.set(slot, sample); } } - - private record CachedCellGenerator(long seed, CellGenerator generator) { - } } diff --git a/core/src/main/java/art/arcane/iris/generation/noise/IrisGeneratorStyle.java b/core/src/main/java/art/arcane/iris/generation/noise/IrisGeneratorStyle.java index 9561e3e56..7cbdff5ff 100644 --- a/core/src/main/java/art/arcane/iris/generation/noise/IrisGeneratorStyle.java +++ b/core/src/main/java/art/arcane/iris/generation/noise/IrisGeneratorStyle.java @@ -21,8 +21,8 @@ package art.arcane.iris.generation.noise; import art.arcane.iris.generation.image.IrisImageMap; import art.arcane.iris.pack.loading.IrisData; -import art.arcane.iris.generation.cache.LazyBoundedCache; import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.world.history.GenerationKernelRegistry; import art.arcane.volmlib.util.documentation.Description; import art.arcane.iris.pack.schema.annotation.MaxNumber; @@ -52,15 +52,7 @@ import java.util.concurrent.ConcurrentHashMap; @Description("A gen style") @Data public class IrisGeneratorStyle { - private static final int GENERATOR_CACHE_SIZE = 8; private static final ConcurrentHashMap ACTIVE_CACHE_KEYS = new ConcurrentHashMap<>(); - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private final transient LazyBoundedCache generatorCache = - new LazyBoundedCache<>(GENERATOR_CACHE_SIZE); - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private transient volatile CachedGenerator recentGenerator; @Description("The base noise style. Used when neither expression nor imageMap is set; a failed expression also falls back to this style, except one that names an unknown engine stream, which fails the pack load.") private NoiseStyle style = NoiseStyle.FLAT; @@ -101,24 +93,20 @@ public class IrisGeneratorStyle { return this; } - public CNG createNoCache(RNG rng, IrisData data) { - return createNoCache(rng, data, 1, 0, false, resolveEngine(data)); + public CNG createNoCache(RNG rng, PackRuntime runtime) { + return createNoCache(rng, runtime, 1, 0, false); } - public CNG createScaledGenerator(RNG rng, IrisData data, double scaleFactor) { - return createNoCache(rng, data).bake().scale(scaleFactor).bake(); + public CNG createScaledGenerator(RNG rng, PackRuntime runtime, double scaleFactor) { + return createNoCache(rng, runtime).bake().scale(scaleFactor).bake(); } - public CNG createForLayer(RNG rng, IrisData data, int octaveMultiplier) { - return createForLayer(rng, data, octaveMultiplier, resolveEngine(data)); + public CNG createForLayer(RNG rng, PackRuntime runtime, int octaveMultiplier) { + return createNoCache(rng, runtime, Math.clamp(octaveMultiplier, 1, 16), 0, false); } - CNG createForLayer(RNG rng, IrisData data, int octaveMultiplier, Engine engine) { - return createNoCache(rng, data, Math.clamp(octaveMultiplier, 1, 16), 0, false, engine); - } - - public CNG createForPrebake(RNG rng, IrisData data, int fallbackCacheSize) { - return createNoCache(rng, data, 1, Math.max(0, fallbackCacheSize), true, resolveEngine(data)); + public CNG createForPrebake(RNG rng, PackRuntime runtime, int fallbackCacheSize) { + return createNoCache(rng, runtime, 1, Math.max(0, fallbackCacheSize), true); } @@ -175,8 +163,10 @@ public class IrisGeneratorStyle { } } - private CNG createNoCache(RNG rng, IrisData data, int octaveMultiplier, int fallbackCacheSize, - boolean quietCacheLog, Engine engine) { + private CNG createNoCache(RNG rng, PackRuntime runtime, int octaveMultiplier, int fallbackCacheSize, + boolean quietCacheLog) { + IrisData data = runtime.data(); + Engine engine = runtime.engine(); requirePositiveFinite("zoom", zoom); requirePositiveFinite("exponent", exponent); if (!Double.isFinite(cellularFrequency) || cellularFrequency < 0D) { @@ -193,7 +183,7 @@ public class IrisGeneratorStyle { if (getExpression() != null) { IrisExpression e = data.getExpressionLoader().load(getExpression()); if (e != null) { - cng = new CNG(rng, new ExpressionNoise(rng, e), 1D, 1).bake(); + cng = new CNG(rng, new ExpressionNoise(rng, runtime.expression(e)), 1D, 1).bake(); sourceStamp = Integer.toUnsignedLong(Objects.hash(getExpression(), e.getLoadFile() == null ? 0L : e.getLoadFile().lastModified())); } @@ -211,8 +201,8 @@ public class IrisGeneratorStyle { .pow(cng.getPower() * exponent); if (fracture != null) { - cng.fractureWith(fracture.createNoCache(rng.nextParallelRNG(2934), data, 1, - fallbackCacheSize, quietCacheLog, engine), fracture.getMultiplier()); + cng.fractureWith(fracture.createNoCache(rng.nextParallelRNG(2934), runtime, 1, + fallbackCacheSize, quietCacheLog), fracture.getMultiplier()); } if (cellularFrequency > 0) { @@ -232,32 +222,17 @@ public class IrisGeneratorStyle { return cng; } - public double warp(RNG rng, IrisData data, double value, double... coords) { - return create(rng, data).noise(coords) + value; + public double warp(RNG rng, PackRuntime runtime, double value, double... coords) { + return create(rng, runtime).noise(coords) + value; } - public CNG create(RNG rng, IrisData data) { - return create(rng, data, resolveEngine(data)); + /** The generator this runtime shares for this style and seed. */ + public CNG create(RNG rng, PackRuntime runtime) { + return create(rng.getSeed(), runtime); } - public CNG create(long seed, IrisData data) { - return cachedGenerator(seed, data, resolveEngine(data)); - } - - public CNG create(RNG rng, IrisData data, Engine engine) { - return cachedGenerator(rng.getSeed(), data, engine); - } - - private CNG cachedGenerator(long seed, IrisData data, Engine engine) { - CachedGenerator recent = recentGenerator; - if (recent != null && recent.key.matches(data, engine, seed)) { - return recent.generator; - } - GeneratorCacheKey key = new GeneratorCacheKey(data, engine, seed); - CNG generator = generatorCache.computeIfAbsent(key, - ignored -> createNoCache(new RNG(seed), data, 1, 0, false, engine)); - recentGenerator = new CachedGenerator(key, generator); - return generator; + public CNG create(long seed, PackRuntime runtime) { + return runtime.styleGenerator(this, seed); } @SuppressWarnings("BooleanMethodIsAlwaysInverted") @@ -282,10 +257,6 @@ public class IrisGeneratorStyle { )); } - private Engine resolveEngine(IrisData data) { - return data == null ? null : data.getEngine(); - } - private static void requirePositiveFinite(String field, double value) { if (!Double.isFinite(value) || value <= 0D || !Double.isFinite(1D / value)) { throw new IllegalArgumentException(field + " must be finite and positive"); @@ -304,41 +275,4 @@ public class IrisGeneratorStyle { } } } - - private static final class GeneratorCacheKey { - private final IrisData data; - private final Engine engine; - private final long seed; - - private GeneratorCacheKey(IrisData data, Engine engine, long seed) { - this.data = data; - this.engine = engine; - this.seed = seed; - } - - private boolean matches(IrisData data, Engine engine, long seed) { - return this.data == data && this.engine == engine && this.seed == seed; - } - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (!(other instanceof GeneratorCacheKey key)) { - return false; - } - return data == key.data && engine == key.engine && seed == key.seed; - } - - @Override - public int hashCode() { - int result = System.identityHashCode(data); - result = 31 * result + System.identityHashCode(engine); - return 31 * result + Long.hashCode(seed); - } - } - - private record CachedGenerator(GeneratorCacheKey key, CNG generator) { - } } diff --git a/core/src/main/java/art/arcane/iris/generation/noise/IrisNoiseGenerator.java b/core/src/main/java/art/arcane/iris/generation/noise/IrisNoiseGenerator.java index 8589d0f21..5c4382da6 100644 --- a/core/src/main/java/art/arcane/iris/generation/noise/IrisNoiseGenerator.java +++ b/core/src/main/java/art/arcane/iris/generation/noise/IrisNoiseGenerator.java @@ -18,9 +18,7 @@ package art.arcane.iris.generation.noise; -import art.arcane.iris.pack.loading.IrisData; -import art.arcane.iris.generation.cache.LazyBoundedCache; -import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.pack.schema.annotation.ArrayType; import art.arcane.volmlib.util.documentation.Description; import art.arcane.iris.pack.schema.annotation.MaxNumber; @@ -40,16 +38,12 @@ import art.arcane.volmlib.util.noise.OffsetNoiseGenerator; import art.arcane.volmlib.util.noise.PerlinNoise; import art.arcane.volmlib.util.noise.SimplexNoise; import art.arcane.volmlib.util.noise.program.NoiseProgram; -import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Data; -import lombok.Getter; import lombok.NoArgsConstructor; -import lombok.Setter; import lombok.experimental.Accessors; import java.util.Objects; -import java.util.concurrent.atomic.AtomicReference; @Snippet("generator") @Accessors(chain = true) @@ -58,7 +52,6 @@ import java.util.concurrent.atomic.AtomicReference; @Description("A noise generator") @Data public class IrisNoiseGenerator { - private static final int GENERATOR_CACHE_SIZE = 32; private static final long GENERATOR_SEED_SALT = 33_955_677L; private static final int MINIMUM_FRACTURE_DEPTH = 4; private static final int MAXIMUM_FRACTURE_NODES = 32; @@ -67,13 +60,6 @@ public class IrisNoiseGenerator { static final int Z_AXIS = 1; private static final ThreadLocal FRACTURE_SAMPLES = ThreadLocal.withInitial(FractureSamples::new); - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private final transient LazyBoundedCache generators = - new LazyBoundedCache<>(GENERATOR_CACHE_SIZE); - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private final transient AtomicReference recentGenerator = new AtomicReference<>(); @MinNumber(0.0001) @Description("The coordinate input zoom") private double zoom = 1; @@ -118,43 +104,28 @@ public class IrisNoiseGenerator { this.enabled = enabled; } - CNG getGenerator(long superSeed, IrisData data, Engine engine) { - long generatorSeed = superSeed + GENERATOR_SEED_SALT - seed; - CachedGenerator recent = recentGenerator.get(); - if (recent != null && recent.key.matches(data, engine, generatorSeed)) { - return recent.generator; - } + CNG getGenerator(long superSeed, PackRuntime runtime) { + return runtime.noiseLayerGenerator(this, superSeed + GENERATOR_SEED_SALT - seed); + } - GeneratorKey key = new GeneratorKey(data, engine, generatorSeed); - CNG generator = generators.computeIfAbsent(key, - ignored -> style.createForLayer(new RNG(generatorSeed), data, octaves, engine)); - if (generator != null) { - recentGenerator.set(new CachedGenerator(key, generator)); - } - return generator; + /** Builds this layer's generator for one derived seed; {@link PackRuntime} shares the result. */ + public CNG buildGenerator(long generatorSeed, PackRuntime runtime) { + return style.createForLayer(new RNG(generatorSeed), runtime, octaves); } public double getMax() { return getOffsetY() + opacity; } - public double getNoise(long superSeed, double xv, double zv, IrisData data) { - if (!enabled) { - return offsetY; - } - - return getNoise(superSeed, xv, zv, data, data == null ? null : data.getEngine()); - } - - double getNoise(long superSeed, double xv, double zv, IrisData data, Engine engine) { - return getNoiseForAxis(superSeed, xv, zv, data, engine, X_AXIS); + public double getNoise(long superSeed, double xv, double zv, PackRuntime runtime) { + return getNoiseForAxis(superSeed, xv, zv, runtime, X_AXIS); } /** * This layer read as the fracture of one axis. Each axis samples this layer's generator reseeded for that axis at * the same coordinates, so the x and z warps are uncorrelated instead of mirror images of each other. */ - private double getNoiseForAxis(long superSeed, double xv, double zv, IrisData data, Engine engine, int axis) { + private double getNoiseForAxis(long superSeed, double xv, double zv, PackRuntime runtime, int axis) { if (!enabled) { return offsetY; } @@ -164,7 +135,7 @@ public class IrisNoiseGenerator { if (!samples.active) { samples.active = true; try { - if (samples.prepare(this, superSeed, data, engine)) { + if (samples.prepare(this, superSeed, runtime)) { return samples.sample(xv, zv, axis); } } finally { @@ -180,13 +151,13 @@ public class IrisNoiseGenerator { for (IrisNoiseGenerator i : fracture) { if (i.isEnabled()) { double fractureOffset = i.getOpacity() / 2D; - x += i.getNoiseForAxis(superSeed + seed + g, xv, zv, data, engine, X_AXIS) - fractureOffset; - z += i.getNoiseForAxis(superSeed + seed + g, xv, zv, data, engine, Z_AXIS) - fractureOffset; + x += i.getNoiseForAxis(superSeed + seed + g, xv, zv, runtime, X_AXIS) - fractureOffset; + z += i.getNoiseForAxis(superSeed + seed + g, xv, zv, runtime, Z_AXIS) - fractureOffset; } g += 819; } - return sample(getGenerator(superSeed, data, engine).reseededForAxis(axis), x, z); + return sample(getGenerator(superSeed, runtime).reseededForAxis(axis), x, z); } boolean supportsBatch() { @@ -210,11 +181,11 @@ public class IrisNoiseGenerator { return true; } - NoiseLayerProgram compileProgram(long superSeed, IrisData data, Engine engine) { - return compileProgram(superSeed, data, engine, false); + NoiseLayerProgram compileProgram(long superSeed, PackRuntime runtime) { + return compileProgram(superSeed, runtime, false); } - private NoiseLayerProgram compileProgram(long superSeed, IrisData data, Engine engine, boolean readAsFracture) { + private NoiseLayerProgram compileProgram(long superSeed, PackRuntime runtime, boolean readAsFracture) { if (!enabled) { return NoiseLayerProgram.disabled(this); } @@ -230,12 +201,12 @@ public class IrisNoiseGenerator { int compiled = 0; for (IrisNoiseGenerator child : fracture) { if (child.isEnabled()) { - children[compiled] = child.compileProgram(superSeed + seed + salt, data, engine, true); + children[compiled] = child.compileProgram(superSeed + seed + salt, runtime, true); offsets[compiled++] = child.getOpacity() / 2D; } salt += 819; } - CNG generator = Objects.requireNonNull(getGenerator(superSeed, data, engine), "Noise layer generator"); + CNG generator = Objects.requireNonNull(getGenerator(superSeed, runtime), "Noise layer generator"); NoiseProgram zAxisProgram = readAsFracture ? NoiseProgram.compile2D(generator.reseededForAxis(Z_AXIS)) : null; return NoiseLayerProgram.of(this, NoiseProgram.compile2D(generator), zAxisProgram, children, offsets); } @@ -311,54 +282,19 @@ public class IrisNoiseGenerator { return false; } - private static final class GeneratorKey { - private final IrisData data; - private final Engine engine; - private final long seed; - - private GeneratorKey(IrisData data, Engine engine, long seed) { - this.data = data; - this.engine = engine; - this.seed = seed; - } - - private boolean matches(IrisData data, Engine engine, long seed) { - return this.data == data && this.engine == engine && this.seed == seed; - } - - @Override - public boolean equals(Object object) { - if (this == object) { - return true; - } - if (!(object instanceof GeneratorKey other)) { - return false; - } - return data == other.data && engine == other.engine && seed == other.seed; - } - - @Override - public int hashCode() { - int result = System.identityHashCode(data); - result = 31 * result + System.identityHashCode(engine); - result = 31 * result + Long.hashCode(seed); - return result; - } - } - private static final class FractureSamples { private final IrisNoiseGenerator[] nodes = new IrisNoiseGenerator[MAXIMUM_FRACTURE_NODES]; private final CNG[] generators = new CNG[MAXIMUM_FRACTURE_NODES]; private int size; private boolean active; - private boolean prepare(IrisNoiseGenerator node, long superSeed, IrisData data, Engine engine) { + private boolean prepare(IrisNoiseGenerator node, long superSeed, PackRuntime runtime) { while (size < MAXIMUM_FRACTURE_NODES) { if (node.getClass() != IrisNoiseGenerator.class || !node.enabled || !node.hasPureStyle() || node.fracture.size() > 1) { return false; } - CNG generator = node.getGenerator(superSeed, data, engine); + CNG generator = node.getGenerator(superSeed, runtime); if (!isPureGenerator(generator)) { return false; } @@ -404,14 +340,4 @@ public class IrisNoiseGenerator { active = false; } } - - private static final class CachedGenerator { - private final GeneratorKey key; - private final CNG generator; - - private CachedGenerator(GeneratorKey key, CNG generator) { - this.key = key; - this.generator = generator; - } - } } diff --git a/core/src/main/java/art/arcane/iris/generation/noise/IrisShapedGeneratorStyle.java b/core/src/main/java/art/arcane/iris/generation/noise/IrisShapedGeneratorStyle.java index 494935f0c..07073c043 100644 --- a/core/src/main/java/art/arcane/iris/generation/noise/IrisShapedGeneratorStyle.java +++ b/core/src/main/java/art/arcane/iris/generation/noise/IrisShapedGeneratorStyle.java @@ -18,7 +18,7 @@ package art.arcane.iris.generation.noise; -import art.arcane.iris.pack.loading.IrisData; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.volmlib.util.documentation.Description; import art.arcane.iris.pack.schema.annotation.MaxNumber; import art.arcane.iris.pack.schema.annotation.MinNumber; @@ -63,16 +63,16 @@ public class IrisShapedGeneratorStyle { this.generator = new IrisGeneratorStyle(style); } - public double get(RNG rng, IrisData data, double... dim) { - return generator.create(rng, data).fitDouble(min, max, dim); + public double get(RNG rng, PackRuntime runtime, double... dim) { + return generator.create(rng, runtime).fitDouble(min, max, dim); } - public double get(RNG rng, IrisData data, double x, double z) { - return generator.create(rng, data).fitDouble(min, max, x, z); + public double get(RNG rng, PackRuntime runtime, double x, double z) { + return generator.create(rng, runtime).fitDouble(min, max, x, z); } - public double get(RNG rng, IrisData data, double x, double y, double z) { - return generator.create(rng, data).fitDouble(min, max, x, y, z); + public double get(RNG rng, PackRuntime runtime, double x, double y, double z) { + return generator.create(rng, runtime).fitDouble(min, max, x, y, z); } public boolean isFlat() { diff --git a/core/src/main/java/art/arcane/iris/generation/noise/IrisStyledRange.java b/core/src/main/java/art/arcane/iris/generation/noise/IrisStyledRange.java index 448e5a562..91a0ebbef 100644 --- a/core/src/main/java/art/arcane/iris/generation/noise/IrisStyledRange.java +++ b/core/src/main/java/art/arcane/iris/generation/noise/IrisStyledRange.java @@ -18,7 +18,7 @@ package art.arcane.iris.generation.noise; -import art.arcane.iris.pack.loading.IrisData; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.volmlib.util.documentation.Description; import art.arcane.iris.pack.schema.annotation.Snippet; import art.arcane.volmlib.util.math.M; @@ -46,7 +46,7 @@ public class IrisStyledRange { @Description("The style to pick the range") private IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.STATIC); - public double get(RNG rng, double x, double z, IrisData data) { + public double get(RNG rng, double x, double z, PackRuntime runtime) { if (min == max) { return min; } @@ -55,11 +55,11 @@ public class IrisStyledRange { return M.lerp(min, max, 0.5); } - return style.create(rng, data).fitDouble(min, max, x, z); + return style.create(rng, runtime).fitDouble(min, max, x, z); } - public ProceduralStream stream(RNG rng, IrisData data) { - return ProceduralStream.of((x, z) -> get(rng, x, z, data), Interpolated.DOUBLE); + public ProceduralStream stream(RNG rng, PackRuntime runtime) { + return ProceduralStream.of((x, z) -> get(rng, x, z, runtime), Interpolated.DOUBLE); } public boolean isFlat() { diff --git a/core/src/main/java/art/arcane/iris/generation/runtime/DimensionStackContext.java b/core/src/main/java/art/arcane/iris/generation/runtime/DimensionStackContext.java index 19a165c47..898b54cac 100644 --- a/core/src/main/java/art/arcane/iris/generation/runtime/DimensionStackContext.java +++ b/core/src/main/java/art/arcane/iris/generation/runtime/DimensionStackContext.java @@ -133,7 +133,7 @@ public final class DimensionStackContext { upper.getDimension().getLoadKey() ); RNG seamRng = new RNG(engine.getSeedManager().getTerrain() ^ salt); - CNG seamNoise = style.create(seamRng, engine.getData(), engine); + CNG seamNoise = style.create(seamRng, PackRuntime.of(engine, engine.getData())); int amplitude = blend.getAmplitude(); samplers.add((x, z) -> clampSeamOffset( seamNoise.fitDouble(-amplitude, amplitude, x, z), amplitude)); diff --git a/core/src/main/java/art/arcane/iris/generation/runtime/DimensionTerrainContext.java b/core/src/main/java/art/arcane/iris/generation/runtime/DimensionTerrainContext.java index d61c4deae..eed52c3ae 100644 --- a/core/src/main/java/art/arcane/iris/generation/runtime/DimensionTerrainContext.java +++ b/core/src/main/java/art/arcane/iris/generation/runtime/DimensionTerrainContext.java @@ -154,6 +154,7 @@ public final class DimensionTerrainContext implements DataProvider { resolvedData = engine.getData(); } IrisData dimensionData = resolvedData; + PackRuntime dimensionRuntime = PackRuntime.of(engine, dimensionData); IrisImageMapRuntime imageMapRuntime = IrisImageMapRuntime.compile( dimensionData, dimension, @@ -219,7 +220,7 @@ public final class DimensionTerrainContext implements DataProvider { } ProceduralStream regionStyleStream = dimension.getRegionStyle() - .create(rng.nextParallelRNG(883), dimensionData).stream() + .create(rng.nextParallelRNG(883), dimensionRuntime).stream() .zoom(dimension.getRegionZoom()); KList regionPool = new KList<>(); for (IrisRegion region : dimensionData.getRegionLoader().loadAll(dimension.getRegions())) { @@ -238,7 +239,7 @@ public final class DimensionTerrainContext implements DataProvider { .convertAware2D((region, x, z) -> mappedRegion(imageMapRuntime, region, x, z)), cachePrefix + "ImageMappedRegionStream", engine, cacheSize) : proceduralRegionStream; Map>> preparedBiomeStreams = - compileInferredBiomeStreams(dimension, dimensionData, rng, preparedRegions); + compileInferredBiomeStreams(dimension, dimensionRuntime, rng, preparedRegions); ProceduralStream landBiomeStream = regionStream .convert(region -> IrisComplex.preparedInferredBiomeStream( @@ -259,7 +260,7 @@ public final class DimensionTerrainContext implements DataProvider { inferredStreams.put(InferredType.SHORE, shoreBiomeStream); ProceduralStream bridgeStream = focusBiome == null - ? ContinentGenerator.create(dimension, rng, dimensionData).stream() + ? ContinentGenerator.create(dimension, rng, dimensionRuntime).stream() .convert(value -> value >= dimension.getLandChance() ? InferredType.SEA : InferredType.LAND) @@ -277,7 +278,7 @@ public final class DimensionTerrainContext implements DataProvider { : inferredStreams.get(InferredType.LAND).get(x, z); }) .convertAware2D((biome, x, z) -> implode( - biome, x, z, rng, dataProvider, childSelectionPlans, 3)) + biome, x, z, rng, dimensionRuntime, dataProvider, childSelectionPlans, 3)) : ProceduralStream.of( (x, z) -> focusBiome, Interpolated.of(value -> 0D, value -> focusBiome) @@ -293,7 +294,7 @@ public final class DimensionTerrainContext implements DataProvider { : ProceduralStream.ofDouble((x, z) -> { double value = 0D; for (IrisShapedGeneratorStyle style : overlayNoise) { - value += style.get(rng, dimensionData, x, z); + value += style.get(rng, dimensionRuntime, x, z); } return value; }); @@ -340,6 +341,7 @@ public final class DimensionTerrainContext implements DataProvider { } }); interpolatedHeight += IrisComplex.averageGeneratorHeights( + dimensionRuntime, groupGenerators, sampledBounds.min(), sampledBounds.max(), @@ -377,7 +379,7 @@ public final class DimensionTerrainContext implements DataProvider { ); return resolvedBiome == baseBiome ? baseBiome - : implode(resolvedBiome, x, z, rng, dataProvider, childSelectionPlans, 3); + : implode(resolvedBiome, x, z, rng, dimensionRuntime, dataProvider, childSelectionPlans, 3); }), cachePrefix + "ImageMappedFinalBiomeStream", engine, cacheSize) : GenerationStreams.cache2D(ProceduralStream.of( (x, z) -> focusBiome, @@ -394,19 +396,19 @@ public final class DimensionTerrainContext implements DataProvider { Terrain3DRuntime terrain3D = !terrain3DEnabled ? null : new Terrain3DRuntime( new Terrain3DRuntime.Sources(heightStream::getDouble, finalBiomeStream::get), new Terrain3DRuntime.Options(engine.getSeedManager().getTerrain() ^ seedOffset, - localHeight, fluidHeight, dimensionData, true, Math.max(4096, cacheSize)) + localHeight, fluidHeight, dimensionRuntime, true, Math.max(4096, cacheSize)) ); ProceduralStream shapedHeightStream = terrain3D == null ? heightStream : GenerationStreams.cache2DDouble(ProceduralStream.ofDouble((x, z) -> shapedHeight(terrain3D, x, z)), cachePrefix + "Terrain3DHeightStream", engine, cacheSize); ProceduralStream slopeStream = GenerationStreams.cache2DDouble(shapedHeightStream.slope(3), cachePrefix + "SlopeStream", engine, cacheSize); ProceduralStream rockStream = dimension.getRockPalette() - .getLayerGenerator(rng.nextParallelRNG(45), dimensionData).stream() + .getLayerGenerator(rng.nextParallelRNG(45), dimensionRuntime).stream() .select(dimension.getRockPalette().getBlockData(dimensionData)); FluidBlockSampler fluidBlockSampler; if (includeFluid) { ProceduralStream fluidStream = dimension.getFluidPalette() - .getLayerGenerator(rng.nextParallelRNG(78), dimensionData).stream() + .getLayerGenerator(rng.nextParallelRNG(78), dimensionRuntime).stream() .select(dimension.getFluidPalette().getBlockData(dimensionData)); fluidBlockSampler = fluidStream::get; } else { @@ -505,7 +507,7 @@ public final class DimensionTerrainContext implements DataProvider { private static Map>> compileInferredBiomeStreams( IrisDimension dimension, - IrisData data, + PackRuntime runtime, RNG rng, Iterable regions ) { @@ -517,11 +519,11 @@ public final class DimensionTerrainContext implements DataProvider { } EnumMap> streams = new EnumMap<>(InferredType.class); streams.put(InferredType.LAND, createInferredBiomeStream( - dimension, data, rng, region, InferredType.LAND)); + dimension, runtime, rng, region, InferredType.LAND)); streams.put(InferredType.SEA, createInferredBiomeStream( - dimension, data, rng, region, InferredType.SEA)); + dimension, runtime, rng, region, InferredType.SEA)); streams.put(InferredType.SHORE, createInferredBiomeStream( - dimension, data, rng, region, InferredType.SHORE)); + dimension, runtime, rng, region, InferredType.SHORE)); compiled.put(region, Collections.unmodifiableMap(streams)); } return Collections.unmodifiableMap(compiled); @@ -529,29 +531,29 @@ public final class DimensionTerrainContext implements DataProvider { private static ProceduralStream createInferredBiomeStream( IrisDimension dimension, - IrisData data, + PackRuntime runtime, RNG rng, IrisRegion region, InferredType type ) { return switch (type) { case LAND -> dimension.getLandBiomeStyle() - .create(rng.nextParallelRNG(InferredType.LAND.ordinal()), data).stream() + .create(rng.nextParallelRNG(InferredType.LAND.ordinal()), runtime).stream() .zoom(dimension.getBiomeZoom()) .zoom(dimension.getLandZoom()) .zoom(region.getLandBiomeZoom()) - .selectRarity(loadInferredBiomes(data, region.getLandBiomes(), InferredType.LAND)); + .selectRarity(loadInferredBiomes(runtime.data(), region.getLandBiomes(), InferredType.LAND)); case SEA -> dimension.getSeaBiomeStyle() - .create(rng.nextParallelRNG(InferredType.SEA.ordinal()), data).stream() + .create(rng.nextParallelRNG(InferredType.SEA.ordinal()), runtime).stream() .zoom(dimension.getBiomeZoom()) .zoom(dimension.getSeaZoom()) .zoom(region.getSeaBiomeZoom()) - .selectRarity(loadInferredBiomes(data, region.getSeaBiomes(), InferredType.SEA)); + .selectRarity(loadInferredBiomes(runtime.data(), region.getSeaBiomes(), InferredType.SEA)); case SHORE -> dimension.getShoreBiomeStyle() - .create(rng.nextParallelRNG(InferredType.SHORE.ordinal()), data).stream() + .create(rng.nextParallelRNG(InferredType.SHORE.ordinal()), runtime).stream() .zoom(dimension.getBiomeZoom()) .zoom(region.getShoreBiomeZoom()) - .selectRarity(loadInferredBiomes(data, region.getShoreBiomes(), InferredType.SHORE)); + .selectRarity(loadInferredBiomes(runtime.data(), region.getShoreBiomes(), InferredType.SHORE)); default -> throw new IllegalArgumentException("Unsupported stacked terrain biome type: " + type); }; } @@ -594,6 +596,7 @@ public final class DimensionTerrainContext implements DataProvider { double x, double z, RNG rng, + PackRuntime runtime, DataProvider dataProvider, Map childSelectionPlans, int remainingDepth @@ -621,7 +624,7 @@ public final class DimensionTerrainContext implements DataProvider { } IrisBiome selected = selectionPlan.select( - biome.getChildrenGenerator(rng, 123, biome.getChildShrinkFactor()), x, z); + biome.getChildrenGenerator(runtime, rng, 123, biome.getChildShrinkFactor()), x, z); if (selected == null) { return biome; } @@ -630,6 +633,7 @@ public final class DimensionTerrainContext implements DataProvider { x, z, rng, + runtime, dataProvider, childSelectionPlans, remainingDepth - 1 diff --git a/core/src/main/java/art/arcane/iris/generation/runtime/Engine.java b/core/src/main/java/art/arcane/iris/generation/runtime/Engine.java index 8bf0cec7c..3b8a9beb3 100644 --- a/core/src/main/java/art/arcane/iris/generation/runtime/Engine.java +++ b/core/src/main/java/art/arcane/iris/generation/runtime/Engine.java @@ -85,6 +85,9 @@ import java.util.stream.Collectors; public interface Engine extends DataProvider, Fallible, BlockUpdater, Renderer, Hotloadable { IrisComplex getComplex(); + /** The runtime objects this engine derived from its pack, or null while no runtime is active. */ + PackRuntime getPackRuntime(); + default BiomeEnvironment getBiomeEnvironment(int x, int y, int z) { return new BiomeEnvironment(0L, getBiome(x, y, z), getRegion(x, y, z), getDimension(), getData()); } diff --git a/core/src/main/java/art/arcane/iris/generation/runtime/EngineHotloader.java b/core/src/main/java/art/arcane/iris/generation/runtime/EngineHotloader.java index 7f33bc846..5800429be 100644 --- a/core/src/main/java/art/arcane/iris/generation/runtime/EngineHotloader.java +++ b/core/src/main/java/art/arcane/iris/generation/runtime/EngineHotloader.java @@ -76,6 +76,7 @@ final class EngineHotloader { engine.sealForTransition("complex hotload", false); engine.prepareRuntimeHotload(); assembly = new RuntimeAssembly( + engine, RuntimeAssembly.nextRuntimeId(), previousGeneration.target(), previousGeneration.mantleStorageDirectory(), @@ -94,6 +95,7 @@ final class EngineHotloader { GenerationRuntime nextGeneration = previousGeneration.withComplex( assembly.cacheId, assembly.complex, + assembly.packRuntime, assembly.upperContext, assembly.dimensionStackContext, biomeMaxes); diff --git a/core/src/main/java/art/arcane/iris/generation/runtime/EngineRuntimeBuilder.java b/core/src/main/java/art/arcane/iris/generation/runtime/EngineRuntimeBuilder.java index 4f96d6f60..ae349ede3 100644 --- a/core/src/main/java/art/arcane/iris/generation/runtime/EngineRuntimeBuilder.java +++ b/core/src/main/java/art/arcane/iris/generation/runtime/EngineRuntimeBuilder.java @@ -88,6 +88,7 @@ final class EngineRuntimeBuilder { PreparedHydrologyCacheIdentity cacheIdentity ) { RuntimeAssembly assembly = new RuntimeAssembly( + engine, RuntimeAssembly.nextRuntimeId(), runtimeTarget, mantleStorageDirectory, @@ -167,6 +168,7 @@ final class EngineRuntimeBuilder { TransitionGenerationPlan transitionPlan ) { RuntimeAssembly assembly = new RuntimeAssembly( + engine, RuntimeAssembly.nextRuntimeId(), runtimeTarget, mantleStorageDirectory, @@ -421,6 +423,7 @@ final class EngineRuntimeBuilder { final GenerationKernelRegistry.RuntimeKernel runtimeKernel; final SeedManager seedManager; final TransitionGenerationPlan transitionPlan; + final PackRuntime packRuntime; static int nextRuntimeId() { return RUNTIME_IDS.incrementAndGet(); @@ -435,8 +438,9 @@ final class EngineRuntimeBuilder { CompletableFuture hash32; boolean ownsMantle; - RuntimeAssembly(int cacheId, EngineTarget target) { + RuntimeAssembly(Engine engine, int cacheId, EngineTarget target) { this( + engine, cacheId, target, null, @@ -444,8 +448,9 @@ final class EngineRuntimeBuilder { null); } - RuntimeAssembly(int cacheId, EngineTarget target, Path mantleStorageDirectory) { + RuntimeAssembly(Engine engine, int cacheId, EngineTarget target, Path mantleStorageDirectory) { this( + engine, cacheId, target, mantleStorageDirectory, @@ -454,6 +459,7 @@ final class EngineRuntimeBuilder { } RuntimeAssembly( + Engine engine, int cacheId, EngineTarget target, Path mantleStorageDirectory, @@ -469,6 +475,7 @@ final class EngineRuntimeBuilder { this.seedManager = this.runtimeKernel.createSeedManager(target.getWorld().getRawWorldSeed()); this.kernelVersion = this.runtimeKernel.version(); this.transitionPlan = transitionPlan; + this.packRuntime = PackRuntime.forEngine(engine, target.getData()); } GenerationRuntime freezeGeneration(BiomeMaxes biomeMaxes) { @@ -485,6 +492,7 @@ final class EngineRuntimeBuilder { seedManager, transitionPlan, complex, + packRuntime, upperContext, dimensionStackContext, mode, diff --git a/core/src/main/java/art/arcane/iris/generation/runtime/EngineShutdownSequence.java b/core/src/main/java/art/arcane/iris/generation/runtime/EngineShutdownSequence.java index b995fde29..650082821 100644 --- a/core/src/main/java/art/arcane/iris/generation/runtime/EngineShutdownSequence.java +++ b/core/src/main/java/art/arcane/iris/generation/runtime/EngineShutdownSequence.java @@ -18,6 +18,10 @@ package art.arcane.iris.generation.runtime; +import art.arcane.iris.structure.nativegen.NativeStructureVolumeIndex; +import art.arcane.iris.structure.placement.StructureReachability; +import art.arcane.iris.structure.placement.StructurePlacementScope; +import art.arcane.iris.structure.placement.IrisStructureLocator; import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.generation.runtime.EngineBackgroundTasks.BackgroundTaskDrain; import art.arcane.iris.generation.runtime.EngineRuntimeBuilder.RuntimeAssembly; @@ -180,6 +184,7 @@ final class EngineShutdownSequence { engine.closed = true; engine.lifecycleState = LifecycleState.CLOSED; } + failure = appendFailure(failure, runCleanup(null, this::releaseStructureRegistries)); IrisLogging.debug("Engine Fully Shutdown!"); } } @@ -207,6 +212,15 @@ final class EngineShutdownSequence { throw new IllegalStateException("Iris engine shutdown remains incomplete after cleanup failures.", failure); } + /** Engine-keyed structure registries hold only live engines, so a closed engine removes itself from each one. */ + private void releaseStructureRegistries() { + NativeStructureOwnershipStore.release(engine); + IrisStructureLocator.invalidate(engine); + StructurePlacementScope.invalidate(engine); + StructureReachability.invalidate(engine); + NativeStructureVolumeIndex.uninstall(engine); + } + void cleanupFailedConstruction(Throwable original) { engine.getClosing().set(true); engine.backgroundTasks.closeBackgroundTaskAdmission(); @@ -251,6 +265,7 @@ final class EngineShutdownSequence { cleanupFailure = releaseGenerationAdmissions(cleanupFailure); if (generationAdmissions.isEmpty()) { engine.closed = true; + cleanupFailure = appendFailure(cleanupFailure, runCleanup(null, this::releaseStructureRegistries)); } } } diff --git a/core/src/main/java/art/arcane/iris/generation/runtime/EngineThreadState.java b/core/src/main/java/art/arcane/iris/generation/runtime/EngineThreadState.java index c9597b27f..98982bb66 100644 --- a/core/src/main/java/art/arcane/iris/generation/runtime/EngineThreadState.java +++ b/core/src/main/java/art/arcane/iris/generation/runtime/EngineThreadState.java @@ -23,29 +23,17 @@ import art.arcane.iris.generation.runtime.IrisEngine.BiomeEnvironmentBinding; import art.arcane.iris.generation.runtime.IrisEngine.GenerationRuntimeBinding; import art.arcane.iris.generation.runtime.IrisEngine.GenerationRuntimeScope; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReferenceArray; - /** * Every per-thread engine binding (runtime assembly, biome environment, generation runtime scope) in one frame. * The engine getters run on generation hot paths, where a ThreadLocal lookup probes long collision chains in the - * workers' crowded thread-local maps. Frames therefore live in a table indexed by thread id and owned by their - * thread; a frame whose slot is taken by another thread falls back to a ThreadLocal. + * workers' crowded thread-local maps. Frames therefore live in thread slots the engine owns, so a closed engine + * leaves nothing behind on its pooled workers. */ final class EngineThreadState { - private static final int SLOTS = 256; - - private final AtomicReferenceArray slots = new AtomicReferenceArray<>(SLOTS); - private final ThreadLocal overflow = new ThreadLocal<>(); - private final AtomicInteger overflowFrames = new AtomicInteger(); + private final ThreadSlots frames = ThreadSlots.bindings(); Frame current() { - Thread thread = Thread.currentThread(); - Frame frame = slots.getPlain(slot(thread)); - if (frame != null && frame.owner == thread) { - return frame; - } - return overflowFrames.get() == 0 ? null : overflow.get(); + return frames.get(); } GenerationRuntimeBinding binding() { @@ -122,13 +110,8 @@ final class EngineThreadState { if (frame != null) { return frame; } - Thread thread = Thread.currentThread(); - frame = new Frame(thread); - if (!slots.compareAndSet(slot(thread), null, frame)) { - frame.overflow = true; - overflow.set(frame); - overflowFrames.incrementAndGet(); - } + frame = new Frame(); + frames.set(frame); return frame; } @@ -136,27 +119,12 @@ final class EngineThreadState { if (frame.assembly != null || frame.environment != null || frame.binding != null) { return; } - if (frame.overflow) { - overflow.remove(); - overflowFrames.decrementAndGet(); - return; - } - slots.compareAndSet(slot(frame.owner), frame, null); - } - - private static int slot(Thread thread) { - return (int) thread.threadId() & (SLOTS - 1); + frames.remove(); } static final class Frame { - private final Thread owner; - private boolean overflow; RuntimeAssembly assembly; BiomeEnvironmentBinding environment; GenerationRuntimeBinding binding; - - private Frame(Thread owner) { - this.owner = owner; - } } } diff --git a/core/src/main/java/art/arcane/iris/generation/runtime/GenerationCacheWarmer.java b/core/src/main/java/art/arcane/iris/generation/runtime/GenerationCacheWarmer.java index 8f7217046..98a649ae0 100644 --- a/core/src/main/java/art/arcane/iris/generation/runtime/GenerationCacheWarmer.java +++ b/core/src/main/java/art/arcane/iris/generation/runtime/GenerationCacheWarmer.java @@ -48,6 +48,7 @@ public final class GenerationCacheWarmer { public static void warm(Engine engine) { long start = M.ms(); IrisData data = engine.getData(); + PackRuntime runtime = PackRuntime.of(engine, data); RNG root = new RNG(engine.getSeedManager().getComponent() + 7777L); int[] counter = {0}; List proceduralTasks = new ArrayList<>(); @@ -55,28 +56,28 @@ public final class GenerationCacheWarmer { KList biomes = engine.getAllBiomes(); biomes.sort(Comparator.comparing(IrisBiome::getLoadKey)); for (IrisBiome biome : biomes) { - warmPlacements(biome.getObjects(), root, counter, data, engine); - warmDecorators(biome.getDecorators(), engine.getSeedManager().getComponent(), counter, data); - warmOres(biome.getOres(), engine.getSeedManager().getTerrain(), counter, data); + warmPlacements(biome.getObjects(), root, counter, runtime); + warmDecorators(biome.getDecorators(), engine.getSeedManager().getComponent(), counter, runtime); + warmOres(biome.getOres(), engine.getSeedManager().getTerrain(), counter, runtime); collectProcedural(biome.getProceduralObjects(), root, counter, proceduralTasks); } KList regions = engine.getDimension().getAllRegions(engine); regions.sort(Comparator.comparing(IrisRegion::getLoadKey)); for (IrisRegion region : regions) { - warmPlacements(region.getObjects(), root, counter, data, engine); - warmOres(region.getOres(), engine.getSeedManager().getTerrain(), counter, data); + warmPlacements(region.getObjects(), root, counter, runtime); + warmOres(region.getOres(), engine.getSeedManager().getTerrain(), counter, runtime); collectProcedural(region.getProceduralObjects(), root, counter, proceduralTasks); } - warmOres(engine.getDimension().getOres(), engine.getSeedManager().getTerrain(), counter, data); + warmOres(engine.getDimension().getOres(), engine.getSeedManager().getTerrain(), counter, runtime); warmProcedural(proceduralTasks, data); IrisLogging.debug("[IrisEngine timing] cache warm " + counter[0] + " configs=" + (M.ms() - start) + "ms"); } private static void warmPlacements(KList placements, RNG root, int[] counter, - IrisData data, Engine engine) { + PackRuntime runtime) { if (placements == null) { return; } @@ -85,12 +86,12 @@ public final class GenerationCacheWarmer { continue; } RNG rng = root.nextParallelRNG(counter[0]++); - placement.getSurfaceWarp(rng, data, engine); - placement.getDensity(rng, 0, 0, data); + placement.getSurfaceWarp(rng, runtime); + placement.getDensity(rng, 0, 0, runtime); } } - private static void warmDecorators(KList decorators, long componentSeed, int[] counter, IrisData data) { + private static void warmDecorators(KList decorators, long componentSeed, int[] counter, PackRuntime runtime) { if (decorators == null) { return; } @@ -100,13 +101,13 @@ public final class GenerationCacheWarmer { } counter[0]++; RNG rng = new RNG(IrisEngineDecorator.seedForPart(componentSeed, decorator.getPartOf())); - decorator.getHeightGenerator(rng, data); - decorator.getGenerator(rng, data); - decorator.getVarianceGenerator(rng, data); + decorator.getHeightGenerator(rng, runtime); + decorator.getGenerator(rng, runtime); + decorator.getVarianceGenerator(rng, runtime); } } - private static void warmOres(KList ores, long terrainSeed, int[] counter, IrisData data) { + private static void warmOres(KList ores, long terrainSeed, int[] counter, PackRuntime runtime) { if (ores == null) { return; } @@ -115,7 +116,7 @@ public final class GenerationCacheWarmer { continue; } counter[0]++; - ore.warm(new RNG(terrainSeed), data); + ore.warm(new RNG(terrainSeed), runtime); } } diff --git a/core/src/main/java/art/arcane/iris/generation/runtime/GenerationRuntime.java b/core/src/main/java/art/arcane/iris/generation/runtime/GenerationRuntime.java index 61463574a..97bfa721b 100644 --- a/core/src/main/java/art/arcane/iris/generation/runtime/GenerationRuntime.java +++ b/core/src/main/java/art/arcane/iris/generation/runtime/GenerationRuntime.java @@ -38,6 +38,7 @@ record GenerationRuntime( SeedManager seedManager, TransitionGenerationPlan transitionPlan, IrisComplex complex, + PackRuntime packRuntime, UpperDimensionContext upperContext, DimensionStackContext dimensionStackContext, EngineMode mode, @@ -57,6 +58,7 @@ record GenerationRuntime( throw new IllegalArgumentException("Generation kernel version does not match its executable runtime."); } Objects.requireNonNull(complex, "generation complex"); + Objects.requireNonNull(packRuntime, "generation pack runtime"); Objects.requireNonNull(mode, "generation mode"); Objects.requireNonNull(mantle, "generation mantle"); mantleStorageDirectory = IrisEngineMantle.normalizeStorageDirectory(mantleStorageDirectory); @@ -70,6 +72,7 @@ record GenerationRuntime( GenerationRuntime withComplex( int nextCacheId, IrisComplex nextComplex, + PackRuntime nextPackRuntime, UpperDimensionContext nextUpperContext, DimensionStackContext nextDimensionStackContext, BiomeMaxes nextBiomeMaxes @@ -84,6 +87,7 @@ record GenerationRuntime( seedManager, transitionPlan, nextComplex, + nextPackRuntime, nextUpperContext, nextDimensionStackContext, mode, diff --git a/core/src/main/java/art/arcane/iris/generation/runtime/IrisComplex.java b/core/src/main/java/art/arcane/iris/generation/runtime/IrisComplex.java index 8441a3c44..e96d2667b 100644 --- a/core/src/main/java/art/arcane/iris/generation/runtime/IrisComplex.java +++ b/core/src/main/java/art/arcane/iris/generation/runtime/IrisComplex.java @@ -155,9 +155,9 @@ public class IrisComplex implements DataProvider { InferredType.SHORE }; @Getter(AccessLevel.NONE) - private final transient ThreadLocal gridBoundsCache = ThreadLocal.withInitial(GridBoundsCache::new); + private final transient ThreadSlots gridBoundsCache = new ThreadSlots<>(GridBoundsCache::new); @Getter(AccessLevel.NONE) - private final transient ThreadLocal effectiveChunks = ThreadLocal.withInitial(EffectiveWater.Chunks::new); + private final transient ThreadSlots effectiveChunks = new ThreadSlots<>(EffectiveWater.Chunks::new); @Getter(AccessLevel.NONE) private final int biomeBoundsSamplingStep; private transient volatile SharedCornerBounds sharedCornerBounds; @@ -200,6 +200,7 @@ public class IrisComplex implements DataProvider { private RNG rng; private double fluidHeight; private IrisData data; + private final transient PackRuntime packRuntime; private Map> generators; private ProceduralStream regionStream; private ProceduralStream regionStyleStream; @@ -325,6 +326,7 @@ public class IrisComplex implements DataProvider { this.rng = new RNG(engine.getSeedManager().getComplex()); childStyleSeed = IrisBiome.childStyleSeed(rng, 123); this.data = engine.getData(); + this.packRuntime = PackRuntime.of(engine, data); imageMapRuntime = IrisImageMapRuntime.compile(engine); double height = engine.getMaxHeight(); fluidHeight = engine.getDimension().getFluidHeight(); @@ -412,20 +414,20 @@ public class IrisComplex implements DataProvider { double value = 0D; for (IrisShapedGeneratorStyle style : overlayNoise) { - value += style.get(rng, getData(), x, z); + value += style.get(rng, packRuntime, x, z); } return value; }); bakeCache = new ChunkBakeCache(new BakeSource(), detached ? ChunkBakeCache.MINIMUM_CAPACITY : ChunkBakeCache.capacityFor(Runtime.getRuntime().maxMemory())); - rockSource = engine.getDimension().getRockPalette().getLayerGenerator(rng.nextParallelRNG(45), data).stream() + rockSource = engine.getDimension().getRockPalette().getLayerGenerator(rng.nextParallelRNG(45), packRuntime).stream() .select(engine.getDimension().getRockPalette().getBlockData(data)); rockStream = new BakedStream<>(bakeCache, BakePlane.ROCK, rockSource); - fluidSource = engine.getDimension().getFluidPalette().getLayerGenerator(rng.nextParallelRNG(78), data).stream() + fluidSource = engine.getDimension().getFluidPalette().getLayerGenerator(rng.nextParallelRNG(78), packRuntime).stream() .select(engine.getDimension().getFluidPalette().getBlockData(data)); fluidStream = new BakedStream<>(bakeCache, BakePlane.FLUID, fluidSource); - regionStyleStream = engine.getDimension().getRegionStyle().create(rng.nextParallelRNG(883), getData()).stream() + regionStyleStream = engine.getDimension().getRegionStyle().create(rng.nextParallelRNG(883), packRuntime).stream() .zoom(engine.getDimension().getRegionZoom()); regionIdentityStream = regionStyleStream.fit(Integer.MIN_VALUE, Integer.MAX_VALUE); regionSource = focusedRegions != null ? focusedRegions @@ -451,7 +453,7 @@ public class IrisComplex implements DataProvider { .convertAware2D(ProceduralStream::get); inferredStreams.put(InferredType.SHORE, shoreBiomeStream); bridgeStream = focusedBiomes != null ? focusedBiomes.convert(IrisBiome::getInferredType) : - ContinentGenerator.create(engine.getDimension(), rng, getData()).stream() + ContinentGenerator.create(engine.getDimension(), rng, packRuntime).stream() .convert((v) -> v >= engine.getDimension().getLandChance() ? InferredType.SEA : InferredType.LAND); ProceduralStream proceduralBaseBiomeStream = focusedBiomes != null ? focusedBiomes : ProceduralStream.of(this::proceduralBaseBiome, @@ -483,7 +485,7 @@ public class IrisComplex implements DataProvider { (x, z) -> baseTerrainHeightStream.getDouble(x, z), this::sampleTerrain3DBiome), new Terrain3DRuntime.Options(engine.getSeedManager().getTerrain(), engine.getHeight(), - fluidHeight, data, terrain3DEnabled, TERRAIN_COLUMN_CACHE_SIZE)); + fluidHeight, packRuntime, terrain3DEnabled, TERRAIN_COLUMN_CACHE_SIZE)); unblendedNaturalHeightStream = terrain3DEnabled ? ProceduralStream.ofDouble(this::sampleTerrain3DHeight) : baseTerrainHeightStream; @@ -1056,7 +1058,7 @@ public class IrisComplex implements DataProvider { synchronized (this) { program = terrainProgram; if (program == null) { - program = TerrainProgram.compile(frozenGenerators, terrainEngine.getSeedManager().getHeight() + 239945); + program = TerrainProgram.compile(packRuntime, frozenGenerators, terrainEngine.getSeedManager().getHeight() + 239945); terrainProgram = program; } } @@ -1174,21 +1176,21 @@ public class IrisComplex implements DataProvider { private ProceduralStream biomePickNoiseStream(IrisDimension dimension, IrisRegion region, InferredType inferredType) { return switch (inferredType) { case CAVE -> dimension.getCaveBiomeStyle() - .create(rng.nextParallelRNG(InferredType.CAVE.ordinal()), getData()).stream() + .create(rng.nextParallelRNG(InferredType.CAVE.ordinal()), packRuntime).stream() .zoom(dimension.getBiomeZoom()) .zoom(region.getCaveBiomeZoom()); case LAND -> dimension.getLandBiomeStyle() - .create(rng.nextParallelRNG(InferredType.LAND.ordinal()), getData()).stream() + .create(rng.nextParallelRNG(InferredType.LAND.ordinal()), packRuntime).stream() .zoom(dimension.getBiomeZoom()) .zoom(dimension.getLandZoom()) .zoom(region.getLandBiomeZoom()); case SEA -> dimension.getSeaBiomeStyle() - .create(rng.nextParallelRNG(InferredType.SEA.ordinal()), getData()).stream() + .create(rng.nextParallelRNG(InferredType.SEA.ordinal()), packRuntime).stream() .zoom(dimension.getBiomeZoom()) .zoom(dimension.getSeaZoom()) .zoom(region.getSeaBiomeZoom()); case SHORE -> dimension.getShoreBiomeStyle() - .create(rng.nextParallelRNG(InferredType.SHORE.ordinal()), getData()).stream() + .create(rng.nextParallelRNG(InferredType.SHORE.ordinal()), packRuntime).stream() .zoom(dimension.getBiomeZoom()) .zoom(region.getShoreBiomeZoom()); }; @@ -1308,7 +1310,7 @@ public class IrisComplex implements DataProvider { configurationName + " fluidPalette may contain only fluid blocks"); } } - return palette.getLayerGenerator(fluidRng, data).stream().select(blocks); + return palette.getLayerGenerator(fluidRng, packRuntime).stream().select(blocks); } public NativeBlockState resolveSeaFluid(double x, double z) { @@ -1961,7 +1963,7 @@ public class IrisComplex implements DataProvider { } if (program == null || program.heightSeed() != heightSeed || group >= program.groups() || program.groupSize(group) != generators.length || generators != frozenGenerators[group]) { - return averageGeneratorHeights(generators, low, high, x, z, heightSeed); + return averageGeneratorHeights(packRuntime, generators, low, high, x, z, heightSeed); } return program.average(group, BATCH_SCRATCH.get(), low, high, x, z); } @@ -2128,7 +2130,7 @@ public class IrisComplex implements DataProvider { IrisBiome biome = focusedBiomeAt(x, z); for (GeneratorGroup group : biomeBuffetGenerators.get(biome)) { NoiseBounds bounds = generatorBounds.get(group.interpolator()).get(biome).noiseBounds; - h += averageGeneratorHeights(group.generators(), bounds.min(), bounds.max(), x, z, seed + 239945); + h += averageGeneratorHeights(packRuntime, group.generators(), bounds.min(), bounds.max(), x, z, seed + 239945); } return h; } @@ -2407,6 +2409,7 @@ public class IrisComplex implements DataProvider { } static double averageGeneratorHeights( + PackRuntime runtime, IrisGenerator[] generators, double low, double high, @@ -2433,7 +2436,7 @@ public class IrisComplex implements DataProvider { GenerationCounter.GENERATOR_EVALUATIONS.add(generators.length); } for (IrisGenerator generator : generators) { - double noise = generator.getHeight(x, z, seed); + double noise = generator.getHeight(runtime, x, z, seed); if (!Double.isFinite(noise)) { throw new IllegalStateException("Terrain generator noise was not finite at " + x + "," + z + " (generator=" + generator.getLoadKey() + ", noise=" + noise @@ -2527,7 +2530,7 @@ public class IrisComplex implements DataProvider { } private IrisBiome pickChild(IrisBiome parent, double x, double z) { - CNG childCell = parent.getChildrenGenerator(childStyleSeed, parent.getChildShrinkFactor()); + CNG childCell = parent.getChildrenGenerator(packRuntime, childStyleSeed, parent.getChildShrinkFactor()); return resolveChildSelectionPlan(parent).select(childCell, x, z).withInferredType(parent.getInferredType()); } diff --git a/core/src/main/java/art/arcane/iris/generation/runtime/IrisEngine.java b/core/src/main/java/art/arcane/iris/generation/runtime/IrisEngine.java index 4cbc2a06d..ce7494c48 100644 --- a/core/src/main/java/art/arcane/iris/generation/runtime/IrisEngine.java +++ b/core/src/main/java/art/arcane/iris/generation/runtime/IrisEngine.java @@ -1424,6 +1424,17 @@ public class IrisEngine implements Engine { return complexIn(threadState.current()); } + @Override + public PackRuntime getPackRuntime() { + EngineThreadState.Frame frame = threadState.current(); + RuntimeAssembly assembly = frame == null ? null : frame.assembly; + if (assembly != null) { + return assembly.packRuntime; + } + GenerationRuntime current = selectedGenerationRuntime(frame); + return current == null ? null : current.packRuntime(); + } + private IrisComplex complexIn(EngineThreadState.Frame frame) { RuntimeAssembly assembly = frame == null ? null : frame.assembly; if (assembly != null && assembly.complex != null) { diff --git a/core/src/main/java/art/arcane/iris/generation/runtime/PackRuntime.java b/core/src/main/java/art/arcane/iris/generation/runtime/PackRuntime.java new file mode 100644 index 000000000..10a6a168a --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/runtime/PackRuntime.java @@ -0,0 +1,258 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.generation.runtime; + +import art.arcane.iris.generation.biome.BiomeRuntime; +import art.arcane.iris.generation.biome.FloatingChildRuntime; +import art.arcane.iris.generation.biome.FloatingIslandMemo; +import art.arcane.iris.generation.biome.IrisBiome; +import art.arcane.iris.generation.biome.IrisBiomePaletteLayer; +import art.arcane.iris.generation.biome.IrisFloatingChildBiomes; +import art.arcane.iris.generation.biome.PaletteLayerRuntime; +import art.arcane.iris.generation.decoration.DecoratorRuntime; +import art.arcane.iris.generation.decoration.DepositRuntime; +import art.arcane.iris.generation.decoration.IrisDecorator; +import art.arcane.iris.generation.decoration.IrisDepositGenerator; +import art.arcane.iris.generation.decoration.IrisOreBands; +import art.arcane.iris.generation.decoration.IrisOreGenerator; +import art.arcane.iris.generation.decoration.OreBandsRuntime; +import art.arcane.iris.generation.noise.ExpressionRuntime; +import art.arcane.iris.generation.noise.GeneratorRuntime; +import art.arcane.iris.generation.noise.IrisExpression; +import art.arcane.iris.generation.noise.IrisGenerator; +import art.arcane.iris.generation.noise.IrisGeneratorStyle; +import art.arcane.iris.generation.noise.IrisNoiseGenerator; +import art.arcane.iris.generation.terrain.IrisDimensionCarvingEntry; +import art.arcane.iris.generation.terrain.IrisDimensionCarvingResolver; +import art.arcane.iris.generation.terrain.IrisMaterialPalette; +import art.arcane.iris.structure.graph.StructureGraphCompilation; +import art.arcane.iris.structure.object.IrisObjectPlacement; +import art.arcane.iris.world.entity.IrisEffect; +import art.arcane.iris.pack.loading.IrisData; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.noise.CNG; +import art.arcane.volmlib.util.scheduling.ChronoLatch; + +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +/** + * The runtime objects one owner derives from pack objects: seeded generators, samplers and profiles. Pack objects are + * read-only configuration, so everything built for a seed, an engine or a world lives here and dies with the owner. + * An engine owns one per generation runtime; engine-less tools use the scope their {@link IrisData} owns. + */ +public final class PackRuntime { + private static final int STYLE_SEED_CAPACITY = 8; + private static final int NOISE_LAYER_SEED_CAPACITY = 32; + private static final int MATERIAL_PALETTE_SEED_CAPACITY = 32; + private static final int CARVING_CHILD_SEED_CAPACITY = 8; + private static final int ORE_CHANCE_SEED_CAPACITY = 32; + private static final int ORE_BANDS_SEED_CAPACITY = 8; + private static final int SURFACE_WARP_SEED_CAPACITY = 8; + + private final Engine engine; + private final IrisData data; + private final RuntimeTable foreignDataScopes; + private final RuntimeTable> styleGenerators = new RuntimeTable<>( + style -> new SeedTable<>(STYLE_SEED_CAPACITY, seed -> style.createNoCache(new RNG(seed), this))); + private final RuntimeTable> noiseLayerGenerators = new RuntimeTable<>( + layer -> new SeedTable<>(NOISE_LAYER_SEED_CAPACITY, seed -> layer.buildGenerator(seed, this))); + private final RuntimeTable> materialPaletteGenerators = new RuntimeTable<>( + palette -> new SeedTable<>(MATERIAL_PALETTE_SEED_CAPACITY, seed -> palette.createLayerGenerator(seed, this))); + private final RuntimeTable> carvingChildGenerators = new RuntimeTable<>( + entry -> new SeedTable<>(CARVING_CHILD_SEED_CAPACITY, seed -> entry.createChildrenGenerator(seed, this))); + private final RuntimeTable> oreChances = new RuntimeTable<>( + ore -> new SeedTable<>(ORE_CHANCE_SEED_CAPACITY, seed -> ore.createChance(seed, this))); + private final RuntimeTable> oreBands = new RuntimeTable<>( + bands -> new SeedTable<>(ORE_BANDS_SEED_CAPACITY, seed -> new OreBandsRuntime(bands, seed, this))); + private final RuntimeTable> surfaceWarps = new RuntimeTable<>( + placement -> new SeedTable<>(SURFACE_WARP_SEED_CAPACITY, seed -> placement.createSurfaceWarp(seed, this))); + private final ConcurrentMap structureGraphs = new ConcurrentHashMap<>(); + private final ConcurrentMap structureRuntimeOutputs = new ConcurrentHashMap<>(); + private final ThreadSlots carvingResolverStates = + new ThreadSlots<>(IrisDimensionCarvingResolver.State::new); + private final RuntimeTable effectLatches = + new RuntimeTable<>(effect -> new ChronoLatch(effect.getInterval())); + private final RuntimeTable decorators = + new RuntimeTable<>(decorator -> new DecoratorRuntime(decorator, this)); + private final RuntimeTable deposits = + new RuntimeTable<>(deposit -> new DepositRuntime(deposit, this)); + private final RuntimeTable generators = new RuntimeTable<>(GeneratorRuntime::new); + private final RuntimeTable expressions = + new RuntimeTable<>(expression -> new ExpressionRuntime(expression, this)); + private final RuntimeTable biomes = new RuntimeTable<>(biome -> new BiomeRuntime(biome, this)); + private final RuntimeTable paletteLayers = + new RuntimeTable<>(layer -> new PaletteLayerRuntime(layer, this)); + private final RuntimeTable floatingChildren = + new RuntimeTable<>(entry -> new FloatingChildRuntime(entry, this)); + private final ThreadSlots floatingIslandMemos = new ThreadSlots<>(FloatingIslandMemo::new); + + private PackRuntime(Engine engine, IrisData data) { + this.engine = engine; + this.data = data; + this.foreignDataScopes = engine == null ? null : new RuntimeTable<>(foreign -> new PackRuntime(engine, foreign)); + } + + /** The scope an engine owns for its pack; the engine creates it with each generation runtime. */ + public static PackRuntime forEngine(Engine engine, IrisData data) { + return new PackRuntime(Objects.requireNonNull(engine, "engine"), data); + } + + /** A scope for tools without an engine. A null pack is allowed for content that never loads other files. */ + public static PackRuntime standalone(IrisData data) { + return new PackRuntime(null, data); + } + + /** + * The runtime scope for work on this pack: the engine's while one is generating, otherwise the scope the pack + * data owns. Resolve it once per chunk or column and pass it down. + */ + public static PackRuntime of(Engine engine, IrisData data) { + PackRuntime engineRuntime = engine == null ? null : engine.getPackRuntime(); + if (engineRuntime == null) { + return forPack(data); + } + return engineRuntime.scopeFor(data); + } + + /** The scope a pack keeps for content baked from its own files alone, such as procedural object variants. */ + public static PackRuntime forPack(IrisData data) { + return data == null ? standalone(null) : data.standalonePackRuntime(); + } + + /** The engine's scope for its own pack. */ + public static PackRuntime of(Engine engine) { + return of(engine, engine.getData()); + } + + /** The owning engine, or null for an engine-less scope. */ + public Engine engine() { + return engine; + } + + public IrisData data() { + return data; + } + + /** + * The scope this owner keeps for another pack, such as a stacked dimension's. Pack objects resolve expressions + * and images through their own data, so runtime objects of a foreign pack must be built against it. + */ + public PackRuntime scopeFor(IrisData packData) { + if (packData == null || packData == data || foreignDataScopes == null) { + return this; + } + return foreignDataScopes.get(packData); + } + + /** Styles are shared configuration that each caller seeds itself, so a style keeps one generator per seed. */ + public CNG styleGenerator(IrisGeneratorStyle style, long seed) { + return styleGenerators.get(style).get(seed); + } + + /** Noise layers are seeded from the generator that reads them, so a layer keeps one generator per seed. */ + public CNG noiseLayerGenerator(IrisNoiseGenerator layer, long seed) { + return noiseLayerGenerators.get(layer).get(seed); + } + + /** Material palettes are seeded by the stream or decorator that reads them, so a palette keeps one generator per seed. */ + public CNG materialPaletteGenerator(IrisMaterialPalette palette, long seed) { + return materialPaletteGenerators.get(palette).get(seed); + } + + /** Carving entries pick their children from the carve seed, so an entry keeps one child generator per seed. */ + public CNG carvingChildGenerator(IrisDimensionCarvingEntry entry, long seed) { + return carvingChildGenerators.get(entry).get(seed); + } + + /** Ores are seeded by the stage that places them, so an ore keeps one chance field per seed. */ + public IrisOreGenerator.OreChance oreChance(IrisOreGenerator ore, long seed) { + return oreChances.get(ore).get(seed); + } + + /** An ore list's chance fields for one seed, resolved together so painting a column holds them directly. */ + public OreBandsRuntime oreBands(IrisOreBands bands, long seed) { + return oreBands.get(bands).get(seed); + } + + /** Object placements warp by the engine's component seed, so a placement keeps one warp generator per seed. */ + public CNG surfaceWarp(IrisObjectPlacement placement, long seed) { + return surfaceWarps.get(placement).get(seed); + } + + /** Structure graphs compile from the pack's own files, so the pack scope keeps one compilation per structure key. */ + public ConcurrentMap structureGraphs() { + return structureGraphs; + } + + /** Whether each structure's sampled assemblies always place output, keyed like {@link #structureGraphs()}. */ + public ConcurrentMap structureRuntimeOutputs() { + return structureRuntimeOutputs; + } + + /** Hotload drops the compiled structure graphs of a pack whose files changed. */ + public void forgetStructureGraphs() { + structureGraphs.clear(); + structureRuntimeOutputs.clear(); + } + + /** Carving lookups that are not handed a resolver state memoize their roots in the calling thread's state. */ + public IrisDimensionCarvingResolver.State carvingResolverState() { + return carvingResolverStates.get(); + } + + /** Every player and entity of this owner shares one interval latch per effect. */ + public ChronoLatch effectLatch(IrisEffect effect) { + return effectLatches.get(effect); + } + + public DecoratorRuntime decorator(IrisDecorator decorator) { + return decorators.get(decorator); + } + + public DepositRuntime deposit(IrisDepositGenerator deposit) { + return deposits.get(deposit); + } + + public GeneratorRuntime generator(IrisGenerator generator) { + return generators.get(generator); + } + + public ExpressionRuntime expression(IrisExpression expression) { + return expressions.get(expression); + } + + public BiomeRuntime biome(IrisBiome biome) { + return biomes.get(biome); + } + + public PaletteLayerRuntime paletteLayer(IrisBiomePaletteLayer layer) { + return paletteLayers.get(layer); + } + + public FloatingChildRuntime floatingChild(IrisFloatingChildBiomes entry) { + return floatingChildren.get(entry); + } + + /** The calling worker's floating island samples for its current chunk. */ + public FloatingIslandMemo floatingIslandMemo() { + return floatingIslandMemos.get(); + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/runtime/RuntimeTable.java b/core/src/main/java/art/arcane/iris/generation/runtime/RuntimeTable.java new file mode 100644 index 000000000..f3615563f --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/runtime/RuntimeTable.java @@ -0,0 +1,68 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.generation.runtime; + +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; + +/** + * Runtime objects of one kind keyed by the identity of the pack object they were built from. Pack types compare by + * value, so two equal configurations still get their own runtime object. A builder may resolve other runtime objects + * from the same table, so entries are built outside the map and the first one published wins. + */ +public final class RuntimeTable { + private final ConcurrentHashMap entries = new ConcurrentHashMap<>(); + private final Function builder; + + public RuntimeTable(Function builder) { + this.builder = Objects.requireNonNull(builder, "runtime builder"); + } + + public R get(C config) { + Identity key = new Identity(Objects.requireNonNull(config, "pack object")); + R existing = entries.get(key); + if (existing != null) { + return existing; + } + R built = Objects.requireNonNull(builder.apply(config), "runtime object"); + R raced = entries.putIfAbsent(key, built); + return raced == null ? built : raced; + } + + private static final class Identity { + private final Object referent; + private final int hash; + + private Identity(Object referent) { + this.referent = referent; + this.hash = System.identityHashCode(referent); + } + + @Override + public boolean equals(Object other) { + return other instanceof Identity identity && identity.referent == referent; + } + + @Override + public int hashCode() { + return hash; + } + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/runtime/SeedTable.java b/core/src/main/java/art/arcane/iris/generation/runtime/SeedTable.java new file mode 100644 index 000000000..eeff4f89f --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/runtime/SeedTable.java @@ -0,0 +1,99 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.generation.runtime; + +import java.util.LinkedHashMap; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicReferenceArray; +import java.util.function.LongFunction; + +/** + * The values one runtime object builds per seed, for pack objects that callers sample with seeds they derive + * themselves. Bounded by least-recent use; an evicted value is rebuilt from the same seed, so eviction never changes + * output. Recently used values are kept aside in seed-indexed slots because callers usually ask for the same few + * seeds many times in a row. + */ +public final class SeedTable { + private static final int SINGLE_RECENT_SLOT = 1; + + private final int capacity; + private final LongFunction builder; + private final LinkedHashMap entries; + private final AtomicReferenceArray> recent; + private final int recentMask; + + public SeedTable(int capacity, LongFunction builder) { + this(capacity, SINGLE_RECENT_SLOT, builder); + } + + /** @param recentSlots a power of two: how many seeds stay on the lock-free path at once */ + public SeedTable(int capacity, int recentSlots, LongFunction builder) { + if (capacity < 1) { + throw new IllegalArgumentException("Seed table capacity must be positive."); + } + if (recentSlots < 1 || Integer.bitCount(recentSlots) != 1) { + throw new IllegalArgumentException("Recent seed slots must be a positive power of two."); + } + this.capacity = capacity; + this.builder = Objects.requireNonNull(builder, "seed builder"); + this.entries = new LinkedHashMap<>(capacity * 2, 0.75F, true); + this.recent = new AtomicReferenceArray<>(recentSlots); + this.recentMask = recentSlots - 1; + } + + public T get(long seed) { + int slot = (int) seed & recentMask; + Recent last = recent.getAcquire(slot); + if (last != null && last.seed == seed) { + return last.value; + } + T value = stored(seed); + if (value == null) { + value = publish(seed, Objects.requireNonNull(builder.apply(seed), "seeded runtime value")); + } + recent.setRelease(slot, new Recent<>(seed, value)); + return value; + } + + private T stored(long seed) { + synchronized (entries) { + return entries.get(seed); + } + } + + private T publish(long seed, T built) { + synchronized (entries) { + T raced = entries.putIfAbsent(seed, built); + if (raced != null) { + return raced; + } + evictBeyondCapacity(); + return built; + } + } + + private void evictBeyondCapacity() { + while (entries.size() > capacity) { + entries.sequencedKeySet().removeFirst(); + } + } + + private record Recent(long seed, T value) { + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/runtime/ThreadSlots.java b/core/src/main/java/art/arcane/iris/generation/runtime/ThreadSlots.java new file mode 100644 index 000000000..9c9cd6786 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/runtime/ThreadSlots.java @@ -0,0 +1,150 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.generation.runtime; + +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicReferenceArray; +import java.util.function.Supplier; + +/** + * Per-thread values owned by the object that holds this table, typically an engine-owned runtime. Unlike a + * ThreadLocal, the values live here and not in the worker threads, so they become unreachable with their owner even + * while the pooled workers that filled them stay alive. A live thread never loses its value: a thread whose probed + * slots all belong to other live threads keeps its value in an overflow map, which drops dead threads whenever it + * takes a new one. The size therefore follows the live threads and not the worker churn. + *

+ * Owners and values sit in parallel arrays so the common lookup, a thread in its home slot, is one owner compare and + * one value read that do not depend on each other. Only the owning thread writes a slot's value, and a slot changes + * owner only once its previous owner removed its value or died, so an owner match always pairs with that owner's + * value. Until some thread has had to store away from its home slot, a thread missing from its home slot has no + * value at all, so unbound threads skip the probe too. + */ +public final class ThreadSlots { + private static final int SLOT_COUNT = 256; + private static final int SLOT_MASK = SLOT_COUNT - 1; + private static final int PROBE_LIMIT = 8; + private static final int NOT_FOUND = -1; + + private final AtomicReferenceArray owners = new AtomicReferenceArray<>(SLOT_COUNT); + private final AtomicReferenceArray values = new AtomicReferenceArray<>(SLOT_COUNT); + private final ConcurrentHashMap overflow = new ConcurrentHashMap<>(); + private final Supplier factory; + private volatile boolean storedAwayFromHome; + + /** A table whose threads each get a value from the factory on first use. */ + public ThreadSlots(Supplier factory) { + this.factory = Objects.requireNonNull(factory, "thread value factory"); + } + + private ThreadSlots() { + this.factory = null; + } + + /** A table of values each thread binds with {@link #set} and clears with {@link #remove}. */ + public static ThreadSlots bindings() { + return new ThreadSlots<>(); + } + + /** This thread's value, created by the factory on first use; null for an unbound thread of a bindings table. */ + public T get() { + Thread thread = Thread.currentThread(); + int home = home(thread); + if (owners.getPlain(home) == thread) { + return values.getPlain(home); + } + T awayFromHome = storedAwayFromHome ? getAwayFromHome(thread) : null; + if (awayFromHome != null || factory == null) { + return awayFromHome; + } + T created = factory.get(); + store(thread, created); + return created; + } + + public void set(T value) { + if (value == null) { + remove(); + return; + } + Thread thread = Thread.currentThread(); + int index = find(thread); + if (index != NOT_FOUND) { + values.set(index, value); + return; + } + if (overflow.replace(thread, value) == null) { + store(thread, value); + } + } + + public void remove() { + Thread thread = Thread.currentThread(); + int index = find(thread); + if (index != NOT_FOUND) { + values.set(index, null); + owners.set(index, null); + return; + } + if (!overflow.isEmpty()) { + overflow.remove(thread); + } + } + + private T getAwayFromHome(Thread thread) { + int index = find(thread); + if (index != NOT_FOUND) { + return values.getPlain(index); + } + return overflow.isEmpty() ? null : overflow.get(thread); + } + + private int find(Thread thread) { + int home = home(thread); + for (int probe = 0; probe < PROBE_LIMIT; probe++) { + int index = (home + probe) & SLOT_MASK; + if (owners.getPlain(index) == thread) { + return index; + } + } + return NOT_FOUND; + } + + private void store(Thread thread, T value) { + int home = home(thread); + for (int probe = 0; probe < PROBE_LIMIT; probe++) { + int index = (home + probe) & SLOT_MASK; + Thread current = owners.get(index); + if ((current == null || !current.isAlive()) && owners.compareAndSet(index, current, thread)) { + values.set(index, value); + if (probe > 0) { + storedAwayFromHome = true; + } + return; + } + } + storedAwayFromHome = true; + overflow.keySet().removeIf(owner -> !owner.isAlive()); + overflow.put(thread, value); + } + + private static int home(Thread thread) { + return (int) thread.threadId() & SLOT_MASK; + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/stage/IrisBiomeActuator.java b/core/src/main/java/art/arcane/iris/generation/stage/IrisBiomeActuator.java index 0410ac36d..c3cab9307 100644 --- a/core/src/main/java/art/arcane/iris/generation/stage/IrisBiomeActuator.java +++ b/core/src/main/java/art/arcane/iris/generation/stage/IrisBiomeActuator.java @@ -61,6 +61,7 @@ public class IrisBiomeActuator extends EngineAssignedActuator { ChunkedDataCache biomeCache = context.getBiome(); IrisComplex complex = context.getComplex(); DimensionStackContext dimensionStackContext = engine.getDimensionStackContext(); + IrisDimension dimension = getDimension(); for (int xf = 0; xf < width; xf++) { for (int zf = 0; zf < depth; zf++) { @@ -69,7 +70,7 @@ public class IrisBiomeActuator extends EngineAssignedActuator { IrisBiome biome = biomeCache.get(xf, zf); NativeBiome platformBiome = resolve(biomeKey( biome, - getDimension(), + dimension, engine, worldX, 0, diff --git a/core/src/main/java/art/arcane/iris/generation/stage/IrisCarveModifier.java b/core/src/main/java/art/arcane/iris/generation/stage/IrisCarveModifier.java index d2580b95f..342316aad 100644 --- a/core/src/main/java/art/arcane/iris/generation/stage/IrisCarveModifier.java +++ b/core/src/main/java/art/arcane/iris/generation/stage/IrisCarveModifier.java @@ -18,6 +18,7 @@ package art.arcane.iris.generation.stage; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.generation.subterrain.SubterrainCell; import art.arcane.iris.generation.subterrain.SubterrainPlanner; @@ -42,6 +43,7 @@ import art.arcane.iris.generation.mantle.TerrainMatterView; import art.arcane.iris.generation.terrain.InferredType; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.biome.IrisBiomePaletteLayer; +import art.arcane.iris.generation.biome.PaletteLayerRuntime; import art.arcane.iris.generation.decoration.IrisDecorationPart; import art.arcane.iris.generation.decoration.IrisDecorator; import art.arcane.iris.generation.terrain.IrisDimensionCarvingResolver; @@ -230,6 +232,7 @@ public class IrisCarveModifier extends EngineAssignedModifier } finally { getEngine().getMetrics().getCave().put(caveStopwatch.getMilliseconds()); mantleChunk.release(); + scratch.releaseReferences(); } } @@ -340,7 +343,7 @@ public class IrisCarveModifier extends EngineAssignedModifier int blockZ = chunkZ << 4; return new SubterrainSurfaceMaterials(planner, planner.plansForBounds(blockX - 1, blockZ - 1, blockX + 16, blockZ + 16), - getEngine().getDimension(), getComplex(), getData(), rng, getEngine().getWorld().minHeight()); + getEngine().getDimension(), getComplex(), PackRuntime.of(getEngine()), rng, getEngine().getWorld().minHeight()); } static boolean hasExplicitCarveIntent(MatterCavern cavern) { @@ -606,6 +609,9 @@ public class IrisCarveModifier extends EngineAssignedModifier private final IrisData data; private final int chunkBlockX; private final int chunkBlockZ; + private final PackRuntime wallRuntime; + private IrisBiomePaletteLayer lastWall; + private PaletteLayerRuntime lastWallRuntime; private WallPainter(Hunk output, CaveTerrainSnapshot terrain, CaveInputs inputs, Long2ObjectOpenHashMap caveBiomeCache, Map customBiomeCache, @@ -619,6 +625,7 @@ public class IrisCarveModifier extends EngineAssignedModifier this.data = data; this.chunkBlockX = chunkBlockX; this.chunkBlockZ = chunkBlockZ; + this.wallRuntime = inputs.runtime.scopeFor(data); } @Override @@ -637,11 +644,20 @@ public class IrisCarveModifier extends EngineAssignedModifier if (biome == null) { return; } - NativeBlockState wall = biome.getWall().get(rng, worldX, yy, worldZ, data); + IrisBiomePaletteLayer wallLayer = biome.getWall(); + NativeBlockState wall = wallLayer.get(rng, 0, worldX, yy, worldZ, wallLayerRuntime(wallLayer)); if (wall != null) { output.setRaw(rx, yy, rz, wall); } } + + private PaletteLayerRuntime wallLayerRuntime(IrisBiomePaletteLayer wallLayer) { + if (wallLayer != lastWall) { + lastWall = wallLayer; + lastWallRuntime = wallRuntime.paletteLayer(wallLayer); + } + return lastWallRuntime; + } } private void addInternalWallsFromMantle(CaveTerrainSnapshot terrain, CarveWallBuffer walls, CarveColumnMask[] columnMasks) { @@ -1016,13 +1032,13 @@ public class IrisCarveModifier extends EngineAssignedModifier private KList floorLayers(CaveLayerMemo layers, IrisBiome biome, int worldX, int worldZ, int floorY, CaveInputs inputs) { if (!hasHeightFreeFloorLayers(biome)) { - return biome.generateLayers(inputs.dimension, worldX, worldZ, rng, 3, floorY, inputs.data, inputs.complex); + return biome.generateLayers(inputs.dimension, worldX, worldZ, rng, 3, floorY, inputs.runtime, inputs.complex); } KList remembered = layers.floor(biome); if (remembered != null) { return remembered; } - KList blocks = biome.generateLayers(inputs.dimension, worldX, worldZ, rng, 3, floorY, inputs.data, inputs.complex); + KList blocks = biome.generateLayers(inputs.dimension, worldX, worldZ, rng, 3, floorY, inputs.runtime, inputs.complex); layers.rememberFloor(biome, blocks); return blocks; } @@ -1033,7 +1049,7 @@ public class IrisCarveModifier extends EngineAssignedModifier if (remembered != null) { return remembered; } - KList blocks = biome.generateCeilingLayers(inputs.dimension, worldX, worldZ, rng, 3, ceilingY, inputs.data, inputs.complex); + KList blocks = biome.generateCeilingLayers(inputs.dimension, worldX, worldZ, rng, 3, ceilingY, inputs.runtime, inputs.complex); layers.rememberCeiling(biome, blocks); return blocks; } @@ -1356,6 +1372,7 @@ public class IrisCarveModifier extends EngineAssignedModifier private final IrisComplex complex; private final IrisDimension dimension; private final IrisData data; + private final PackRuntime runtime; private final int height; private final IrisDimensionCarvingResolver.State state = new IrisDimensionCarvingResolver.State(); private final IrisDimensionCarvingResolver.Snapshot snapshot; @@ -1393,6 +1410,7 @@ public class IrisCarveModifier extends EngineAssignedModifier complex = engine.getComplex(); dimension = engine.getDimension(); data = engine.getData(); + runtime = PackRuntime.of(engine, data); height = engine.getHeight(); cells = SubterrainChunkCells.of(engine, chunkX, chunkZ); IrisContext context = IrisContext.get(); diff --git a/core/src/main/java/art/arcane/iris/generation/stage/IrisCarveScratch.java b/core/src/main/java/art/arcane/iris/generation/stage/IrisCarveScratch.java index aa9ebbb9a..a27cf7ebc 100644 --- a/core/src/main/java/art/arcane/iris/generation/stage/IrisCarveScratch.java +++ b/core/src/main/java/art/arcane/iris/generation/stage/IrisCarveScratch.java @@ -67,6 +67,12 @@ final class IrisCarveScratch { caveBiomeCache.clear(); customCaveBiomePresent = false; } + + /** Drops every biome, block and cavern reference so the thread's scratch pins no pack once a chunk is carved. */ + void releaseReferences() { + reset(); + layers.reset(); + } } final class CaveLayerMemo { @@ -78,6 +84,8 @@ final class CaveLayerMemo { private int ceilingCount; void reset() { + Arrays.fill(floor, 0, floorCount, null); + Arrays.fill(ceiling, 0, ceilingCount, null); floorCount = 0; ceilingCount = 0; } diff --git a/core/src/main/java/art/arcane/iris/generation/stage/IrisDecorantActuator.java b/core/src/main/java/art/arcane/iris/generation/stage/IrisDecorantActuator.java index 5d323f901..ac23c84b3 100644 --- a/core/src/main/java/art/arcane/iris/generation/stage/IrisDecorantActuator.java +++ b/core/src/main/java/art/arcane/iris/generation/stage/IrisDecorantActuator.java @@ -18,6 +18,7 @@ package art.arcane.iris.generation.stage; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.decoration.HydrologyVegetation; import art.arcane.iris.generation.decoration.IrisCeilingDecorator; import art.arcane.iris.generation.decoration.IrisSeaFloorDecorator; @@ -140,6 +141,7 @@ public class IrisDecorantActuator extends EngineAssignedActuator plans = new ArrayList<>(generators.size()); AboveTerrainHosts aboveTerrainHosts = new AboveTerrainHosts(terrain, context); + PackRuntime runtime = PackRuntime.of(getEngine(), getData()); int attempts = 0; for (int i = 0; i < generators.size(); i++) { try { - DepositPlan plan = plan(generators.get(i), rng.nextParallelRNG(seed * (i + 1L)), context); + DepositPlan plan = plan(generators.get(i), rng.nextParallelRNG(seed * (i + 1L)), context, runtime); if (plan.attempts() == 0 || footprintsMissTerrain(plan, highestSurface) || plan.generator().getPlacementScope() == IrisDepositPlacementScope.ABOVE_TERRAIN && !aboveTerrainHosts.present(plan.generator().getSurfaceClearance())) { @@ -209,7 +211,7 @@ public class IrisDepositModifier extends EngineAssignedModifier data, RNG rng, int cx, int cz, boolean safe, HeightMap he, ChunkContext context) { - DepositPlan plan = plan(k, rng, context); + DepositPlan plan = plan(k, rng, context, PackRuntime.of(getEngine(), getData())); if (plan.attempts() == 0) { return; } @@ -231,13 +233,13 @@ public class IrisDepositModifier extends EngineAssignedModifier (long) highestSurface - Math.max(0, generator.getSurfaceClearance()); } - private DepositPlan plan(IrisDepositGenerator generator, RNG rng, ChunkContext context) { + private DepositPlan plan(IrisDepositGenerator generator, RNG rng, ChunkContext context, PackRuntime runtime) { if (generator.getSpawnChance() < rng.d()) { - return new DepositPlan(generator, rng.getSeed(), false, 0); + return new DepositPlan(generator, runtime, rng.getSeed(), false, 0); } boolean ore = generator.isOre(getData()); int attempts = rng.i(generator.getMinPerChunk(), generator.getMaxPerChunk() + 1); - return new DepositPlan(generator, rng.getSeed(), ore, + return new DepositPlan(generator, runtime, rng.getSeed(), ore, attempts == 0 || surfaceBiomeMayMatch(generator, context) ? attempts : 0); } @@ -306,7 +308,7 @@ public class IrisDepositModifier extends EngineAssignedModifier seaBlocks = biome == null || fluidDepth == 0 ? null - : biome.generateSeaLayers(worldX, worldZ, rng, fluidDepth, data); + : biome.generateSeaLayers(worldX, worldZ, rng, fluidDepth, runtime); for (int y = layer.renderMaxY(); y >= layer.renderMinY(); y--) { int sourceY = y - layer.localBaseY(); @@ -256,7 +258,7 @@ public final class IrisDimensionStackActuator extends EngineAssignedActuator 0 && depth >= 2 && ceilingDepth < 2) { if (ceilingBlocks == null && biome != null) { ceilingBlocks = biome.generateCeilingLayers(dimension, worldX, worldZ, rng, - 2, ceilingY, data, null); + 2, ceilingY, runtime, null); } writeBlock(output, metadata, localX, y, localZ, ceilingBlocks != null && ceilingBlocks.hasIndex(ceilingDepth) @@ -266,7 +268,7 @@ public final class IrisDimensionStackActuator extends EngineAssignedActuator generateBottomPaletteLayers(IrisFloatingChildBiomes entry, IrisDimension dimension, double wx, double wz, RNG random, int paletteDepth, IrisData data, IrisComplex complex) { + private static KList generateBottomPaletteLayers(IrisFloatingChildBiomes entry, IrisDimension dimension, double wx, double wz, RNG random, int paletteDepth, PackRuntime runtime, IrisComplex complex) { if (entry == null || entry.getBottomPaletteMode() != FloatingBottomPaletteMode.CUSTOM || entry.getBottomPalette() == null || entry.getBottomPalette().isEmpty()) { return null; } - return generatePaletteLayers(dimension, entry.getBottomPalette(), wx, wz, random.nextParallelRNG(0xB0770B), paletteDepth, data, complex); + return generatePaletteLayers(dimension, entry.getBottomPalette(), wx, wz, random.nextParallelRNG(0xB0770B), paletteDepth, runtime, complex); } - private static KList generatePaletteLayers(IrisDimension dimension, KList layers, double wx, double wz, RNG random, int maxDepth, IrisData data, IrisComplex complex) { + private static KList generatePaletteLayers(IrisDimension dimension, KList layers, double wx, double wz, RNG random, int maxDepth, PackRuntime runtime, IrisComplex complex) { KList generated = new KList<>(); if (layers == null || layers.isEmpty() || maxDepth <= 0) { return generated; @@ -80,7 +81,7 @@ public class IrisFloatingChildBiomeModifier extends EngineAssignedModifier topBlocks = target == null ? null : target.generateLayers(dimension, wx, wz, layerRng, topPaletteDepth, surfaceY, data, complex); + KList topBlocks = target == null ? null : target.generateLayers(dimension, wx, wz, layerRng, topPaletteDepth, surfaceY, runtime, complex); if (topBlocks == null || topBlocks.isEmpty()) { physicalDepth = usesPhysicalDepth(parent, entry); topPaletteDepth = physicalDepth ? Math.max(paletteDepth, surfaceY - baseY + 1) : paletteDepth; - topBlocks = parent.generateLayers(dimension, wx, wz, layerRng, topPaletteDepth, surfaceY, data, complex); + topBlocks = parent.generateLayers(dimension, wx, wz, layerRng, topPaletteDepth, surfaceY, runtime, complex); } - KList bottomBlocks = generateBottomPaletteLayers(entry, dimension, wx, wz, layerRng, paletteDepth, data, complex); + KList bottomBlocks = generateBottomPaletteLayers(entry, dimension, wx, wz, layerRng, paletteDepth, runtime, complex); return new PaletteContext(topBlocks, bottomBlocks, B.getState("minecraft:stone"), surfaceY, physicalDepth); } @@ -230,11 +231,12 @@ public class IrisFloatingChildBiomeModifier extends EngineAssignedModifier output, boolean multicore, ChunkContext context) { int chunkHeight = output.getHeight(); IrisData data = getData(); + PackRuntime runtime = PackRuntime.of(getEngine(), data); IrisComplex complex = getComplex(); long baseSeed = getEngine().getSeedManager().getTerrain() ^ FLOATING_BASE_SEED_SALT; FloatingIslandBoundarySampler boundarySampler = context.getFloatingIslandBoundarySampler(); @@ -342,7 +345,7 @@ public class IrisFloatingChildBiomeModifier extends EngineAssignedModifier { int max = Math.abs(Math.max(h - ha, Math.max(h - hb, Math.max(h - hc, h - hd)))); for (int i = h; i > h - max; i--) { - NativeBlockState d = biome.getWall().get(rng, x + i, i + h, z + i, getData()); + NativeBlockState d = biome.getWall().get(rng, x + i, i + h, z + i, getComplex().getPackRuntime()); if (d != null) { if (isAirOrWater(x, i, z, originX, originZ, currentData)) { @@ -241,7 +241,7 @@ public class IrisPostModifier extends EngineAssignedModifier { //@done { IrisSlopeClip sc = biome.getSlab().getSlopeCondition(); - NativeBlockState d = sc.isValid(getComplex().getSlopeStream().get(x, z)) ? biome.getSlab().get(rng, x, h, z, getData()) : null; + NativeBlockState d = sc.isValid(getComplex().getSlopeStream().get(x, z)) ? biome.getSlab().get(rng, x, h, z, getComplex().getPackRuntime()) : null; if (d != null) { boolean cancel = B.isAir(d); diff --git a/core/src/main/java/art/arcane/iris/generation/stage/IrisTerrainNormalActuator.java b/core/src/main/java/art/arcane/iris/generation/stage/IrisTerrainNormalActuator.java index bf727098f..542d92e36 100644 --- a/core/src/main/java/art/arcane/iris/generation/stage/IrisTerrainNormalActuator.java +++ b/core/src/main/java/art/arcane/iris/generation/stage/IrisTerrainNormalActuator.java @@ -18,6 +18,7 @@ package art.arcane.iris.generation.stage; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.EngineAssignedActuator; import art.arcane.iris.pack.loading.IrisData; @@ -30,6 +31,7 @@ import art.arcane.iris.generation.hydrology.config.IrisHydrologyMaterials; import art.arcane.iris.generation.hydrology.raster.WaterRole; import art.arcane.iris.generation.terrain.IrisDimension; import art.arcane.iris.generation.decoration.IrisOreBands; +import art.arcane.iris.generation.decoration.OreBandsRuntime; import art.arcane.iris.generation.terrain.IrisMaterialPalette; import art.arcane.iris.generation.terrain.IrisRegion; import art.arcane.iris.generation.terrain.Terrain3DColumn; @@ -114,13 +116,13 @@ public class IrisTerrainNormalActuator extends EngineAssignedActuator= paintDepth) { return layerBlock; } - NativeBlockState painted = palette.get(rng, x, y, z, data); + NativeBlockState painted = palette.get(rng, x, y, z, runtime); return painted == null ? layerBlock : painted; } @@ -143,7 +145,7 @@ public class IrisTerrainNormalActuator extends EngineAssignedActuator waterHeadStream; private final ProceduralStream waterRoleStream; @@ -155,14 +157,14 @@ public class IrisTerrainNormalActuator extends EngineAssignedActuator rockCache; private final ChunkedDataCache fluidCache; private final UpperDimensionContext upperContext; - private final IrisOreBands dimensionSurfaceOres; - private final IrisOreBands dimensionUndergroundOres; + private final OreBandsRuntime dimensionSurfaceOres; + private final OreBandsRuntime dimensionUndergroundOres; private final NativeBlockState air; private final NativeBlockState bedrock; - private IrisOreBands biomeSurfaceOres; - private IrisOreBands regionSurfaceOres; - private IrisOreBands biomeUndergroundOres; - private IrisOreBands regionUndergroundOres; + private OreBandsRuntime biomeSurfaceOres; + private OreBandsRuntime regionSurfaceOres; + private OreBandsRuntime biomeUndergroundOres; + private OreBandsRuntime regionUndergroundOres; private int surfaceOreTop; private int surfaceOreFloor; private int undergroundOreTop; @@ -181,7 +183,7 @@ public class IrisTerrainNormalActuator extends EngineAssignedActuator he && i <= hf) { int fdepth = hf - i; if (seaFloor && fblocks == null) { - fblocks = biome.generateSeaLayers(realX, realZ, rng, role == WaterRole.INLET ? INLET_SEA_LAYERS : hf - he, data); + fblocks = biome.generateSeaLayers(realX, realZ, rng, role == WaterRole.INLET ? INLET_SEA_LAYERS : hf - he, runtime); } put(i, HydrologyFluidLayerSelector.select( fblocks, @@ -297,7 +299,7 @@ public class IrisTerrainNormalActuator extends EngineAssignedActuator 0 ? layerCeilingY + 2 : 0); @@ -310,7 +312,7 @@ public class IrisTerrainNormalActuator extends EngineAssignedActuator 0 && depth >= 2 && i - layerCeilingY < 2) { if (ceilingBlocks == null) { ceilingBlocks = biome.generateCeilingLayers(dimension, realX, realZ, rng, - 2, layerCeilingY, data, complex); + 2, layerCeilingY, runtime, complex); } int ceilingDepth = i - layerCeilingY; put(i, ceilingBlocks.hasIndex(ceilingDepth) @@ -320,7 +322,7 @@ public class IrisTerrainNormalActuator extends EngineAssignedActuator columnCache = ThreadLocal.withInitial(ColumnCache::new); + private final ThreadSlots columnCache = new ThreadSlots<>(ColumnCache::new); SubterrainPlan(Options options) { definition = Objects.requireNonNull(options.definition()); diff --git a/core/src/main/java/art/arcane/iris/generation/subterrain/SubterrainSurfaceMaterials.java b/core/src/main/java/art/arcane/iris/generation/subterrain/SubterrainSurfaceMaterials.java index d327aa81a..0907bbb5f 100644 --- a/core/src/main/java/art/arcane/iris/generation/subterrain/SubterrainSurfaceMaterials.java +++ b/core/src/main/java/art/arcane/iris/generation/subterrain/SubterrainSurfaceMaterials.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.subterrain; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.decoration.IrisDecorationPart; import art.arcane.iris.generation.decoration.IrisDecorator; @@ -22,19 +23,21 @@ public final class SubterrainSurfaceMaterials { private final IrisDimension dimension; private final IrisComplex complex; private final IrisData data; + private final PackRuntime runtime; private final RNG random; private final int minimumY; private final Map biomes = new HashMap<>(); private final Map> floorSupports = new HashMap<>(); public SubterrainSurfaceMaterials(SubterrainPlanner planner, List plans, - IrisDimension dimension, IrisComplex complex, IrisData data, + IrisDimension dimension, IrisComplex complex, PackRuntime runtime, RNG random, int minimumY) { this.planner = planner; this.plans = plans; this.dimension = dimension; this.complex = complex; - this.data = data; + this.runtime = runtime; + this.data = runtime.data(); this.random = random; this.minimumY = minimumY; } @@ -54,11 +57,11 @@ public final class SubterrainSurfaceMaterials { } NativeBlockState candidate; if (surface == Surface.WALL) { - candidate = biome.getWall().get(random, x, worldY - minimumY, z, data); + candidate = biome.getWall().get(random, x, worldY - minimumY, z, runtime); } else { KList layers = surface == Surface.FLOOR - ? biome.generateLayers(dimension, x, z, random, 1, worldY + 1 - minimumY, data, complex) - : biome.generateCeilingLayers(dimension, x, z, random, 1, worldY - 1 - minimumY, data, complex); + ? biome.generateLayers(dimension, x, z, random, 1, worldY + 1 - minimumY, runtime, complex) + : biome.generateCeilingLayers(dimension, x, z, random, 1, worldY - 1 - minimumY, runtime, complex); candidate = layers.isEmpty() ? null : layers.getFirst(); } return SubterrainRasterizer.isRetainedSolid(candidate) ? candidate : fallback; diff --git a/core/src/main/java/art/arcane/iris/generation/terrain/ContinentGenerator.java b/core/src/main/java/art/arcane/iris/generation/terrain/ContinentGenerator.java index 0d95de5ea..df01ebf2d 100644 --- a/core/src/main/java/art/arcane/iris/generation/terrain/ContinentGenerator.java +++ b/core/src/main/java/art/arcane/iris/generation/terrain/ContinentGenerator.java @@ -1,6 +1,6 @@ package art.arcane.iris.generation.terrain; -import art.arcane.iris.pack.loading.IrisData; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.noise.CNG; @@ -10,12 +10,12 @@ public final class ContinentGenerator { private ContinentGenerator() { } - public static CNG create(IrisDimension dimension, RNG parentSeedSource, IrisData packData) { - return createScaledContinentalStyleGenerator(dimension, deriveContinentSeed(parentSeedSource), packData); + public static CNG create(IrisDimension dimension, RNG parentSeedSource, PackRuntime runtime) { + return createScaledContinentalStyleGenerator(dimension, deriveContinentSeed(parentSeedSource), runtime); } - private static CNG createScaledContinentalStyleGenerator(IrisDimension dimension, RNG continentSeed, IrisData packData) { - return dimension.getContinentalStyle().createScaledGenerator(continentSeed, packData, inverseContinentZoom(dimension)); + private static CNG createScaledContinentalStyleGenerator(IrisDimension dimension, RNG continentSeed, PackRuntime runtime) { + return dimension.getContinentalStyle().createScaledGenerator(continentSeed, runtime, inverseContinentZoom(dimension)); } static RNG deriveContinentSeed(RNG parentSeedSource) { diff --git a/core/src/main/java/art/arcane/iris/generation/terrain/IrisDimension.java b/core/src/main/java/art/arcane/iris/generation/terrain/IrisDimension.java index 27c89264a..8575d4bdc 100644 --- a/core/src/main/java/art/arcane/iris/generation/terrain/IrisDimension.java +++ b/core/src/main/java/art/arcane/iris/generation/terrain/IrisDimension.java @@ -18,6 +18,7 @@ package art.arcane.iris.generation.terrain; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.world.entity.IrisSpawnGroup; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.biome.IrisBiomeCustom; @@ -68,7 +69,6 @@ import art.arcane.iris.pack.datapack.DataVersion; import art.arcane.iris.pack.datapack.IDataFixer; import art.arcane.iris.pack.datapack.IDataFixer.Dimension; import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.iris.generation.cache.LazyBoundedCache; import art.arcane.iris.world.history.GenerationRegistryContractFactory; import art.arcane.iris.pack.schema.annotation.ArrayType; import art.arcane.volmlib.util.documentation.Description; @@ -88,7 +88,6 @@ import art.arcane.volmlib.util.json.JSONArray; import art.arcane.volmlib.util.json.JSONObject; import art.arcane.volmlib.util.mantle.flag.MantleFlag; import art.arcane.volmlib.util.mantle.flag.ReservedFlag; -import art.arcane.volmlib.util.math.Position2; import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.noise.CNG; import lombok.Data; @@ -133,21 +132,11 @@ import java.util.regex.Pattern; public class IrisDimension extends IrisRegistrant { private static final Pattern RESOURCE_KEY_PATTERN = Pattern.compile("[a-z0-9_.-]+:[a-z0-9/._-]+"); - private final transient AtomicCache parallaxSize = new AtomicCache<>(); private final transient AtomicCache staticObjectLayer = new AtomicCache<>(); - private final transient AtomicCache rockLayerGenerator = new AtomicCache<>(); - private final transient AtomicCache fluidLayerGenerator = new AtomicCache<>(); - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private final transient LazyBoundedCache coordinateFractures = new LazyBoundedCache<>(8); - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private transient volatile CachedCoordinateFracture recentCoordinateFracture; private final transient AtomicCache sinr = new AtomicCache<>(); private final transient AtomicCache cosr = new AtomicCache<>(); private final transient AtomicCache rad = new AtomicCache<>(); private final transient AtomicCache undergroundSpawnTables = new AtomicCache<>(); - private final transient AtomicCache featuresUsed = new AtomicCache<>(); private final transient AtomicCache> carvingEntryIndex = new AtomicCache<>(); private final transient AtomicCache> surfaceOreCache = new AtomicCache<>(); private final transient AtomicCache> undergroundOreCache = new AtomicCache<>(); @@ -464,17 +453,17 @@ public class IrisDimension extends IrisRegistrant { carvingEntryIndex.reset(); } - public NativeBlockState generateOres(int x, int y, int z, RNG rng, IrisData data, boolean surface) { + public NativeBlockState generateOres(int x, int y, int z, RNG rng, PackRuntime runtime, boolean surface) { KList localOres = surface ? getSurfaceOres() : getUndergroundOres(); - return generateOres(localOres, x, y, z, rng, data); + return generateOres(localOres, x, y, z, rng, runtime); } - public NativeBlockState generateSurfaceOres(int x, int y, int z, RNG rng, IrisData data) { - return generateOres(getSurfaceOres(), x, y, z, rng, data); + public NativeBlockState generateSurfaceOres(int x, int y, int z, RNG rng, PackRuntime runtime) { + return generateOres(getSurfaceOres(), x, y, z, rng, runtime); } - public NativeBlockState generateUndergroundOres(int x, int y, int z, RNG rng, IrisData data) { - return generateOres(getUndergroundOres(), x, y, z, rng, data); + public NativeBlockState generateUndergroundOres(int x, int y, int z, RNG rng, PackRuntime runtime) { + return generateOres(getUndergroundOres(), x, y, z, rng, runtime); } public boolean hasSurfaceOres() { @@ -485,7 +474,7 @@ public class IrisDimension extends IrisRegistrant { return !getUndergroundOres().isEmpty(); } - private NativeBlockState generateOres(KList localOres, int x, int y, int z, RNG rng, IrisData data) { + private NativeBlockState generateOres(KList localOres, int x, int y, int z, RNG rng, PackRuntime runtime) { if (localOres.isEmpty()) { return null; } @@ -493,7 +482,7 @@ public class IrisDimension extends IrisRegistrant { int oreCount = localOres.size(); for (int oreIndex = 0; oreIndex < oreCount; oreIndex++) { IrisOreGenerator oreGenerator = localOres.get(oreIndex); - NativeBlockState ore = oreGenerator.generate(x, y, z, rng, data); + NativeBlockState ore = oreGenerator.generate(x, y, z, rng, runtime); if (ore != null) { return ore; } @@ -554,18 +543,6 @@ public class IrisDimension extends IrisRegistrant { return fluidHeight - (int) dimensionHeight.getMin(); } - public CNG getCoordFracture(RNG rng, int signature) { - long seed = rng.getSeed() + signature; - CachedCoordinateFracture recent = recentCoordinateFracture; - if (recent != null && recent.seed == seed) { - return recent.generator; - } - CNG generator = coordinateFractures.computeIfAbsent(seed, ignored -> - CNG.signature(new RNG(seed)).scale(0.012 / coordFractureZoom)); - recentCoordinateFracture = new CachedCoordinateFracture(seed, generator); - return generator; - } - public double getDimensionAngle() { return rad.aquire(() -> Math.toRadians(dimensionAngleDeg)); } @@ -1400,7 +1377,4 @@ public class IrisDimension extends IrisRegistrant { IO.writeAll(dimTypeVanilla, json); } } - - private record CachedCoordinateFracture(long seed, CNG generator) { - } } diff --git a/core/src/main/java/art/arcane/iris/generation/terrain/IrisDimensionCarvingEntry.java b/core/src/main/java/art/arcane/iris/generation/terrain/IrisDimensionCarvingEntry.java index 6fa49dbfc..1aac7ac66 100644 --- a/core/src/main/java/art/arcane/iris/generation/terrain/IrisDimensionCarvingEntry.java +++ b/core/src/main/java/art/arcane/iris/generation/terrain/IrisDimensionCarvingEntry.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.terrain; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.NoiseStyle; @@ -21,8 +22,6 @@ import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; @Snippet("dimension-carving-entry") @Accessors(chain = true) @@ -34,7 +33,6 @@ public class IrisDimensionCarvingEntry { private static final int CHILDREN_SEED_SALT = 2137; private static final double MINIMUM_CHILD_SHRINK_FACTOR = 0.0001D; private final transient AtomicCache realBiome = new AtomicCache<>(true); - private final transient Map childGenerators = new ConcurrentHashMap<>(); @Description("Stable id for this carving entry") private String id = ""; @@ -82,12 +80,12 @@ public class IrisDimensionCarvingEntry { }); } - public CNG getChildrenGenerator(long seed, IrisData data) { - return childGenerators.computeIfAbsent(deriveChildrenGeneratorSeed(seed), key -> createChildrenGenerator(key, data)); + public CNG getChildrenGenerator(long seed, PackRuntime runtime) { + return runtime.carvingChildGenerator(this, deriveChildrenGeneratorSeed(seed)); } - private CNG createChildrenGenerator(long childrenGeneratorSeed, IrisData data) { - return getChildStyle().createScaledGenerator(deriveChildStyleSeed(childrenGeneratorSeed), data, childShrinkFactor()); + public CNG createChildrenGenerator(long childrenGeneratorSeed, PackRuntime runtime) { + return getChildStyle().createScaledGenerator(deriveChildStyleSeed(childrenGeneratorSeed), runtime, childShrinkFactor()); } long deriveChildrenGeneratorSeed(long worldSeed) { diff --git a/core/src/main/java/art/arcane/iris/generation/terrain/IrisDimensionCarvingResolver.java b/core/src/main/java/art/arcane/iris/generation/terrain/IrisDimensionCarvingResolver.java index 979f8042e..8a4058d2a 100644 --- a/core/src/main/java/art/arcane/iris/generation/terrain/IrisDimensionCarvingResolver.java +++ b/core/src/main/java/art/arcane/iris/generation/terrain/IrisDimensionCarvingResolver.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.terrain; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.pack.value.IrisRange; @@ -22,8 +23,6 @@ import java.util.Map; public final class IrisDimensionCarvingResolver { private static final int MAX_CHILD_DEPTH = 32; private static final long CHILD_SEED_SALT = 0x9E3779B97F4A7C15L; - private static final ThreadLocal> THREAD_STATE = - ThreadLocal.withInitial(() -> new WeakReference<>(null)); private IrisDimensionCarvingResolver() { @@ -34,7 +33,7 @@ public final class IrisDimensionCarvingResolver { } public static IrisBiome resolveBiome(Engine engine, int worldX, int worldY, int worldZ, State state) { - State resolvedState = state == null ? threadState() : state; + State resolvedState = state == null ? threadState(engine) : state; IrisData data = resolvedState.bind(engine); IrisDimensionCarvingEntry root = resolveBoundRootEntry(engine, worldY, data, resolvedState); if (root == null) { @@ -45,21 +44,21 @@ public final class IrisDimensionCarvingResolver { } public static IrisDimensionCarvingEntry resolveRootEntry(Engine engine, int worldY) { - return resolveRootEntry(engine, worldY, threadState()); + return resolveRootEntry(engine, worldY, threadState(engine)); } public static IrisDimensionCarvingEntry resolveRootEntry(Engine engine, int worldY, State state) { - State resolvedState = state == null ? threadState() : state; + State resolvedState = state == null ? threadState(engine) : state; IrisData data = resolvedState.bind(engine); return resolveBoundRootEntry(engine, worldY, data, resolvedState); } public static IrisDimensionCarvingEntry resolveFromRoot(Engine engine, IrisDimensionCarvingEntry rootEntry, int worldX, int worldY, int worldZ) { - return resolveFromRoot(engine, rootEntry, worldX, worldY, worldZ, threadState()); + return resolveFromRoot(engine, rootEntry, worldX, worldY, worldZ, threadState(engine)); } public static IrisDimensionCarvingEntry resolveFromRoot(Engine engine, IrisDimensionCarvingEntry rootEntry, int worldX, int worldY, int worldZ, State state) { - State resolvedState = state == null ? threadState() : state; + State resolvedState = state == null ? threadState(engine) : state; IrisData data = resolvedState.bind(engine); return resolveBoundFromRoot(engine, rootEntry, worldX, worldY, worldZ, data, resolvedState); } @@ -237,7 +236,7 @@ public final class IrisDimensionCarvingResolver { } long seed = resolveChildSeed(engine, state); - CNG childGenerator = parent.getChildrenGenerator(seed, data); + CNG childGenerator = parent.getChildrenGenerator(seed, PackRuntime.of(engine, data)); double sample = childGenerator.noiseFast2D(worldX, worldZ); CarvingChoice selected = selectionPlan.select(sample); if (selected == null || selected.entry == null) { @@ -313,15 +312,10 @@ public final class IrisDimensionCarvingResolver { return state.childSeed; } - private static State threadState() { - WeakReference reference = THREAD_STATE.get(); - State state = reference.get(); - if (state != null) { - return state; - } - State replacement = new State(); - THREAD_STATE.set(new WeakReference<>(replacement)); - return replacement; + /** The calling thread's resolver state for this engine; engines without a pack runtime resolve unmemoized. */ + public static State threadState(Engine engine) { + PackRuntime runtime = engine.getPackRuntime(); + return runtime == null ? new State() : runtime.carvingResolverState(); } public static final class Snapshot { diff --git a/core/src/main/java/art/arcane/iris/generation/terrain/IrisMaterialPalette.java b/core/src/main/java/art/arcane/iris/generation/terrain/IrisMaterialPalette.java index f1ba6c709..86f79e270 100644 --- a/core/src/main/java/art/arcane/iris/generation/terrain/IrisMaterialPalette.java +++ b/core/src/main/java/art/arcane/iris/generation/terrain/IrisMaterialPalette.java @@ -18,6 +18,7 @@ package art.arcane.iris.generation.terrain; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.volmlib.nativelib.terrain.structure.StructurePalette; import art.arcane.iris.generation.block.IrisBlockData; @@ -27,8 +28,6 @@ import art.arcane.iris.generation.noise.NoiseStyle; import art.arcane.iris.pack.loading.IrisData; import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.iris.generation.cache.LazyBoundedCache; -import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.pack.schema.annotation.ArrayType; import art.arcane.volmlib.util.documentation.Description; import art.arcane.iris.pack.schema.annotation.MinNumber; @@ -47,7 +46,6 @@ import lombok.Setter; import lombok.experimental.Accessors; import java.util.Optional; -import java.util.concurrent.atomic.AtomicReference; @Snippet("palette") @Accessors(chain = true) @@ -56,19 +54,11 @@ import java.util.concurrent.atomic.AtomicReference; @Description("A palette of materials") @Data public class IrisMaterialPalette implements StructurePalette { - private static final int LAYER_GENERATOR_CACHE_SIZE = 32; private static final int LAYER_GENERATOR_SALT = -23_498_896; private final transient AtomicCache> blockData = new AtomicCache<>(); @Getter(AccessLevel.NONE) @Setter(AccessLevel.NONE) - private final transient LazyBoundedCache layerGenerators = - new LazyBoundedCache<>(LAYER_GENERATOR_CACHE_SIZE); - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private final transient AtomicReference recentLayerGenerator = new AtomicReference<>(); - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) private final transient IrisBlockData fallback = new IrisBlockData("STONE"); @Description("The style of noise") private IrisGeneratorStyle style = NoiseStyle.STATIC.style(); @@ -84,8 +74,8 @@ public class IrisMaterialPalette implements StructurePalette { return palette != null && palette.size() == 1 && palette.get(0) == fallback; } - public NativeBlockState get(RNG rng, double x, double y, double z, IrisData rdata) { - KList localBlockData = getBlockData(rdata); + public NativeBlockState get(RNG rng, double x, double y, double z, PackRuntime runtime) { + KList localBlockData = getBlockData(runtime.data()); int blockDataSize = localBlockData.size(); if (blockDataSize == 0) { return null; @@ -98,7 +88,7 @@ public class IrisMaterialPalette implements StructurePalette { double scaledX = x / zoom; double scaledY = y / zoom; double scaledZ = z / zoom; - return getLayerGenerator(rng, rdata).fit(localBlockData, scaledX, scaledY, scaledZ); + return getLayerGenerator(rng, runtime).fit(localBlockData, scaledX, scaledY, scaledZ); } public Optional getTile(RNG rng, double x, double y, double z, IrisData rdata) { @@ -109,22 +99,13 @@ public class IrisMaterialPalette implements StructurePalette { return tile != null ? Optional.of(tile) : Optional.empty(); } - public CNG getLayerGenerator(RNG rng, IrisData rdata) { - Engine engine = rdata == null ? null : rdata.getEngine(); - int generatorSignature = LAYER_GENERATOR_SALT + getBlockData(rdata).size(); - long generatorSeed = rng.getSeed() + generatorSignature; - CachedLayerGenerator recent = recentLayerGenerator.get(); - if (recent != null && recent.key.matches(rdata, engine, generatorSeed)) { - return recent.generator; - } + public CNG getLayerGenerator(RNG rng, PackRuntime runtime) { + int generatorSignature = LAYER_GENERATOR_SALT + getBlockData(runtime.data()).size(); + return runtime.materialPaletteGenerator(this, rng.getSeed() + generatorSignature); + } - LayerGeneratorKey key = new LayerGeneratorKey(rdata, engine, generatorSeed); - CNG generator = layerGenerators.computeIfAbsent(key, - ignored -> style.create(new RNG(generatorSeed), rdata, engine)); - if (generator != null) { - recentLayerGenerator.set(new CachedLayerGenerator(key, generator)); - } - return generator; + public CNG createLayerGenerator(long seed, PackRuntime runtime) { + return style.createNoCache(new RNG(seed), runtime); } public IrisMaterialPalette qclear() { @@ -165,49 +146,4 @@ public class IrisMaterialPalette implements StructurePalette { palette.clear(); return this; } - - private static final class LayerGeneratorKey { - private final IrisData data; - private final Engine engine; - private final long seed; - - private LayerGeneratorKey(IrisData data, Engine engine, long seed) { - this.data = data; - this.engine = engine; - this.seed = seed; - } - - private boolean matches(IrisData data, Engine engine, long seed) { - return this.data == data && this.engine == engine && this.seed == seed; - } - - @Override - public boolean equals(Object object) { - if (this == object) { - return true; - } - if (!(object instanceof LayerGeneratorKey other)) { - return false; - } - return data == other.data && engine == other.engine && seed == other.seed; - } - - @Override - public int hashCode() { - int result = System.identityHashCode(data); - result = 31 * result + System.identityHashCode(engine); - result = 31 * result + Long.hashCode(seed); - return result; - } - } - - private static final class CachedLayerGenerator { - private final LayerGeneratorKey key; - private final CNG generator; - - private CachedLayerGenerator(LayerGeneratorKey key, CNG generator) { - this.key = key; - this.generator = generator; - } - } } diff --git a/core/src/main/java/art/arcane/iris/generation/terrain/IrisRegion.java b/core/src/main/java/art/arcane/iris/generation/terrain/IrisRegion.java index 8d4e565c9..53dbd266f 100644 --- a/core/src/main/java/art/arcane/iris/generation/terrain/IrisRegion.java +++ b/core/src/main/java/art/arcane/iris/generation/terrain/IrisRegion.java @@ -18,6 +18,7 @@ package art.arcane.iris.generation.terrain; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.cave.IrisCaveProfile; import art.arcane.iris.generation.decoration.IrisDepositGenerator; @@ -176,17 +177,17 @@ public class IrisRegion extends IrisRegistrant implements Rarity { @ArrayType(type = IrisOreGenerator.class, min = 1) private KList ores = new KList<>(); - public NativeBlockState generateOres(int x, int y, int z, RNG rng, IrisData data, boolean surface) { + public NativeBlockState generateOres(int x, int y, int z, RNG rng, PackRuntime runtime, boolean surface) { KList localOres = surface ? getSurfaceOres() : getUndergroundOres(); - return generateOres(localOres, x, y, z, rng, data); + return generateOres(localOres, x, y, z, rng, runtime); } - public NativeBlockState generateSurfaceOres(int x, int y, int z, RNG rng, IrisData data) { - return generateOres(getSurfaceOres(), x, y, z, rng, data); + public NativeBlockState generateSurfaceOres(int x, int y, int z, RNG rng, PackRuntime runtime) { + return generateOres(getSurfaceOres(), x, y, z, rng, runtime); } - public NativeBlockState generateUndergroundOres(int x, int y, int z, RNG rng, IrisData data) { - return generateOres(getUndergroundOres(), x, y, z, rng, data); + public NativeBlockState generateUndergroundOres(int x, int y, int z, RNG rng, PackRuntime runtime) { + return generateOres(getUndergroundOres(), x, y, z, rng, runtime); } public boolean hasSurfaceOres() { @@ -197,7 +198,7 @@ public class IrisRegion extends IrisRegistrant implements Rarity { return !getUndergroundOres().isEmpty(); } - private NativeBlockState generateOres(KList localOres, int x, int y, int z, RNG rng, IrisData data) { + private NativeBlockState generateOres(KList localOres, int x, int y, int z, RNG rng, PackRuntime runtime) { if (localOres.isEmpty()) { return null; } @@ -205,7 +206,7 @@ public class IrisRegion extends IrisRegistrant implements Rarity { int oreCount = localOres.size(); for (int oreIndex = 0; oreIndex < oreCount; oreIndex++) { IrisOreGenerator oreGenerator = localOres.get(oreIndex); - NativeBlockState ore = oreGenerator.generate(x, y, z, rng, data); + NativeBlockState ore = oreGenerator.generate(x, y, z, rng, runtime); if (ore != null) { return ore; } diff --git a/core/src/main/java/art/arcane/iris/generation/terrain/RegionSelection.java b/core/src/main/java/art/arcane/iris/generation/terrain/RegionSelection.java index 9c6234f9c..fa5771811 100644 --- a/core/src/main/java/art/arcane/iris/generation/terrain/RegionSelection.java +++ b/core/src/main/java/art/arcane/iris/generation/terrain/RegionSelection.java @@ -53,7 +53,7 @@ public final class RegionSelection { } } return select(new Options(dimension, data, - dimension.getRegionStyle().create(new RNG(snapshot.complexSeed()).nextParallelRNG(883), data) + dimension.getRegionStyle().create(new RNG(snapshot.complexSeed()).nextParallelRNG(883), data.standalonePackRuntime()) .stream().zoom(dimension.getRegionZoom()), IrisImageMapRuntime.compile(data, dimension, dimension.getMinHeight()), focused)); } diff --git a/core/src/main/java/art/arcane/iris/generation/terrain/Terrain3DRuntime.java b/core/src/main/java/art/arcane/iris/generation/terrain/Terrain3DRuntime.java index 9f35327db..c771d02ae 100644 --- a/core/src/main/java/art/arcane/iris/generation/terrain/Terrain3DRuntime.java +++ b/core/src/main/java/art/arcane/iris/generation/terrain/Terrain3DRuntime.java @@ -1,7 +1,8 @@ package art.arcane.iris.generation.terrain; +import art.arcane.iris.generation.runtime.ThreadSlots; import art.arcane.iris.generation.cache.ConcurrentClockCache; -import art.arcane.iris.pack.loading.IrisData; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.volmlib.util.noise.CNG; @@ -33,12 +34,12 @@ public final class Terrain3DRuntime { private final Terrain3DFragmentFilter fragments; private final Object profileLock = new Object(); private volatile Map profiles = new IdentityHashMap<>(); - private final ThreadLocal localColumn = ThreadLocal.withInitial(ColumnMemo::new); + private final ThreadSlots localColumn = new ThreadSlots<>(ColumnMemo::new); private volatile Object cacheGeneration = new Object(); public Terrain3DRuntime(Sources sources, Options options) { this(sources, options, (style, seed) -> { - CNG noise = style.createNoCache(new RNG(seed), options.data()); + CNG noise = style.createNoCache(new RNG(seed), options.runtime()); return noise::noiseFastSigned3D; }); } @@ -317,7 +318,7 @@ public final class Terrain3DRuntime { } } - public record Options(long seed, int height, double fluidHeight, IrisData data, + public record Options(long seed, int height, double fluidHeight, PackRuntime runtime, boolean enabled, int maximumColumns) { public Options { if (height < 2 || height > 4096 || !Double.isFinite(fluidHeight) diff --git a/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/biome/SelectorCompiler.java b/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/biome/SelectorCompiler.java index 175bcaf22..d2f954b1f 100644 --- a/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/biome/SelectorCompiler.java +++ b/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/biome/SelectorCompiler.java @@ -58,11 +58,11 @@ public final class SelectorCompiler { IrisGeneratorStyle exported = exportable(key.style()); RNG seed = new RNG(CALIBRATION_SEED).nextParallelRNG(key.salt()); if (key.scaled()) { - CNG iris = exported.createScaledGenerator(seed, data, key.factor()); + CNG iris = exported.createScaledGenerator(seed, data.standalonePackRuntime(), key.factor()); IrisGeneratorStyle compiled = scaledCopy(exported, key.factor()); return compile(compiled, key.salt(), iris::noiseFast2D, COHERENT_BLOCKS * compiled.getZoom()); } - CNG iris = exported.create(seed, data); + CNG iris = exported.create(seed, data.standalonePackRuntime()); double zoom = key.factor(); IrisGeneratorStyle compiled = copy(exported); compiled.setZoom(exported.getZoom() * zoom); diff --git a/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/decoration/DecoratorCoverage.java b/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/decoration/DecoratorCoverage.java index 76174827b..fb03df22a 100644 --- a/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/decoration/DecoratorCoverage.java +++ b/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/decoration/DecoratorCoverage.java @@ -30,7 +30,7 @@ final class DecoratorCoverage { } static Coverage measure(IrisGeneratorStyle style, double chance, IrisData data) { - CNG generator = style.createNoCache(new RNG(STYLE_SEED), data); + CNG generator = style.createNoCache(new RNG(STYLE_SEED), data.standalonePackRuntime()); double zoom = style.getZoom(); return measure((x, z) -> generator.fitDouble(0.0, 1.0, x / zoom, z / zoom) <= chance); } diff --git a/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/noise/NoiseStyleCompiler.java b/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/noise/NoiseStyleCompiler.java index 9b39fbc4b..a49a886d5 100644 --- a/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/noise/NoiseStyleCompiler.java +++ b/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/noise/NoiseStyleCompiler.java @@ -1,5 +1,6 @@ package art.arcane.iris.pack.datapack.export.compile.noise; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.noise.IrisGenerator; import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.IrisNoiseGenerator; @@ -38,6 +39,7 @@ public final class NoiseStyleCompiler implements StyleCompiler { private final StyleCompiler selectors; private final Map leaves = new ConcurrentHashMap<>(); private final Map levels = new ConcurrentHashMap<>(); + private final PackRuntime runtime = PackRuntime.standalone(null); public NoiseStyleCompiler(CellularStyleLowering cellular) { this.cellular = Objects.requireNonNull(cellular, "cellular"); @@ -56,7 +58,7 @@ public final class NoiseStyleCompiler implements StyleCompiler { } public static CNG generator(IrisGeneratorStyle style) { - return build(prepared(Objects.requireNonNull(style, "style"), 1.0), 1); + return build(prepared(Objects.requireNonNull(style, "style"), 1.0), 1, PackRuntime.standalone(null)); } @Override @@ -182,7 +184,7 @@ public final class NoiseStyleCompiler implements StyleCompiler { private Field style(IrisGeneratorStyle style, int octaveMultiplier, Domain domain, Emit emit, String path) { IrisGeneratorStyle prepared = prepared(Objects.requireNonNull(style, "noise style"), domain.zoom()); String stylePath = path + "/" + styleName(style); - CNG root = build(prepared, octaveMultiplier); + CNG root = build(prepared, octaveMultiplier, runtime); if (cellular(prepared, root)) { if (domain.warpX() != null || domain.warpZ() != null) { throw new IllegalArgumentException("Cellular noise style " + styleName(style) + " cannot be exported under a layer fracture warp"); @@ -393,8 +395,8 @@ public final class NoiseStyleCompiler implements StyleCompiler { } } - private static CNG build(IrisGeneratorStyle style, int octaveMultiplier) { - return style.createForLayer(new RNG(BUILD_SEED), null, octaveMultiplier); + private static CNG build(IrisGeneratorStyle style, int octaveMultiplier, PackRuntime runtime) { + return style.createForLayer(new RNG(BUILD_SEED), runtime, octaveMultiplier); } private static IrisGeneratorStyle prepared(IrisGeneratorStyle style, double zoom) { diff --git a/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/object/VariantPlanner.java b/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/object/VariantPlanner.java index 2d7a79d9a..69e0e52c6 100644 --- a/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/object/VariantPlanner.java +++ b/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/object/VariantPlanner.java @@ -184,7 +184,7 @@ final class VariantPlanner { return warps; } String key = ContentIds.hash(GSON.toJson(style)); - CNG generator = style.create(new RNG(ContentIds.seed(key)), data); + CNG generator = style.create(new RNG(ContentIds.seed(key)), data.standalonePackRuntime()); double half = style.getMultiplier() / 2; WarpField field = (x, y, z) -> generator.fitDouble(-half, half, x, y, z); for (int index = 0; index < WARP_VARIANTS; index++) { diff --git a/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/subterrain/SubterrainBaker.java b/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/subterrain/SubterrainBaker.java index c3060f77f..547e02df4 100644 --- a/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/subterrain/SubterrainBaker.java +++ b/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/subterrain/SubterrainBaker.java @@ -1,5 +1,6 @@ package art.arcane.iris.pack.datapack.export.compile.subterrain; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.subterrain.IrisSubterrainFeature; import art.arcane.iris.generation.subterrain.SubterrainBounds; @@ -47,6 +48,7 @@ public final class SubterrainBaker { private final long seed; private final IrisData data; + private final PackRuntime runtime; private final IrisDimension dimension; private final BlockStateResolver blocks; private final List diagnostics; @@ -57,6 +59,7 @@ public final class SubterrainBaker { public SubterrainBaker(PackCompileContext context, long seed) { this.seed = seed; data = context.data(); + runtime = data.standalonePackRuntime(); dimension = context.dimension(); blocks = BlockStateResolver.forContext(context); diagnostics = context.diagnostics(); @@ -135,9 +138,9 @@ public final class SubterrainBaker { } int height = y - dimension.getMinHeight(); NativeBlockState candidate = switch (surface) { - case WALL -> biome.getWall().get(random, x, height, z, data); - case FLOOR -> first(biome.generateLayersWithSlope(dimension, x, z, random, 1, height + 1, data, FLAT_SLOPE)); - case CEILING -> first(biome.generateCeilingLayers(dimension, x, z, random, 1, height - 1, data, null)); + case WALL -> biome.getWall().get(random, x, height, z, runtime); + case FLOOR -> first(biome.generateLayersWithSlope(dimension, x, z, random, 1, height + 1, runtime, FLAT_SLOPE)); + case CEILING -> first(biome.generateCeilingLayers(dimension, x, z, random, 1, height - 1, runtime, null)); case INTERIOR -> null; }; return SubterrainRasterizer.isRetainedSolid(candidate) ? candidate : null; @@ -171,7 +174,7 @@ public final class SubterrainBaker { this.random = random; this.resource = resource; plans = List.of(plan); - surfaces = new SubterrainSurfaceMaterials(planner, plans, dimension, null, data, random, dimension.getMinHeight()); + surfaces = new SubterrainSurfaceMaterials(planner, plans, dimension, null, runtime, random, dimension.getMinHeight()); } private BakedRoom room() { diff --git a/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/terrain/VolumetricCompiler.java b/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/terrain/VolumetricCompiler.java index c92bb5619..09181e804 100644 --- a/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/terrain/VolumetricCompiler.java +++ b/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/terrain/VolumetricCompiler.java @@ -101,7 +101,7 @@ public final class VolumetricCompiler { } private static List fit(Marginal marginal, Field unit, Sampling sampling) { - CNG iris = marginal.style().createNoCache(new RNG(MARGINAL_SEED), sampling.data()); + CNG iris = marginal.style().createNoCache(new RNG(MARGINAL_SEED), sampling.data().standalonePackRuntime()); Map noises = sampling.registry().byReference(); double frequency = STYLE_SCALE / marginal.horizontalScale(); SplittableRandom random = new SplittableRandom(MARGINAL_SEED); diff --git a/core/src/main/java/art/arcane/iris/pack/loading/IrisData.java b/core/src/main/java/art/arcane/iris/pack/loading/IrisData.java index d7e26f680..368929b24 100644 --- a/core/src/main/java/art/arcane/iris/pack/loading/IrisData.java +++ b/core/src/main/java/art/arcane/iris/pack/loading/IrisData.java @@ -36,6 +36,8 @@ import art.arcane.iris.spi.IrisPlatforms; import art.arcane.iris.pack.PackDirectoryResolver; import art.arcane.volmlib.util.cache.AtomicCache; import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.generation.runtime.PackRuntime; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.runtime.IrisEngineStreamType; import art.arcane.iris.generation.decoration.IrisProceduralBlocks; import art.arcane.iris.world.loot.IrisBlockDrops; @@ -168,6 +170,10 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory { private transient volatile Engine soleEngine; @Getter(AccessLevel.NONE) @Setter(AccessLevel.NONE) + @EqualsAndHashCode.Exclude + private transient volatile PackRuntime standalonePackRuntime; + @Getter(AccessLevel.NONE) + @Setter(AccessLevel.NONE) private transient volatile Set blockDropMaterials; private IrisData(File dataFolder) { @@ -201,6 +207,23 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory { return Optional.ofNullable(dataLoaders.get(dataFolder)); } + /** + * Closes every cached loader for a pack inside the given folder. A world's generation packs + * live in its own folder and get cached by metadata reads; without this, each closed studio + * world would leave its loader in the cache for the rest of the server's life. + */ + public static void closeLoadedUnder(File root) { + if (root == null) { + return; + } + Path normalizedRoot = root.toPath().toAbsolutePath().normalize(); + for (IrisData data : dataLoaders.values()) { + if (data.getDataFolder().toPath().toAbsolutePath().normalize().startsWith(normalizedRoot)) { + data.close(); + } + } + } + public static void invalidateLoadedAuthoringResources(File source) { Path requested = dataFolderIdentity(Objects.requireNonNull(source, "authoring pack source")); for (Map.Entry entry : dataLoaders.entrySet()) { @@ -656,6 +679,23 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory { dataLoaders.remove(dataFolder, this); } + /** + * The runtime scope for tools that work on this pack without an engine, such as studio previews and validators. + * It is replaced when the pack objects are reloaded and dropped when this data closes. + */ + public PackRuntime standalonePackRuntime() { + PackRuntime current = standalonePackRuntime; + if (current != null) { + return current; + } + synchronized (this) { + if (standalonePackRuntime == null) { + standalonePackRuntime = PackRuntime.standalone(this); + } + return standalonePackRuntime; + } + } + public IrisData copy() { return IrisData.get(dataFolder); } @@ -774,6 +814,7 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory { public void dump() { blockDropMaterials = null; + standalonePackRuntime = null; StructureGraphCatalog.invalidate(this); IrisObjectScale.invalidate(this); for (ResourceLoader i : loaders.values()) { diff --git a/core/src/main/java/art/arcane/iris/platform/bukkit/nms/BukkitStructureStagePolicy.java b/core/src/main/java/art/arcane/iris/platform/bukkit/nms/BukkitStructureStagePolicy.java index 60fd3016c..5bd96956e 100644 --- a/core/src/main/java/art/arcane/iris/platform/bukkit/nms/BukkitStructureStagePolicy.java +++ b/core/src/main/java/art/arcane/iris/platform/bukkit/nms/BukkitStructureStagePolicy.java @@ -1,5 +1,6 @@ package art.arcane.iris.platform.bukkit.nms; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.terrain.IrisDimension; import art.arcane.volmlib.nativelib.terrain.structure.StructureCachePolicy; import art.arcane.volmlib.nativelib.terrain.structure.StructureStagePolicy; @@ -147,7 +148,7 @@ public final class BukkitStructureStagePolicy implements StructureStagePolicy< @Override public NativeBlockState paletteBlock(StructurePalette source, RNG rng, int x, int y, int z) { - return ((IrisMaterialPalette) source).get(rng, x, y, z, engine.getData()); + return ((IrisMaterialPalette) source).get(rng, x, y, z, PackRuntime.of(engine)); } @Override diff --git a/core/src/main/java/art/arcane/iris/platform/generation/BukkitChunkGenerator.java b/core/src/main/java/art/arcane/iris/platform/generation/BukkitChunkGenerator.java index 668a2c7df..8d2f297f6 100644 --- a/core/src/main/java/art/arcane/iris/platform/generation/BukkitChunkGenerator.java +++ b/core/src/main/java/art/arcane/iris/platform/generation/BukkitChunkGenerator.java @@ -273,6 +273,13 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun } } + private void closeCachedWorldPacks() { + if (world == null) { + return; + } + IrisData.closeLoadedUnder(world.worldFolder()); + } + private void closeStartupTarget() { EngineTarget target = startupTarget; startupTarget = null; @@ -952,6 +959,7 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun folder.clear(); populators.clear(); closeStartupTarget(); + closeCachedWorldPacks(); startupReady.completeExceptionally(new IllegalStateException("Iris generator closed during startup.")); }); dispatchAccepted.set(true); diff --git a/core/src/main/java/art/arcane/iris/structure/graph/StructureGraphCatalog.java b/core/src/main/java/art/arcane/iris/structure/graph/StructureGraphCatalog.java index b35879a2c..892107737 100644 --- a/core/src/main/java/art/arcane/iris/structure/graph/StructureGraphCatalog.java +++ b/core/src/main/java/art/arcane/iris/structure/graph/StructureGraphCatalog.java @@ -1,24 +1,18 @@ package art.arcane.iris.structure.graph; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.structure.placement.StructureAssembler; import art.arcane.iris.pack.value.IrisPosition; import art.arcane.iris.structure.placement.IrisStructure; import art.arcane.iris.spi.IrisLogging; import art.arcane.volmlib.util.math.RNG; -import com.github.benmanes.caffeine.cache.Cache; -import com.github.benmanes.caffeine.cache.Caffeine; import java.util.List; import java.util.Objects; -import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; public final class StructureGraphCatalog { - private static final Cache> CACHE = - Caffeine.newBuilder().weakKeys().build(); - private static final Cache> RUNTIME_OUTPUT = - Caffeine.newBuilder().weakKeys().build(); private static final List RUNTIME_SAMPLE_SEEDS = List.of( 0L, 1L, 2L, 3L, 5L, 8L, 13L, 21L, 34L, 55L, 89L, 144L, 233L, 377L, 610L, 987L); @@ -32,15 +26,13 @@ public final class StructureGraphCatalog { if (structureKey == null || structureKey.isBlank()) { return compileAndReport(activeData, activeStructure); } - ConcurrentMap catalog = CACHE.get( - activeData, ignored -> new ConcurrentHashMap<>()); + ConcurrentMap catalog = PackRuntime.forPack(activeData).structureGraphs(); return catalog.computeIfAbsent(structureKey, ignored -> compileAndReport(activeData, activeStructure)); } public static void invalidate(IrisData data) { if (data != null) { - CACHE.invalidate(data); - RUNTIME_OUTPUT.invalidate(data); + PackRuntime.forPack(data).forgetStructureGraphs(); } } @@ -54,8 +46,7 @@ public final class StructureGraphCatalog { if (structureKey == null || structureKey.isBlank()) { return sampleRuntimeAssembly(activeData, activeStructure); } - ConcurrentMap catalog = RUNTIME_OUTPUT.get( - activeData, ignored -> new ConcurrentHashMap<>()); + ConcurrentMap catalog = PackRuntime.forPack(activeData).structureRuntimeOutputs(); return catalog.computeIfAbsent( structureKey, ignored -> sampleRuntimeAssembly(activeData, activeStructure)); } diff --git a/core/src/main/java/art/arcane/iris/structure/nativegen/NativeStructureOwnershipStore.java b/core/src/main/java/art/arcane/iris/structure/nativegen/NativeStructureOwnershipStore.java index 6a2d093e6..e64675de7 100644 --- a/core/src/main/java/art/arcane/iris/structure/nativegen/NativeStructureOwnershipStore.java +++ b/core/src/main/java/art/arcane/iris/structure/nativegen/NativeStructureOwnershipStore.java @@ -13,7 +13,6 @@ import art.arcane.volmlib.util.matter.MatterSlice; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; -import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedHashMap; @@ -29,7 +28,8 @@ import java.util.function.IntConsumer; public final class NativeStructureOwnershipStore { private static final int MAX_CACHED_AUTHORITIES = 65_536; - private static final Cache STATES = Caffeine.newBuilder().weakKeys().build(); + /** Stores of live engines; each engine closes its store, then releases it once the engine is closed. */ + private static final Cache STATES = Caffeine.newBuilder().build(); private NativeStructureOwnershipStore() { } @@ -68,14 +68,25 @@ public final class NativeStructureOwnershipStore { state.close(); } + /** Drops a closed engine's store; a closed engine cannot open a new one. */ + public static void release(Engine engine) { + STATES.invalidate(Objects.requireNonNull(engine, "Native structure ownership store requires an engine")); + } + private static State state(Engine engine) { Engine resolved = Objects.requireNonNull(engine, "Native structure ownership store requires an engine"); + State state = STATES.getIfPresent(resolved); + if (state != null) { + return state; + } + if (resolved.isClosed()) { + throw new IllegalStateException("Native structure ownership store is closed for this engine."); + } return STATES.get(resolved, State::new); } static final class State { - private final WeakReference engine; private final Storage storage; private final Cache authorities; private final ReentrantReadWriteLock lifecycleLock; @@ -87,8 +98,7 @@ public final class NativeStructureOwnershipStore { } State(Engine engine, Storage storage) { - this.engine = new WeakReference<>(Objects.requireNonNull(engine, - "Native structure ownership store requires an engine")); + Objects.requireNonNull(engine, "Native structure ownership store requires an engine"); this.storage = Objects.requireNonNull(storage, "Native structure ownership storage must not be null"); this.authorities = Caffeine.newBuilder().maximumSize(MAX_CACHED_AUTHORITIES).build(); @@ -213,19 +223,10 @@ public final class NativeStructureOwnershipStore { } private void requireOpen() { - engine(); if (closed) { throw new GenerationClosedException("Native structure ownership store is closed"); } } - - private Engine engine() { - Engine active = engine.get(); - if (active == null) { - throw new IllegalStateException("Native structure ownership engine is unavailable"); - } - return active; - } } interface Storage { @@ -242,18 +243,18 @@ public final class NativeStructureOwnershipStore { } static final class MantleStorage implements Storage { - private final WeakReference engine; + private final Engine engine; private final Map pendingBundles; - private final WeakReference retirementEngine; + private final IrisEngine retirementEngine; private final IntConsumer retirementListener; MantleStorage(Engine engine) { Engine required = Objects.requireNonNull(engine, "Native structure ownership store requires an engine"); - this.engine = new WeakReference<>(required); + this.engine = required; this.pendingBundles = new ConcurrentHashMap<>(); if (required instanceof IrisEngine irisEngine) { - this.retirementEngine = new WeakReference<>(irisEngine); + this.retirementEngine = irisEngine; this.retirementListener = this::flushRuntime; irisEngine.addGenerationRuntimeRetirementListener(retirementListener); } else { @@ -337,7 +338,7 @@ public final class NativeStructureOwnershipStore { @Override public void close() { - IrisEngine activeRetirementEngine = retirementEngine == null ? null : retirementEngine.get(); + IrisEngine activeRetirementEngine = retirementEngine; if (activeRetirementEngine != null) { activeRetirementEngine.removeGenerationRuntimeRetirementListener(retirementListener); } @@ -412,10 +413,7 @@ public final class NativeStructureOwnershipStore { } private RuntimeMantleOwner owner() { - Engine active = engine.get(); - if (active == null) { - throw new IllegalStateException("Native structure ownership engine is unavailable"); - } + Engine active = engine; EngineMantle mantle = active.getMantle(); int runtimeId = active.getCacheID(); if (!(active instanceof IrisEngine irisEngine)) { diff --git a/core/src/main/java/art/arcane/iris/structure/nativegen/NativeStructureVolumeIndex.java b/core/src/main/java/art/arcane/iris/structure/nativegen/NativeStructureVolumeIndex.java index 618023b76..1a52a95f8 100644 --- a/core/src/main/java/art/arcane/iris/structure/nativegen/NativeStructureVolumeIndex.java +++ b/core/src/main/java/art/arcane/iris/structure/nativegen/NativeStructureVolumeIndex.java @@ -13,9 +13,9 @@ import art.arcane.volmlib.util.collection.KList; import java.io.IOException; import java.util.Collections; +import java.util.HashMap; import java.util.Map; import java.util.Objects; -import java.util.WeakHashMap; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; @@ -35,8 +35,8 @@ public final class NativeStructureVolumeIndex { private static final int ORIGIN_REACH_CHUNKS = StructureOwnershipRecordView.MAX_REFERENCE_DISTANCE_CHUNKS; private static final int MAX_CACHED_ORIGIN_CHUNKS = 16_384; private static final int MAX_CACHED_QUERY_CHUNKS = 4_096; - private static final Map INDEXES = - Collections.synchronizedMap(new WeakHashMap<>()); + /** Indexes of live engines; each engine uninstalls its own index when it closes. */ + private static final Map INDEXES = Collections.synchronizedMap(new HashMap<>()); private final OriginResolver origins; private final VolumeCache originCache = new VolumeCache(MAX_CACHED_ORIGIN_CHUNKS); diff --git a/core/src/main/java/art/arcane/iris/structure/object/HeightmapObjectPlacer.java b/core/src/main/java/art/arcane/iris/structure/object/HeightmapObjectPlacer.java index e463d4b92..a1d6c218b 100644 --- a/core/src/main/java/art/arcane/iris/structure/object/HeightmapObjectPlacer.java +++ b/core/src/main/java/art/arcane/iris/structure/object/HeightmapObjectPlacer.java @@ -18,6 +18,7 @@ package art.arcane.iris.structure.object; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.block.TileData; @@ -29,19 +30,22 @@ public class HeightmapObjectPlacer implements IObjectPlacer { private final long s; private final IrisObjectPlacement config; private final IObjectPlacer oplacer; + private final PackRuntime runtime; - public HeightmapObjectPlacer(RNG rng, int x, int yv, int z, IrisObjectPlacement config, IObjectPlacer oplacer) { + public HeightmapObjectPlacer(RNG rng, int x, int yv, int z, IrisObjectPlacement config, IObjectPlacer oplacer, + PackRuntime runtime) { s = rng.nextLong() + yv + z - x; this.config = config; this.oplacer = oplacer; + this.runtime = runtime; } public int getHighest(int param1Int1, int param1Int2, IrisData data) { - return (int) Math.round(config.getHeightmap().getNoise(this.s, param1Int1, param1Int2, data)); + return (int) Math.round(config.getHeightmap().getNoise(this.s, param1Int1, param1Int2, runtime.scopeFor(data))); } public int getHighest(int param1Int1, int param1Int2, IrisData data, boolean param1Boolean) { - return (int) Math.round(config.getHeightmap().getNoise(this.s, param1Int1, param1Int2, data)); + return (int) Math.round(config.getHeightmap().getNoise(this.s, param1Int1, param1Int2, runtime.scopeFor(data))); } public void set(int param1Int1, int param1Int2, int param1Int3, NativeBlockState param1BlockData) { diff --git a/core/src/main/java/art/arcane/iris/structure/object/IrisObjectPlacement.java b/core/src/main/java/art/arcane/iris/structure/object/IrisObjectPlacement.java index 60d98d731..f1ad4953d 100644 --- a/core/src/main/java/art/arcane/iris/structure/object/IrisObjectPlacement.java +++ b/core/src/main/java/art/arcane/iris/structure/object/IrisObjectPlacement.java @@ -18,6 +18,7 @@ package art.arcane.iris.structure.object; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.cave.CarvingMode; import art.arcane.iris.generation.cave.IrisCaveAnchorMode; import art.arcane.iris.generation.decoration.IrisStiltSettings; @@ -43,7 +44,6 @@ import art.arcane.iris.pack.validation.ContentGate; import art.arcane.iris.pack.validation.PackCompatReport; import art.arcane.iris.pack.loading.IrisData; import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.iris.generation.cache.LazyBoundedCache; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.structure.placement.LootResolver; import art.arcane.iris.pack.schema.annotation.ArrayType; @@ -87,11 +87,6 @@ import java.util.function.Function; @Description("Represents an iris object placer. It places objects.") @Data public class IrisObjectPlacement { - private static final int SURFACE_WARP_CACHE_SIZE = 8; - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - private final transient LazyBoundedCache surfaceWarpCache = - new LazyBoundedCache<>(SURFACE_WARP_CACHE_SIZE); @RegistryListResource(IrisObject.class) @Required @ArrayType(min = 1, type = String.class) @@ -359,19 +354,19 @@ public class IrisObjectPlacement { return p; } - public CNG getSurfaceWarp(RNG rng, IrisData data) { - return getSurfaceWarp(rng, data, data.getEngine()); - } - - public CNG getSurfaceWarp(RNG rng, IrisData data, @Nullable Engine engine) { + /** Engines seed the surface warp from their component seed; engine-less tools use the caller's seed. */ + public CNG getSurfaceWarp(RNG rng, PackRuntime runtime) { + Engine engine = runtime.engine(); long seed = engine == null ? rng.getSeed() : engine.getSeedManager().getComponent() + 1024L; - SurfaceWarpCacheKey key = new SurfaceWarpCacheKey(data, engine, seed); - return surfaceWarpCache.computeIfAbsent(key, - ignored -> getWarp().create(new RNG(seed), data, engine)); + return runtime.surfaceWarp(this, seed); } - public double warp(RNG rng, double x, double y, double z, IrisData data) { - return getSurfaceWarp(rng, data).fitDouble(-(getWarp().getMultiplier() / 2D), (getWarp().getMultiplier() / 2D), x, y, z); + public CNG createSurfaceWarp(long seed, PackRuntime runtime) { + return getWarp().create(new RNG(seed), runtime); + } + + public double warp(RNG rng, double x, double y, double z, PackRuntime runtime) { + return getSurfaceWarp(rng, runtime).fitDouble(-(getWarp().getMultiplier() / 2D), (getWarp().getMultiplier() / 2D), x, y, z); } public IrisObject getObject(DataProvider g, RNG random) { @@ -414,12 +409,12 @@ public class IrisObjectPlacement { return densityStyle.getMid(); } - public int getDensity(RNG rng, double x, double z, IrisData data) { + public int getDensity(RNG rng, double x, double z, PackRuntime runtime) { if (densityStyle == null) { return density; } - return (int) Math.round(densityStyle.get(rng, x, z, data)); + return (int) Math.round(densityStyle.get(rng, x, z, runtime)); } private TableCache getCache(IrisData manager) { @@ -515,36 +510,6 @@ public class IrisObjectPlacement { return null; } - private static final class SurfaceWarpCacheKey { - private final IrisData data; - private final Engine engine; - private final long seed; - - private SurfaceWarpCacheKey(IrisData data, Engine engine, long seed) { - this.data = data; - this.engine = engine; - this.seed = seed; - } - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (!(other instanceof SurfaceWarpCacheKey key)) { - return false; - } - return data == key.data && engine == key.engine && seed == key.seed; - } - - @Override - public int hashCode() { - int result = System.identityHashCode(data); - result = 31 * result + System.identityHashCode(engine); - return 31 * result + Long.hashCode(seed); - } - } - private static class TableCache { final transient WeightedTables global = new WeightedTables(); final transient KMap basic = new KMap<>(); diff --git a/core/src/main/java/art/arcane/iris/structure/object/IrisObjectReplace.java b/core/src/main/java/art/arcane/iris/structure/object/IrisObjectReplace.java index 01db39b9a..b20bf96f5 100644 --- a/core/src/main/java/art/arcane/iris/structure/object/IrisObjectReplace.java +++ b/core/src/main/java/art/arcane/iris/structure/object/IrisObjectReplace.java @@ -18,6 +18,7 @@ package art.arcane.iris.structure.object; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.block.IrisBlockData; import art.arcane.iris.generation.terrain.IrisMaterialPalette; @@ -49,7 +50,6 @@ import java.util.Map; @Description("Find and replace object materials") @Data public class IrisObjectReplace { - private final transient AtomicCache replaceGen = new AtomicCache<>(); private final transient AtomicCache> findData = new AtomicCache<>(); private final transient AtomicCache> replaceData = new AtomicCache<>(); @ArrayType(min = 1, type = IrisBlockData.class) @@ -83,8 +83,8 @@ public class IrisObjectReplace { }); } - public NativeBlockState getReplace(RNG seed, double x, double y, double z, IrisData rdata) { - return getReplace().get(seed, x, y, z, rdata); + public NativeBlockState getReplace(RNG seed, double x, double y, double z, PackRuntime runtime) { + return getReplace().get(seed, x, y, z, runtime); } /** diff --git a/core/src/main/java/art/arcane/iris/structure/object/ObjectBlockPass.java b/core/src/main/java/art/arcane/iris/structure/object/ObjectBlockPass.java index e8e0ffa38..7e3ddfbbc 100644 --- a/core/src/main/java/art/arcane/iris/structure/object/ObjectBlockPass.java +++ b/core/src/main/java/art/arcane/iris/structure/object/ObjectBlockPass.java @@ -1,5 +1,6 @@ package art.arcane.iris.structure.object; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.block.BlockDataMergeSupport; import art.arcane.iris.generation.block.TileData; import art.arcane.iris.generation.decoration.IrisProceduralBlocks; @@ -43,7 +44,7 @@ final class ObjectBlockPass { void process() { boolean warped = !state.config.getWarp().isFlat(); boolean hasEdits = !state.config.getEdit().isEmpty(); - CNG surfaceWarp = warped ? state.config.getSurfaceWarp(context.rng, context.self.getLoader()) : null; + CNG surfaceWarp = warped ? state.config.getSurfaceWarp(context.rng, context.runtime.scopeFor(context.self.getLoader())) : null; double warpHalf = warped ? state.config.getWarp().getMultiplier() / 2D : 0D; boolean waterlogCandidate = state.config.isWaterloggable() || state.config.isUnderwater(); double[] exact = warped || hasEdits ? bake.exact(context.self, state.spin) : null; @@ -179,7 +180,7 @@ final class ObjectBlockPass { if (context.rng.chance(j.getChance())) { for (NativeBlockState k : j.getFind(context.rdata)) { if (j.isExact() ? k.matches(data) : IrisObjectShaping.materialKey(k).equals(IrisObjectShaping.materialKey(data))) { - NativeBlockState newData = j.getReplace(context.rng, exactX + context.x, exactY + state.y, exactZ + context.z, context.rdata); + NativeBlockState newData = j.getReplace(context.rng, exactX + context.x, exactY + state.y, exactZ + context.z, context.runtime); boolean sameMaterial = IrisObjectShaping.materialKey(newData).equals(IrisObjectShaping.materialKey(data)); if (sameMaterial && !(newData.isCustom() || data.isCustom())) diff --git a/core/src/main/java/art/arcane/iris/structure/object/PlacementContext.java b/core/src/main/java/art/arcane/iris/structure/object/PlacementContext.java index 915d087c4..08d3c830f 100644 --- a/core/src/main/java/art/arcane/iris/structure/object/PlacementContext.java +++ b/core/src/main/java/art/arcane/iris/structure/object/PlacementContext.java @@ -1,5 +1,6 @@ package art.arcane.iris.structure.object; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.cave.CarveResult; import art.arcane.iris.structure.object.PlacementContext.TransformedBounds; import art.arcane.iris.structure.object.PlacementContext.WorldBounds; @@ -23,6 +24,7 @@ public final class PlacementContext { final IrisObjectPlacement config; final IrisData rdata; + final PackRuntime runtime; final IObjectPlacer placer; final CarveResult caveResult; final RNG rng; @@ -53,6 +55,7 @@ public final class PlacementContext { this.config = Objects.requireNonNull(config, "Object placement config is required."); this.rng = Objects.requireNonNull(rng, "Object placement RNG is required."); this.rdata = Objects.requireNonNull(rdata, "Object placement data is required."); + this.runtime = PackRuntime.of(placer.getEngine(), rdata); this.self = Objects.requireNonNull(self, "Object is required."); this.alignment = Objects.requireNonNull(alignment, "Object placement alignment is required."); this.caveResult = caveResult; diff --git a/core/src/main/java/art/arcane/iris/structure/object/PlacementModuleNativeStructureProtection.java b/core/src/main/java/art/arcane/iris/structure/object/PlacementModuleNativeStructureProtection.java index 0dc292d13..f428b2f30 100644 --- a/core/src/main/java/art/arcane/iris/structure/object/PlacementModuleNativeStructureProtection.java +++ b/core/src/main/java/art/arcane/iris/structure/object/PlacementModuleNativeStructureProtection.java @@ -1,5 +1,6 @@ package art.arcane.iris.structure.object; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.block.B; import art.arcane.iris.generation.runtime.Engine; @@ -38,7 +39,7 @@ final class PlacementModuleNativeStructureProtection implements PlacementModule int z = context.z; var bounds = state.bounds; var projection = state.paintProjection; - var surfaceWarp = config.getWarp().isFlat() ? null : config.getSurfaceWarp(context.rng, self.getLoader()); + var surfaceWarp = config.getWarp().isFlat() ? null : config.getSurfaceWarp(context.rng, context.runtime.scopeFor(self.getLoader())); double warpHalf = config.getWarp().isFlat() ? 0 : config.getWarp().getMultiplier() / 2D; int randomY = state.yrand; Engine engine = placer.getEngine(); diff --git a/core/src/main/java/art/arcane/iris/structure/object/PlacementModulePaint.java b/core/src/main/java/art/arcane/iris/structure/object/PlacementModulePaint.java index 848eaf4b8..1c6bba285 100644 --- a/core/src/main/java/art/arcane/iris/structure/object/PlacementModulePaint.java +++ b/core/src/main/java/art/arcane/iris/structure/object/PlacementModulePaint.java @@ -1,5 +1,6 @@ package art.arcane.iris.structure.object; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.geometry.IrisBlockVector; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.noise.CNG; @@ -40,7 +41,7 @@ public final class PlacementModulePaint implements PlacementModule { state.reject("paint-projection"); return; } - var warp = state.config.getWarp().isFlat() ? null : state.config.getSurfaceWarp(context.rng, context.self.getLoader()); + var warp = state.config.getWarp().isFlat() ? null : state.config.getSurfaceWarp(context.rng, context.runtime.scopeFor(context.self.getLoader())); double half = state.config.getWarp().isFlat() ? 0 : state.config.getWarp().getMultiplier() / 2D; state.paintSupport = transformedPaintSupport(context.self, state.spin, state.translateOffset, warp, half, context.x, state.y + state.yrand, context.z); diff --git a/core/src/main/java/art/arcane/iris/structure/object/PlacementModulePreparation.java b/core/src/main/java/art/arcane/iris/structure/object/PlacementModulePreparation.java index 789011cb1..2171d6b69 100644 --- a/core/src/main/java/art/arcane/iris/structure/object/PlacementModulePreparation.java +++ b/core/src/main/java/art/arcane/iris/structure/object/PlacementModulePreparation.java @@ -14,7 +14,7 @@ final class PlacementModulePreparation implements PlacementModule { lifecycle.add(PLACER, PlacementStage.PREPARE, (context, state, ignored) -> { if (state.config.getHeightmap() != null) { state.placer = new HeightmapObjectPlacer(context.rng, context.x, context.yv, context.z, - state.config, context.placer); + state.config, context.placer, context.runtime); } }); lifecycle.add(TRANSFORMS, PlacementStage.PREPARE, PlacementModulePreparation::prepare, diff --git a/core/src/main/java/art/arcane/iris/structure/object/PlacementModuleStilt.java b/core/src/main/java/art/arcane/iris/structure/object/PlacementModuleStilt.java index 27bfd6a4f..a58b6238c 100644 --- a/core/src/main/java/art/arcane/iris/structure/object/PlacementModuleStilt.java +++ b/core/src/main/java/art/arcane/iris/structure/object/PlacementModuleStilt.java @@ -1,5 +1,6 @@ package art.arcane.iris.structure.object; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.block.BlockDataMergeSupport; import art.arcane.iris.generation.decoration.IrisStiltSettings; import art.arcane.iris.generation.hydrology.grid.CellHash; @@ -243,7 +244,7 @@ public final class PlacementModuleStilt implements PlacementModule { boolean hasEdits = !config.getEdit().isEmpty(); boolean warped = !config.getWarp().isFlat(); boolean waterlogCandidate = config.isWaterloggable() || config.isUnderwater(); - CNG surfaceWarp = warped ? config.getSurfaceWarp(rng, self.getLoader()) : null; + CNG surfaceWarp = warped ? config.getSurfaceWarp(rng, context.runtime.scopeFor(self.getLoader())) : null; double warpHalf = warped ? config.getWarp().getMultiplier() / 2D : 0D; double[] exact = warped || hasEdits || eroding ? bake.exact(self, state.spin) : null; int count = bake.count(); @@ -296,7 +297,7 @@ public final class PlacementModuleStilt implements PlacementModule { NativeBlockState d; if (settings != null && settings.getPalette() != null) { - d = settings.getPalette().get(rng, x, y, z, rdata); + d = settings.getPalette().get(rng, x, y, z, context.runtime); } else { d = palette.stiltDefault(entry); } @@ -316,7 +317,7 @@ public final class PlacementModuleStilt implements PlacementModule { continue; } if (j.isExact() ? k.matches(d) : IrisObjectShaping.materialKey(k).equals(IrisObjectShaping.materialKey(d))) { - NativeBlockState newData = j.getReplace(rng, exactX + x, exactY + y, exactZ + z, rdata); + NativeBlockState newData = j.getReplace(rng, exactX + x, exactY + y, exactZ + z, context.runtime); if (IrisObjectShaping.materialKey(newData).equals(IrisObjectShaping.materialKey(d))) { d = BlockDataMergeSupport.merge(d, newData); diff --git a/core/src/main/java/art/arcane/iris/structure/placement/IrisStructureLocator.java b/core/src/main/java/art/arcane/iris/structure/placement/IrisStructureLocator.java index 90d579cce..7b94f9467 100644 --- a/core/src/main/java/art/arcane/iris/structure/placement/IrisStructureLocator.java +++ b/core/src/main/java/art/arcane/iris/structure/placement/IrisStructureLocator.java @@ -81,9 +81,9 @@ public final class IrisStructureLocator { private static final long CAVE_ANCHOR_DOMAIN = 0x43415645414E4348L; private static final Pattern NAMESPACED_RESOURCE_KEY = Pattern.compile("[a-z0-9_.-]+:[a-z0-9/._-]+"); - private static final Cache INDEX_CACHE = Caffeine.newBuilder().weakKeys().build(); - private static final Cache LOCATABLE_INDEX_CACHE = - Caffeine.newBuilder().weakKeys().build(); + /** Indexes of live engines; each engine invalidates its own entries when it closes. */ + private static final Cache INDEX_CACHE = Caffeine.newBuilder().build(); + private static final Cache LOCATABLE_INDEX_CACHE = Caffeine.newBuilder().build(); private static final PlacementIndex EMPTY_INDEX = new PlacementIndex( Collections.emptySet(), Collections.emptySet(), Collections.emptySet(), Collections.emptySet(), Collections.emptySet(), Collections.emptyList()); @@ -1143,6 +1143,9 @@ public final class IrisStructureLocator { if (engine.getData() == null || engine.getDimension() == null) { throw new IllegalStateException("Iris structure index requires a fully bound engine and dimension"); } + if (engine.isClosed()) { + return build(engine); + } return INDEX_CACHE.get(engine, ignored -> build(engine)); } @@ -1150,6 +1153,9 @@ public final class IrisStructureLocator { if (engine == null) { return EMPTY_LOCATABLE_INDEX; } + if (engine.isClosed()) { + return buildLocatableIndex(engine); + } return LOCATABLE_INDEX_CACHE.get(engine, ignored -> buildLocatableIndex(engine)); } diff --git a/core/src/main/java/art/arcane/iris/structure/placement/IrisStructureStrata.java b/core/src/main/java/art/arcane/iris/structure/placement/IrisStructureStrata.java index 1fba10f72..dfaf0790a 100644 --- a/core/src/main/java/art/arcane/iris/structure/placement/IrisStructureStrata.java +++ b/core/src/main/java/art/arcane/iris/structure/placement/IrisStructureStrata.java @@ -1,7 +1,9 @@ package art.arcane.iris.structure.placement; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.decoration.IrisOreBands; +import art.arcane.iris.generation.decoration.OreBandsRuntime; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.IrisComplex; import art.arcane.iris.generation.stage.IrisTerrainNormalActuator; @@ -25,6 +27,7 @@ public final class IrisStructureStrata implements StructureStrata { private final IrisComplex complex; private final IrisDimension dimension; private final IrisData data; + private final PackRuntime runtime; private final RNG rng; private final int offsetY; private final int bedrockFloor; @@ -34,6 +37,7 @@ public final class IrisStructureStrata implements StructureStrata { complex = Objects.requireNonNull(engine.getComplex(), "Structure strata require a terrain complex"); dimension = engine.getDimension(); data = engine.getData(); + runtime = PackRuntime.of(engine, data); rng = new RNG(engine.getSeedManager().getTerrain()); offsetY = engine.getMinHeight(); bedrockFloor = dimension.isBedrock() ? 1 : 0; @@ -57,7 +61,7 @@ public final class IrisStructureStrata implements StructureStrata { } int surface = surfaceY - offsetY; KList layers = biome.generateLayersWithSlope(dimension, x, z, rng, - surface + 1 - bedrockFloor, surface, data, FLAT_GROUND); + surface + 1 - bedrockFloor, surface, runtime, FLAT_GROUND); return new StrataColumn(x, z, surface, submerged, layers, mapped, rock, biome, region); } @@ -69,12 +73,12 @@ public final class IrisStructureStrata implements StructureStrata { private final KList layers; private final NativeBlockState mapped; private final NativeBlockState rock; - private final IrisOreBands biomeSurface; - private final IrisOreBands regionSurface; - private final IrisOreBands dimensionSurface; - private final IrisOreBands biomeUnderground; - private final IrisOreBands regionUnderground; - private final IrisOreBands dimensionUnderground; + private final OreBandsRuntime biomeSurface; + private final OreBandsRuntime regionSurface; + private final OreBandsRuntime dimensionSurface; + private final OreBandsRuntime biomeUnderground; + private final OreBandsRuntime regionUnderground; + private final OreBandsRuntime dimensionUnderground; private StrataColumn(int x, int z, int surface, boolean submerged, KList layers, NativeBlockState mapped, NativeBlockState rock, IrisBiome biome, IrisRegion region) { @@ -85,12 +89,12 @@ public final class IrisStructureStrata implements StructureStrata { this.layers = layers; this.mapped = mapped; this.rock = rock; - biomeSurface = hideOres ? IrisOreBands.EMPTY : biome.getSurfaceOreBands(); - regionSurface = hideOres ? IrisOreBands.EMPTY : region.getSurfaceOreBands(); - dimensionSurface = hideOres ? IrisOreBands.EMPTY : dimension.getSurfaceOreBands(); - biomeUnderground = hideOres ? IrisOreBands.EMPTY : biome.getUndergroundOreBands(); - regionUnderground = hideOres ? IrisOreBands.EMPTY : region.getUndergroundOreBands(); - dimensionUnderground = hideOres ? IrisOreBands.EMPTY : dimension.getUndergroundOreBands(); + biomeSurface = ores(biome.getSurfaceOreBands()); + regionSurface = ores(region.getSurfaceOreBands()); + dimensionSurface = ores(dimension.getSurfaceOreBands()); + biomeUnderground = ores(biome.getUndergroundOreBands()); + regionUnderground = ores(region.getUndergroundOreBands()); + dimensionUnderground = ores(dimension.getUndergroundOreBands()); } @Override @@ -117,16 +121,20 @@ public final class IrisStructureStrata implements StructureStrata { return layers.size(); } - private NativeBlockState ore(IrisOreBands first, IrisOreBands second, IrisOreBands third, int internalY) { + private OreBandsRuntime ores(IrisOreBands bands) { + return runtime.oreBands(hideOres ? IrisOreBands.EMPTY : bands, rng.getSeed()); + } + + private NativeBlockState ore(OreBandsRuntime first, OreBandsRuntime second, OreBandsRuntime third, int internalY) { NativeBlockState ore = null; if (first.contains(internalY)) { - ore = first.generate(x, internalY, z, rng, data, data == null ? null : data.getEngine()); + ore = first.generate(x, internalY, z, rng); } if (ore == null && second.contains(internalY)) { - ore = second.generate(x, internalY, z, rng, data, data == null ? null : data.getEngine()); + ore = second.generate(x, internalY, z, rng); } if (ore == null && third.contains(internalY)) { - ore = third.generate(x, internalY, z, rng, data, data == null ? null : data.getEngine()); + ore = third.generate(x, internalY, z, rng); } return ore; } diff --git a/core/src/main/java/art/arcane/iris/structure/placement/StructurePlacementScope.java b/core/src/main/java/art/arcane/iris/structure/placement/StructurePlacementScope.java index cb97f4dfb..04aaf047d 100644 --- a/core/src/main/java/art/arcane/iris/structure/placement/StructurePlacementScope.java +++ b/core/src/main/java/art/arcane/iris/structure/placement/StructurePlacementScope.java @@ -7,16 +7,16 @@ import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.terrain.IrisRegion; import art.arcane.volmlib.util.collection.KList; -import java.lang.ref.WeakReference; -import java.util.ArrayList; import java.util.Collections; import java.util.IdentityHashMap; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.Set; public final class StructurePlacementScope { - private static final List SCOPE_INDEXES = new ArrayList<>(); + /** Scope indexes of live engines; each engine invalidates its own entry when it closes. */ + private static final Map SCOPE_INDEXES = new IdentityHashMap<>(); private StructurePlacementScope() { } @@ -63,26 +63,30 @@ public final class StructurePlacementScope { return false; } + public static void invalidate(Engine engine) { + synchronized (SCOPE_INDEXES) { + SCOPE_INDEXES.remove(engine); + } + } + + static boolean isIndexed(Engine engine) { + synchronized (SCOPE_INDEXES) { + return SCOPE_INDEXES.containsKey(engine); + } + } + private static ScopeIndex scopeIndex(Engine engine) { + if (engine.isClosed()) { + return buildScopeIndex(engine); + } int revision = engine.getCacheID(); synchronized (SCOPE_INDEXES) { - for (int i = SCOPE_INDEXES.size() - 1; i >= 0; i--) { - CachedScopeIndex cached = SCOPE_INDEXES.get(i); - Engine indexedEngine = cached.engine().get(); - if (indexedEngine == null) { - SCOPE_INDEXES.remove(i); - continue; - } - if (indexedEngine == engine) { - if (cached.revision() == revision) { - return cached.index(); - } - SCOPE_INDEXES.remove(i); - break; - } + CachedScopeIndex cached = SCOPE_INDEXES.get(engine); + if (cached != null && cached.revision() == revision) { + return cached.index(); } ScopeIndex index = buildScopeIndex(engine); - SCOPE_INDEXES.add(new CachedScopeIndex(new WeakReference<>(engine), revision, index)); + SCOPE_INDEXES.put(engine, new CachedScopeIndex(revision, index)); return index; } } @@ -155,7 +159,7 @@ public final class StructurePlacementScope { } } - private record CachedScopeIndex(WeakReference engine, int revision, ScopeIndex index) { + private record CachedScopeIndex(int revision, ScopeIndex index) { } private record ScopeIndex(boolean biome, boolean caveBiome, boolean region, boolean dimension) { diff --git a/core/src/main/java/art/arcane/iris/structure/placement/StructureReachability.java b/core/src/main/java/art/arcane/iris/structure/placement/StructureReachability.java index 7e60a0d60..deed5c864 100644 --- a/core/src/main/java/art/arcane/iris/structure/placement/StructureReachability.java +++ b/core/src/main/java/art/arcane/iris/structure/placement/StructureReachability.java @@ -42,7 +42,8 @@ import java.util.Set; *

The reachable set is fixed per live engine/world and is rebuilt after hotload. */ public final class StructureReachability { - private static final Cache> REACHABLE_CACHE = Caffeine.newBuilder().weakKeys().build(); + /** Reachable keys of live engines; each engine invalidates its own entry when it closes. */ + private static final Cache> REACHABLE_CACHE = Caffeine.newBuilder().build(); private StructureReachability() { } @@ -52,6 +53,9 @@ public final class StructureReachability { if (activeEngine.getData() == null) { throw new IllegalStateException("Structure reachability requires a bound pack data loader"); } + if (activeEngine.isClosed()) { + return build(activeEngine); + } return REACHABLE_CACHE.get(activeEngine, ignored -> build(activeEngine)); } diff --git a/core/src/main/java/art/arcane/iris/studio/map/BiomePalettePlacement.java b/core/src/main/java/art/arcane/iris/studio/map/BiomePalettePlacement.java index a6c03c5ae..2f4eba9af 100644 --- a/core/src/main/java/art/arcane/iris/studio/map/BiomePalettePlacement.java +++ b/core/src/main/java/art/arcane/iris/studio/map/BiomePalettePlacement.java @@ -18,6 +18,7 @@ package art.arcane.iris.studio.map; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.generation.decoration.IrisDecorationPart; import art.arcane.iris.generation.decoration.IrisEngineDecorator; @@ -37,29 +38,31 @@ import art.arcane.volmlib.util.noise.CNG; * passes use. */ abstract class BiomePalettePlacement { + protected final PackRuntime runtime; protected final IrisData data; - private BiomePalettePlacement(IrisData data) { - this.data = data; + private BiomePalettePlacement(PackRuntime runtime) { + this.runtime = runtime; + this.data = runtime.data(); } static BiomePalettePlacement of(Engine engine, IrisBiome biome, BiomePalette palette) { - IrisData data = engine.getData(); + PackRuntime runtime = PackRuntime.of(engine); RNG terrainRandom = new RNG(engine.getSeedManager().getTerrain()); RNG carveRandom = new RNG(engine.getSeedManager().getCarve()); RNG postRandom = new RNG(engine.getSeedManager().getPost()); int seaLevel = seaLevel(engine.getDimension()); int index = palette.index(); return switch (palette.kind()) { - case LAYER -> new StackedLayer(palette.layerIn(biome), index, biome.getLayerHeightGenerators(terrainRandom, data), - terrainRandom, data); - case SEA_LAYER -> new StackedLayer(palette.layerIn(biome), index, biome.getLayerSeaHeightGenerators(terrainRandom, data), - terrainRandom, data); + case LAYER -> new StackedLayer(palette.layerIn(biome), index, biome.getLayerHeightGenerators(terrainRandom, runtime), + terrainRandom, runtime); + case SEA_LAYER -> new StackedLayer(palette.layerIn(biome), index, biome.getLayerSeaHeightGenerators(terrainRandom, runtime), + terrainRandom, runtime); case CAVE_CEILING_LAYER -> new StackedLayer(palette.layerIn(biome), index, - biome.getCaveCeilingLayerHeightGenerators(carveRandom, data), carveRandom, data); - case WALL -> new SingleBlocks(palette.layerIn(biome), data, carveRandom, seaLevel); - case SLAB -> new SingleBlocks(palette.layerIn(biome), data, postRandom, seaLevel); - case DECORATOR -> new Decorations(palette.decoratorIn(biome), engine.getSeedManager().getComponent(), seaLevel, data); + biome.getCaveCeilingLayerHeightGenerators(carveRandom, runtime), carveRandom, runtime); + case WALL -> new SingleBlocks(palette.layerIn(biome), runtime, carveRandom, seaLevel); + case SLAB -> new SingleBlocks(palette.layerIn(biome), runtime, postRandom, seaLevel); + case DECORATOR -> new Decorations(palette.decoratorIn(biome), engine.getSeedManager().getComponent(), seaLevel, runtime); }; } @@ -89,8 +92,8 @@ abstract class BiomePalettePlacement { private abstract static class LayerPlacement extends BiomePalettePlacement { protected final IrisBiomePaletteLayer layer; - private LayerPlacement(IrisBiomePaletteLayer layer, IrisData data) { - super(data); + private LayerPlacement(IrisBiomePaletteLayer layer, PackRuntime runtime) { + super(runtime); this.layer = layer; } @@ -114,8 +117,8 @@ abstract class BiomePalettePlacement { private final RNG random; private final CNG thicknessNoise; - private StackedLayer(IrisBiomePaletteLayer layer, int index, KList thicknessNoises, RNG random, IrisData data) { - super(layer, data); + private StackedLayer(IrisBiomePaletteLayer layer, int index, KList thicknessNoises, RNG random, PackRuntime runtime) { + super(layer, runtime); this.index = index; this.random = random; this.thicknessNoise = index < thicknessNoises.size() ? thicknessNoises.get(index) : null; @@ -143,7 +146,7 @@ abstract class BiomePalettePlacement { @Override double noise(int blockX, int blockZ, int depth) { double zoom = layer.getZoom(); - return layer.getLayerGenerator(random, index + depth, data) + return layer.getLayerGenerator(random, index + depth, runtime) .noise((blockX + depth) / zoom / zoom, depth / zoom, (blockZ - depth) / zoom / zoom); } } @@ -155,8 +158,8 @@ abstract class BiomePalettePlacement { private final RNG random; private final int sampleHeight; - private SingleBlocks(IrisBiomePaletteLayer layer, IrisData data, RNG random, int sampleHeight) { - super(layer, data); + private SingleBlocks(IrisBiomePaletteLayer layer, PackRuntime runtime, RNG random, int sampleHeight) { + super(layer, runtime); this.random = random; this.sampleHeight = sampleHeight; } @@ -169,7 +172,7 @@ abstract class BiomePalettePlacement { @Override double noise(int blockX, int blockZ, int depth) { double zoom = layer.getZoom(); - return layer.getLayerGenerator(random, data).noise(blockX / zoom, sampleHeight / zoom, blockZ / zoom); + return layer.getLayerGenerator(random, runtime).noise(blockX / zoom, sampleHeight / zoom, blockZ / zoom); } } @@ -185,12 +188,12 @@ abstract class BiomePalettePlacement { private final boolean picksFromFlatNoise; private final int sampleHeight; - private Decorations(IrisDecorator decorator, long componentSeed, int sampleHeight, IrisData data) { - super(data); + private Decorations(IrisDecorator decorator, long componentSeed, int sampleHeight, PackRuntime runtime) { + super(runtime); this.decorator = decorator; RNG partRandom = new RNG(IrisEngineDecorator.seedForPart(componentSeed, decorator.getPartOf())); - this.placementNoise = decorator.getGenerator(partRandom, data); - this.blockNoise = decorator.getVarianceGenerator(partRandom, data); + this.placementNoise = decorator.getGenerator(partRandom, runtime); + this.blockNoise = decorator.getVarianceGenerator(partRandom, runtime); this.picksFromFlatNoise = decorator.getPartOf() == IrisDecorationPart.NONE || decorator.getPartOf() == IrisDecorationPart.CEILING; this.sampleHeight = sampleHeight; diff --git a/core/src/main/java/art/arcane/iris/studio/map/BiomeTintField.java b/core/src/main/java/art/arcane/iris/studio/map/BiomeTintField.java index 3a20b60fa..e1981c0de 100644 --- a/core/src/main/java/art/arcane/iris/studio/map/BiomeTintField.java +++ b/core/src/main/java/art/arcane/iris/studio/map/BiomeTintField.java @@ -21,6 +21,7 @@ package art.arcane.iris.studio.map; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.biome.IrisBiomeCustom; +import art.arcane.iris.generation.runtime.Engine; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; @@ -38,14 +39,16 @@ final class BiomeTintField { private final IrisBiome biome; private final RNG biomeRandom; + private final Engine engine; private final MinecraftBiomeColors minecraftColors; private final BiomeTintColors sameColorsEverywhere; private final Map colorsByCustomBiome = new ConcurrentHashMap<>(); private final BlendedTint[] blendedTintCache = new BlendedTint[BLENDED_TINT_CACHE_SIZE]; private final ChunkColors[] chunkColorsCache = new ChunkColors[CHUNK_COLORS_CACHE_SIZE]; - BiomeTintField(IrisBiome biome, RNG biomeRandom, MinecraftBiomeColors minecraftColors) { + BiomeTintField(IrisBiome biome, Engine engine, RNG biomeRandom, MinecraftBiomeColors minecraftColors) { this.biome = biome; + this.engine = engine; this.biomeRandom = biomeRandom; this.minecraftColors = minecraftColors; BiomeTintColors onlyColors = onlyPossibleColors(); @@ -95,9 +98,9 @@ final class BiomeTintField { private BiomeTintColors colorsForChunkAt(int originX, int originZ) { if (biome.isCustom()) { - return customColors(biome.getCustomBiome(biomeRandom, originX, 0, originZ)); + return customColors(biome.getCustomBiome(biomeRandom, engine, originX, 0, originZ)); } - return vanillaColors(biome.getSkyBiomeKey(biomeRandom, originX, 0, originZ)); + return vanillaColors(biome.getSkyBiomeKey(biomeRandom, engine, originX, 0, originZ)); } // Follows the same choices as IrisBiome#getSkyBiomeKey and #getCustomBiome, returning null when chunks can differ. diff --git a/core/src/main/java/art/arcane/iris/studio/map/NoiseExplorerGUI.java b/core/src/main/java/art/arcane/iris/studio/map/NoiseExplorerGUI.java index f7ed1dab9..ec4bb4e8d 100644 --- a/core/src/main/java/art/arcane/iris/studio/map/NoiseExplorerGUI.java +++ b/core/src/main/java/art/arcane/iris/studio/map/NoiseExplorerGUI.java @@ -18,6 +18,7 @@ package art.arcane.iris.studio.map; +import art.arcane.iris.generation.runtime.PackRuntime; import com.formdev.flatlaf.FlatClientProperties; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.configuration.IrisSettings; @@ -570,7 +571,8 @@ public final class NoiseExplorerGUI extends JPanel { } long mixedSeed = new RNG(sourceSeed).nextParallelRNG(3245).lmax(); IrisGenerator selectedGenerator = generator; - return (x, z) -> selectedGenerator.getHeight(x, z, mixedSeed); + PackRuntime runtime = PackRuntime.of(engine, selectedGenerator.getLoader()); + return (x, z) -> selectedGenerator.getHeight(runtime, x, z, mixedSeed); } private List loadPackSources(Engine engine) { @@ -608,7 +610,8 @@ public final class NoiseExplorerGUI extends JPanel { throw new IllegalStateException("Pack generator not found: " + key); } long mixedSeed = new RNG(sourceSeed).nextParallelRNG(3245).lmax(); - return LoadedSource.of((x, z) -> generator.getHeight(x, z, mixedSeed)); + PackRuntime runtime = data.standalonePackRuntime(); + return LoadedSource.of((x, z) -> generator.getHeight(runtime, x, z, mixedSeed)); } )); } diff --git a/core/src/main/java/art/arcane/iris/studio/map/PaletteLayerPreview.java b/core/src/main/java/art/arcane/iris/studio/map/PaletteLayerPreview.java index a3aecf10c..a8d7a7bea 100644 --- a/core/src/main/java/art/arcane/iris/studio/map/PaletteLayerPreview.java +++ b/core/src/main/java/art/arcane/iris/studio/map/PaletteLayerPreview.java @@ -98,7 +98,7 @@ final class PaletteLayerPreview { BiomePalettePlacement placement = BiomePalettePlacement.of(engine, biome, palette); BiomeTintField biomeTints = textures == null ? null - : new BiomeTintField(biome, new RNG(engine.getSeedManager().getBiome()), textures.biomeColors()); + : new BiomeTintField(biome, engine, new RNG(engine.getSeedManager().getBiome()), textures.biomeColors()); PaletteLayerPreview ground = palette.kind() == BiomePalette.Kind.DECORATOR ? groundUnder(engine, palette.biomeKey(), biome, data, textures, biomeTints) : null; diff --git a/core/src/main/java/art/arcane/iris/world/entity/IrisEffect.java b/core/src/main/java/art/arcane/iris/world/entity/IrisEffect.java index 508d343f9..f5db66405 100644 --- a/core/src/main/java/art/arcane/iris/world/entity/IrisEffect.java +++ b/core/src/main/java/art/arcane/iris/world/entity/IrisEffect.java @@ -31,7 +31,7 @@ import art.arcane.iris.pack.schema.annotation.Required; import art.arcane.iris.pack.schema.annotation.Snippet; import art.arcane.iris.spi.IrisLogging; import art.arcane.volmlib.util.math.RNG; -import art.arcane.volmlib.util.scheduling.ChronoLatch; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.platform.registry.RegistryUtil; import art.arcane.iris.world.task.J; import lombok.AllArgsConstructor; @@ -66,7 +66,6 @@ public class IrisEffect { private static final Set UNKNOWN_SOUND_CATEGORIES = ConcurrentHashMap.newKeySet(); private final transient AtomicCache pt = new AtomicCache<>(); - private final transient AtomicCache latch = new AtomicCache<>(); private final transient AtomicCache particleEffectResolved = new AtomicCache<>(); private final transient AtomicCache soundResolved = new AtomicCache<>(); @RegistryListPotionEffect @@ -176,12 +175,12 @@ public class IrisEffect { private IrisCommandRegistry commandRegistry = null; - public boolean canTick() { - return latch.aquire(() -> new ChronoLatch(interval)).flip(); + public boolean canTick(PackRuntime runtime) { + return runtime.effectLatch(this).flip(); } - public boolean shouldApplyNow() { - return canTick() && RNG.r.nextInt(chance) == 0; + public boolean shouldApplyNow(PackRuntime runtime) { + return canTick(runtime) && RNG.r.nextInt(chance) == 0; } public String getParticleEffectKey() { @@ -272,7 +271,7 @@ public class IrisEffect { } public void apply(Player p, Engine g) { - if (!shouldApplyNow()) { + if (!shouldApplyNow(PackRuntime.of(g))) { return; } @@ -349,8 +348,8 @@ public class IrisEffect { } } - public void apply(Entity p) { - if (!shouldApplyNow()) { + public void apply(Entity p, PackRuntime runtime) { + if (!shouldApplyNow(runtime)) { return; } diff --git a/core/src/main/java/art/arcane/iris/world/entity/IrisEntity.java b/core/src/main/java/art/arcane/iris/world/entity/IrisEntity.java index c1c51c11c..5533b1a42 100644 --- a/core/src/main/java/art/arcane/iris/world/entity/IrisEntity.java +++ b/core/src/main/java/art/arcane/iris/world/entity/IrisEntity.java @@ -18,6 +18,7 @@ package art.arcane.iris.world.entity; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.volmlib.nativelib.entity.NativeEntityOptions; import art.arcane.volmlib.nativelib.entity.NativeEntityType; import art.arcane.iris.spi.IrisPlatform; @@ -409,7 +410,7 @@ public class IrisEntity extends IrisRegistrant implements NativeEntityOptions { } if (spawnEffect != null) { - spawnEffect.apply(e); + spawnEffect.apply(e, PackRuntime.of(gen)); } if (rawCommands.isNotEmpty()) { diff --git a/core/src/main/java/art/arcane/iris/world/history/GenerationBoundaryStore.java b/core/src/main/java/art/arcane/iris/world/history/GenerationBoundaryStore.java index be3db16cf..844094364 100644 --- a/core/src/main/java/art/arcane/iris/world/history/GenerationBoundaryStore.java +++ b/core/src/main/java/art/arcane/iris/world/history/GenerationBoundaryStore.java @@ -1,5 +1,6 @@ package art.arcane.iris.world.history; +import art.arcane.iris.generation.runtime.ThreadSlots; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import it.unimi.dsi.fastutil.longs.LongArrays; @@ -619,7 +620,7 @@ public final class GenerationBoundaryStore { private final long[] regionKeys; private final Long2ObjectOpenHashMap shardHashes; private final LinkedHashMap masks; - private final ThreadLocal lastRegion = new ThreadLocal<>(); + private final ThreadSlots lastRegion = ThreadSlots.bindings(); private MaskSource( Path directory, diff --git a/core/src/main/java/art/arcane/iris/world/history/GenerationHistoryRuntimeRouter.java b/core/src/main/java/art/arcane/iris/world/history/GenerationHistoryRuntimeRouter.java index 60608b719..bbafbb513 100644 --- a/core/src/main/java/art/arcane/iris/world/history/GenerationHistoryRuntimeRouter.java +++ b/core/src/main/java/art/arcane/iris/world/history/GenerationHistoryRuntimeRouter.java @@ -1,5 +1,6 @@ package art.arcane.iris.world.history; +import art.arcane.iris.generation.runtime.ThreadSlots; import art.arcane.volmlib.nativelib.terrain.NativeGenerationRoute; import art.arcane.volmlib.nativelib.terrain.NativeBlockPositionPredicate; @@ -48,8 +49,8 @@ public final class GenerationHistoryRuntimeRouter implements AutoCloseable { private final Map savedMantles = new LinkedHashMap<>(); private final ReentrantLock stateLock; private final Condition inactive; - private final ThreadLocal operationDepth; - private final ThreadLocal scopedRoute; + private final ThreadSlots operationDepth; + private final ThreadSlots scopedRoute; private int activeOperations; private int activeLoads; private boolean closed; @@ -71,8 +72,8 @@ public final class GenerationHistoryRuntimeRouter implements AutoCloseable { this.retiringBindings = new LinkedHashMap<>(); this.stateLock = new ReentrantLock(); this.inactive = stateLock.newCondition(); - this.operationDepth = ThreadLocal.withInitial(() -> 0); - this.scopedRoute = new ThreadLocal<>(); + this.operationDepth = new ThreadSlots<>(() -> 0); + this.scopedRoute = ThreadSlots.bindings(); this.biomes = new SavedBiomeRuntime(engine, history); this.objectContinuations = new HistoricalObjectContinuations(history, this::readObjectContinuationRegion); diff --git a/core/src/main/java/art/arcane/iris/world/history/TransitionBandIndex.java b/core/src/main/java/art/arcane/iris/world/history/TransitionBandIndex.java index 07c20efb0..7cb7cf68f 100644 --- a/core/src/main/java/art/arcane/iris/world/history/TransitionBandIndex.java +++ b/core/src/main/java/art/arcane/iris/world/history/TransitionBandIndex.java @@ -1,5 +1,6 @@ package art.arcane.iris.world.history; +import art.arcane.iris.generation.runtime.ThreadSlots; import java.util.concurrent.atomic.AtomicLongArray; import java.util.concurrent.atomic.AtomicReferenceArray; @@ -9,7 +10,7 @@ final class TransitionBandIndex { private final GenerationBoundary boundary; private final TransitionBoundarySampler sampler; private final AtomicReferenceArray regions = new AtomicReferenceArray<>(MAXIMUM_CACHED_REGIONS); - private final ThreadLocal lastRegion = new ThreadLocal<>(); + private final ThreadSlots lastRegion = ThreadSlots.bindings(); TransitionBandIndex(GenerationBoundary boundary, TransitionBoundarySampler sampler) { this.boundary = boundary; diff --git a/core/src/main/java/art/arcane/iris/world/history/TransitionBoundarySampler.java b/core/src/main/java/art/arcane/iris/world/history/TransitionBoundarySampler.java index e22703820..83a74d3af 100644 --- a/core/src/main/java/art/arcane/iris/world/history/TransitionBoundarySampler.java +++ b/core/src/main/java/art/arcane/iris/world/history/TransitionBoundarySampler.java @@ -1,5 +1,6 @@ package art.arcane.iris.world.history; +import art.arcane.iris.generation.runtime.ThreadSlots; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; @@ -21,7 +22,7 @@ final class TransitionBoundarySampler { private final TerrainBoundarySignatureStore.Snapshot signatures; private final LinkedHashMap chunkCandidates; private final Map> pendingCandidates = new HashMap<>(); - private final ThreadLocal cache; + private final ThreadSlots cache; private int cachedCandidates; private long candidateBuildCount; @@ -36,7 +37,7 @@ final class TransitionBoundarySampler { this.searchWidth = terrainWidth; this.signatures = Objects.requireNonNull(signatures, "Terrain boundary signatures"); this.chunkCandidates = new LinkedHashMap<>(MAXIMUM_CACHED_CHUNKS, 0.75F, true); - this.cache = ThreadLocal.withInitial(ChunkCache::new); + this.cache = new ThreadSlots<>(ChunkCache::new); } TransitionGenerationPlan.TerrainSample sample(int blockX, int blockZ) { diff --git a/core/src/main/java/art/arcane/iris/world/history/TransitionDisplacementField.java b/core/src/main/java/art/arcane/iris/world/history/TransitionDisplacementField.java index 9e0260988..13d700b82 100644 --- a/core/src/main/java/art/arcane/iris/world/history/TransitionDisplacementField.java +++ b/core/src/main/java/art/arcane/iris/world/history/TransitionDisplacementField.java @@ -1,5 +1,6 @@ package art.arcane.iris.world.history; +import art.arcane.iris.generation.runtime.ThreadSlots; import java.util.LinkedHashMap; import java.util.Objects; import java.util.concurrent.CompletableFuture; @@ -15,7 +16,7 @@ public final class TransitionDisplacementField { private final Sources sources; private final LinkedHashMap completed = new LinkedHashMap<>(64, 0.75F, true); private final ConcurrentHashMap> pending = new ConcurrentHashMap<>(); - private final ThreadLocal local = new ThreadLocal<>(); + private final ThreadSlots local = ThreadSlots.bindings(); public TransitionDisplacementField(TransitionGenerationPlan plan, Sources sources) { this.plan = Objects.requireNonNull(plan); diff --git a/core/src/test/java/art/arcane/iris/generation/biome/FloatingIslandBoundarySamplerTest.java b/core/src/test/java/art/arcane/iris/generation/biome/FloatingIslandBoundarySamplerTest.java index 2faffebcb..8281f5313 100644 --- a/core/src/test/java/art/arcane/iris/generation/biome/FloatingIslandBoundarySamplerTest.java +++ b/core/src/test/java/art/arcane/iris/generation/biome/FloatingIslandBoundarySamplerTest.java @@ -18,6 +18,7 @@ package art.arcane.iris.generation.biome; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.world.IrisWorld; import art.arcane.iris.pack.loading.IrisData; @@ -553,42 +554,43 @@ public class FloatingIslandBoundarySamplerTest { IrisBiome parent = mock(IrisBiome.class); IrisData data = mock(IrisData.class); Engine engine = mock(Engine.class); + PackRuntime runtime = PackRuntime.forEngine(engine, data); IrisWorld world = IrisWorld.builder().minHeight(0).maxHeight(320).build(); KList entries = new KList<>(); entries.add(entry); when(parent.getFloatingChildBiomes()).thenReturn(entries); when(parent.isMergeFloatingChildBiomes()).thenReturn(false); - when(entry.getFootprintCng(anyLong(), same(data))).thenReturn(footprint); + when(entry.getFootprintCng(anyLong(), same(runtime))).thenReturn(footprint); when(entry.getFootprintThreshold()).thenReturn(0.5D); - when(entry.getAltitudeCng(anyLong(), same(data))).thenReturn(constant); + when(entry.getAltitudeCng(anyLong(), same(runtime))).thenReturn(constant); when(entry.getMinHeightAboveSurface()).thenReturn(160); when(entry.getMaxHeightAboveSurface()).thenReturn(160); when(entry.getRealBiome(parent, data)).thenReturn(parent); when(entry.getTopShapeMode()).thenReturn(TopShapeMode.NOISE); - when(entry.getTopShapeCng(anyLong(), same(data))).thenReturn(constant); + when(entry.getTopShapeCng(anyLong(), same(runtime))).thenReturn(constant); when(entry.getTopShapeAmp()).thenReturn(1.0D); when(entry.getMaxTopHeight()).thenReturn(18); - when(entry.getBottomCng(anyLong(), same(data))).thenReturn(constant); + when(entry.getBottomCng(anyLong(), same(runtime))).thenReturn(constant); when(entry.getBottomExponent()).thenReturn(1.0D); when(entry.getBottomDepthMin()).thenReturn(20); when(entry.getBottomDepthMax()).thenReturn(20); when(entry.getMaxThickness()).thenReturn(64); when(entry.getMinAbsoluteY()).thenReturn(null); when(entry.getMaxAbsoluteY()).thenReturn(null); - when(entry.getWallWarpCng(anyLong(), same(data))).thenReturn(null); + when(entry.getWallWarpCng(anyLong(), same(runtime))).thenReturn(null); when(entry.getWallWarpAmplitude()).thenReturn(0.0D); - when(entry.getCarvingProfileSampler(engine, data)).thenReturn(null); + when(entry.getCarvingProfileSampler(runtime)).thenReturn(null); when(entry.hasCarvingReference()).thenReturn(false); - when(entry.getCarveCng(anyLong(), same(data))).thenReturn(constant); + when(entry.getCarveCng(anyLong(), same(runtime))).thenReturn(constant); when(entry.getCarveThreshold()).thenReturn(0.5D); when(engine.getWorld()).thenReturn(world); FloatingIslandBoundarySampler sampler = new FloatingIslandBoundarySampler((x, z) -> parent); int[] expectedBottom = {159, 158, 156, 153, 150, 147, 144, 142, 141, 140}; int[] expectedTop = {161, 162, 164, 166, 169, 172, 174, 176, 177, 178}; - assertNull(FloatingIslandSample.sample(parent, 0, 0, 320, 31L, data, engine, sampler)); + assertNull(FloatingIslandSample.sample(parent, 0, 0, 320, 31L, runtime, sampler)); for (int i = 0; i < expectedBottom.length; i++) { - FloatingIslandSample sample = FloatingIslandSample.sample(parent, i + 1, 0, 320, 31L, data, engine, sampler); + FloatingIslandSample sample = FloatingIslandSample.sample(parent, i + 1, 0, 320, 31L, runtime, sampler); assertNotNull("distance " + (i + 2) + " rejected with code " + FloatingIslandSample.getLastReject(), sample); assertEquals(expectedBottom[i], sample.bottomY()); assertEquals(expectedTop[i], sample.topY()); @@ -633,6 +635,7 @@ public class FloatingIslandBoundarySamplerTest { IrisBiome parent = mock(IrisBiome.class); IrisData data = mock(IrisData.class); Engine engine = mock(Engine.class); + PackRuntime runtime = PackRuntime.forEngine(engine, data); IrisWorld world = IrisWorld.builder().minHeight(0).maxHeight(320).build(); KList entries = new KList<>(); entries.add(lower); @@ -640,26 +643,26 @@ public class FloatingIslandBoundarySamplerTest { when(parent.getFloatingChildBiomes()).thenReturn(entries); when(parent.isMergeFloatingChildBiomes()).thenReturn(true); for (IrisFloatingChildBiomes entry : entries) { - when(entry.getFootprintCng(anyLong(), same(data))).thenReturn(footprint); + when(entry.getFootprintCng(anyLong(), same(runtime))).thenReturn(footprint); when(entry.getFootprintThreshold()).thenReturn(0.5D); - when(entry.getAltitudeCng(anyLong(), same(data))).thenReturn(constant); + when(entry.getAltitudeCng(anyLong(), same(runtime))).thenReturn(constant); when(entry.getRealBiome(parent, data)).thenReturn(parent); when(entry.getTopShapeMode()).thenReturn(TopShapeMode.NOISE); - when(entry.getTopShapeCng(anyLong(), same(data))).thenReturn(constant); + when(entry.getTopShapeCng(anyLong(), same(runtime))).thenReturn(constant); when(entry.getTopShapeAmp()).thenReturn(1.0D); when(entry.getMaxTopHeight()).thenReturn(18); - when(entry.getBottomCng(anyLong(), same(data))).thenReturn(constant); + when(entry.getBottomCng(anyLong(), same(runtime))).thenReturn(constant); when(entry.getBottomExponent()).thenReturn(1.0D); when(entry.getBottomDepthMin()).thenReturn(20); when(entry.getBottomDepthMax()).thenReturn(20); when(entry.getMaxThickness()).thenReturn(64); when(entry.getMinAbsoluteY()).thenReturn(null); when(entry.getMaxAbsoluteY()).thenReturn(null); - when(entry.getWallWarpCng(anyLong(), same(data))).thenReturn(null); + when(entry.getWallWarpCng(anyLong(), same(runtime))).thenReturn(null); when(entry.getWallWarpAmplitude()).thenReturn(0.0D); - when(entry.getCarvingProfileSampler(engine, data)).thenReturn(null); + when(entry.getCarvingProfileSampler(runtime)).thenReturn(null); when(entry.hasCarvingReference()).thenReturn(false); - when(entry.getCarveCng(anyLong(), same(data))).thenReturn(null); + when(entry.getCarveCng(anyLong(), same(runtime))).thenReturn(null); when(entry.getCarveThreshold()).thenReturn(1.0D); } when(lower.getMinHeightAboveSurface()).thenReturn(160); @@ -669,8 +672,8 @@ public class FloatingIslandBoundarySamplerTest { when(engine.getWorld()).thenReturn(world); FloatingIslandBoundarySampler sampler = new FloatingIslandBoundarySampler((x, z) -> parent); - assertNull(FloatingIslandSample.sample(parent, 0, 0, 320, 35L, data, engine, sampler)); - FloatingIslandSample sample = FloatingIslandSample.sample(parent, 1, 0, 320, 35L, data, engine, sampler); + assertNull(FloatingIslandSample.sample(parent, 0, 0, 320, 35L, runtime, sampler)); + FloatingIslandSample sample = FloatingIslandSample.sample(parent, 1, 0, 320, 35L, runtime, sampler); assertNotNull(sample); assertTrue(sample.hasMergedEntries()); diff --git a/core/src/test/java/art/arcane/iris/generation/biome/FloatingIslandLockedLayersTest.java b/core/src/test/java/art/arcane/iris/generation/biome/FloatingIslandLockedLayersTest.java index ee1453d07..edcf5bfd3 100644 --- a/core/src/test/java/art/arcane/iris/generation/biome/FloatingIslandLockedLayersTest.java +++ b/core/src/test/java/art/arcane/iris/generation/biome/FloatingIslandLockedLayersTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.biome; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.block.B; import art.arcane.iris.generation.context.ChunkContext; import art.arcane.iris.generation.hydrology.raster.WaterRole; @@ -20,6 +21,7 @@ import java.util.Arrays; import static org.junit.Assert.assertSame; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.anyDouble; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyLong; @@ -41,6 +43,8 @@ public class FloatingIslandLockedLayersTest { .setFloatingChildBiomes(new KList<>(entry)); Engine engine = mock(Engine.class, RETURNS_DEEP_STUBS); when(engine.getDimension()).thenReturn(new IrisDimension()); + PackRuntime engineRuntime = PackRuntime.forEngine(engine, engine.getData()); + when(engine.getPackRuntime()).thenReturn(engineRuntime); when(engine.getSubterrainCell(anyInt(), anyInt(), anyInt())).thenReturn(null); when(engine.getComplex().allowsNewDiscreteContentAt(anyInt(), anyInt())).thenReturn(false); when(engine.getComplex().getWaterRoleStream()).thenReturn(ProceduralStream.of((x, z) -> WaterRole.NONE, @@ -71,19 +75,19 @@ public class FloatingIslandLockedLayersTest { MockedStatic blocks = mockStatic(B.class)) { blocks.when(() -> B.getState("minecraft:stone")).thenReturn(first); samples.when(() -> FloatingIslandSample.sampleMemoized(eq(parent), eq(-16), eq(-16), - anyInt(), anyLong(), any(), eq(engine), eq(boundary))).thenReturn(thin); + anyInt(), anyLong(), argThat((PackRuntime runtime) -> runtime.engine() == engine), eq(boundary))).thenReturn(thin); samples.when(() -> FloatingIslandSample.sampleMemoized(eq(parent), eq(-15), eq(-16), - anyInt(), anyLong(), any(), eq(engine), eq(boundary))).thenReturn(thick); + anyInt(), anyLong(), argThat((PackRuntime runtime) -> runtime.engine() == engine), eq(boundary))).thenReturn(thick); samples.when(() -> FloatingIslandSample.sampleMemoized(eq(parent), eq(-14), eq(-16), - anyInt(), anyLong(), any(), eq(engine), eq(boundary))).thenReturn(raised); + anyInt(), anyLong(), argThat((PackRuntime runtime) -> runtime.engine() == engine), eq(boundary))).thenReturn(raised); samples.when(() -> FloatingIslandSample.sampleMemoized(eq(parent), eq(-13), eq(-16), - anyInt(), anyLong(), any(), eq(engine), eq(boundary))).thenReturn(gapped); + anyInt(), anyLong(), argThat((PackRuntime runtime) -> runtime.engine() == engine), eq(boundary))).thenReturn(gapped); samples.when(() -> FloatingIslandSample.sampleMemoized(eq(parent), eq(-12), eq(-16), - anyInt(), anyLong(), any(), eq(engine), eq(boundary))).thenReturn(mirrored); + anyInt(), anyLong(), argThat((PackRuntime runtime) -> runtime.engine() == engine), eq(boundary))).thenReturn(mirrored); samples.when(() -> FloatingIslandSample.sampleMemoized(eq(parent), eq(-11), eq(-16), - anyInt(), anyLong(), any(), eq(engine), eq(boundary))).thenReturn(custom); + anyInt(), anyLong(), argThat((PackRuntime runtime) -> runtime.engine() == engine), eq(boundary))).thenReturn(custom); samples.when(() -> FloatingIslandSample.sampleMemoized(eq(ordinaryParent), eq(-10), eq(-16), - anyInt(), anyLong(), any(), eq(engine), eq(boundary))).thenReturn(ordinary); + anyInt(), anyLong(), argThat((PackRuntime runtime) -> runtime.engine() == engine), eq(boundary))).thenReturn(ordinary); new IrisFloatingChildBiomeModifier(engine).onModify(-16, -16, output, false, context); } assertSame(first, output.get(0, 20, 0)); @@ -121,7 +125,7 @@ public class FloatingIslandLockedLayersTest { when(layer.getSlopeCondition()).thenReturn(new IrisSlopeClip()); when(layer.getHeightGenerator(any(), any())).thenReturn(height); when(height.fit(anyInt(), anyInt(), anyDouble(), anyDouble())).thenReturn(1); - when(layer.get(any(), anyInt(), anyDouble(), anyDouble(), anyDouble(), any())).thenReturn(block); + when(layer.get(any(), anyInt(), anyDouble(), anyDouble(), anyDouble(), any(PaletteLayerRuntime.class))).thenReturn(block); when(layer.get(any(), anyDouble(), anyDouble(), anyDouble(), any())).thenReturn(block); return layer; } diff --git a/core/src/test/java/art/arcane/iris/generation/biome/FloatingIslandMemoContextTest.java b/core/src/test/java/art/arcane/iris/generation/biome/FloatingIslandMemoContextTest.java index 515964bc6..86685c096 100644 --- a/core/src/test/java/art/arcane/iris/generation/biome/FloatingIslandMemoContextTest.java +++ b/core/src/test/java/art/arcane/iris/generation/biome/FloatingIslandMemoContextTest.java @@ -1,9 +1,9 @@ package art.arcane.iris.generation.biome; import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.pack.loading.IrisData; import art.arcane.volmlib.util.collection.KList; -import org.junit.After; import org.junit.Test; import static org.junit.Assert.assertNull; @@ -13,35 +13,40 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class FloatingIslandMemoContextTest { - @After - public void clearMemo() { - FloatingIslandSample.clearThreadCaches(); - } - @Test - public void rejectedColumnsAreCachedOnlyForTheirParentAndContext() { - FloatingIslandSample.clearThreadCaches(); + public void rejectedColumnsAreCachedOnlyForTheirParentContextAndRuntime() { IrisBiome first = parent(); IrisBiome second = parent(); IrisData data = mock(IrisData.class); - Engine engine = mock(Engine.class); + PackRuntime runtime = PackRuntime.forEngine(mock(Engine.class), data); FloatingIslandBoundarySampler boundary = new FloatingIslandBoundarySampler((x, z) -> first); - sample(first, 320, 7L, data, engine, boundary); - sample(first, 320, 7L, data, engine, boundary); - sample(second, 320, 7L, data, engine, boundary); + sample(first, 320, 7L, runtime, boundary); + sample(first, 320, 7L, runtime, boundary); + sample(second, 320, 7L, runtime, boundary); verify(first, times(1)).getFloatingChildBiomes(); verify(second, times(1)).getFloatingChildBiomes(); - sample(first, 320, 9L, data, engine, boundary); - sample(first, 128, 9L, data, engine, boundary); - sample(first, 128, 9L, data, mock(Engine.class), boundary); - sample(first, 128, 9L, mock(IrisData.class), engine, boundary); - sample(first, 128, 9L, data, engine, new FloatingIslandBoundarySampler((x, z) -> first)); + sample(first, 320, 9L, runtime, boundary); + sample(first, 128, 9L, runtime, boundary); + sample(first, 128, 9L, PackRuntime.forEngine(mock(Engine.class), data), boundary); + sample(first, 128, 9L, runtime.scopeFor(mock(IrisData.class)), boundary); + sample(first, 128, 9L, runtime, new FloatingIslandBoundarySampler((x, z) -> first)); verify(first, times(6)).getFloatingChildBiomes(); } - private static void sample(IrisBiome parent, int height, long seed, IrisData data, Engine engine, + @Test + public void clearingTheChunkMemoSamplesAgain() { + IrisBiome parent = parent(); + PackRuntime runtime = PackRuntime.forEngine(mock(Engine.class), mock(IrisData.class)); + FloatingIslandBoundarySampler boundary = new FloatingIslandBoundarySampler((x, z) -> parent); + sample(parent, 320, 7L, runtime, boundary); + FloatingIslandSample.clearChunkMemo(runtime); + sample(parent, 320, 7L, runtime, boundary); + verify(parent, times(2)).getFloatingChildBiomes(); + } + + private static void sample(IrisBiome parent, int height, long seed, PackRuntime runtime, FloatingIslandBoundarySampler boundary) { - assertNull(FloatingIslandSample.sampleMemoized(parent, -16, 32, height, seed, data, engine, boundary)); + assertNull(FloatingIslandSample.sampleMemoized(parent, -16, 32, height, seed, runtime, boundary)); } private static IrisBiome parent() { diff --git a/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeCeilingLayerTest.java b/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeCeilingLayerTest.java index 171b39279..59ff30d9b 100644 --- a/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeCeilingLayerTest.java +++ b/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeCeilingLayerTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.biome; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.terrain.IrisDimension; import art.arcane.volmlib.nativelib.terrain.NativeBlockState; @@ -15,6 +16,8 @@ import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; public class IrisBiomeCeilingLayerTest { + private static final PackRuntime RUNTIME = PackRuntime.standalone(null); + @Test public void emitsEveryCeilingLayerWithoutSurfaceLayers() { NativeBlockState first = mock(NativeBlockState.class); @@ -24,7 +27,7 @@ public class IrisBiomeCeilingLayerTest { new KList<>(layer(first, 2), layer(second, 1), layer(third, 2))); KList result = biome.generateCeilingLayers( - new IrisDimension(), 13, -27, new RNG(1), 8, 64, null, null); + new IrisDimension(), 13, -27, new RNG(1), 8, 64, RUNTIME, null); assertEquals(List.of(first, first, second, third, third), result); } @@ -34,17 +37,17 @@ public class IrisBiomeCeilingLayerTest { IrisBiome first = variableBiome(1, 1); IrisBiome second = variableBiome(7, 31); RNG rng = new RNG(37); - second.getLayerHeightGenerators(rng, null); + second.getLayerHeightGenerators(rng, RUNTIME); for (int x = -200; x <= 200; x += 7) { KList firstCeiling = first.generateCeilingLayers( - new IrisDimension(), x, -x, rng, 100, 120, null, null); + new IrisDimension(), x, -x, rng, 100, 120, RUNTIME, null); KList secondCeiling = second.generateCeilingLayers( - new IrisDimension(), x, -x, rng, 100, 120, null, null); + new IrisDimension(), x, -x, rng, 100, 120, RUNTIME, null); assertEquals(firstCeiling.size(), secondCeiling.size()); } - first.getLayerHeightGenerators(rng, null); - assertNotSame(first.getLayerHeightGenerators(rng, null).get(0), - first.getLayerCeilingHeightGenerators().get(first.getCaveCeilingLayers(), 7235, rng, null).get(0)); + first.getLayerHeightGenerators(rng, RUNTIME); + assertNotSame(first.getLayerHeightGenerators(rng, RUNTIME).get(0), + first.getCaveCeilingLayerHeightGenerators(rng, RUNTIME).get(0)); } @Test @@ -53,9 +56,9 @@ public class IrisBiomeCeilingLayerTest { NativeBlockState second = mock(NativeBlockState.class); IrisBiome biome = new IrisBiome().setCaveCeilingLayers(new KList<>(layer(first, 2), layer(second, 3))); assertEquals(List.of(first, first, second), biome.generateCeilingLayers( - new IrisDimension(), 0, 0, new RNG(1), 3, 64, null, null)); + new IrisDimension(), 0, 0, new RNG(1), 3, 64, RUNTIME, null)); assertTrue(biome.generateCeilingLayers( - new IrisDimension(), 0, 0, new RNG(1), 0, 64, null, null).isEmpty()); + new IrisDimension(), 0, 0, new RNG(1), 0, 64, RUNTIME, null).isEmpty()); } @Test diff --git a/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeChildrenGeneratorTest.java b/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeChildrenGeneratorTest.java index f556b2278..465f474d2 100644 --- a/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeChildrenGeneratorTest.java +++ b/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeChildrenGeneratorTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.biome; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.NoiseStyle; import art.arcane.iris.pack.loading.IrisData; @@ -30,7 +31,7 @@ public class IrisBiomeChildrenGeneratorTest { } private void buildChildrenGenerator() { - biome.getChildrenGenerator(new RNG(WORLD_SEED), CHILDREN_SIGNATURE, CHILD_SHRINK_FACTOR); + biome.getChildrenGenerator(PackRuntime.standalone(biome.getLoader()), new RNG(WORLD_SEED), CHILDREN_SIGNATURE, CHILD_SHRINK_FACTOR); } private double[] sampleUntouchedSharedChildStyleGenerator() { @@ -38,7 +39,7 @@ public class IrisBiomeChildrenGeneratorTest { } private double[] sampleSharedChildStyleGenerator(IrisGeneratorStyle childStyle) { - return sampleSharedGenerator(childStyle, deriveSharedChildStyleSeed(), packData); + return sampleSharedGenerator(childStyle, deriveSharedChildStyleSeed(), PackRuntime.of(packData.getEngine(), packData)); } private static RNG deriveSharedChildStyleSeed() { diff --git a/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeFieldSeedCohesionTest.java b/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeFieldSeedCohesionTest.java index 12453b944..8ac88efed 100644 --- a/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeFieldSeedCohesionTest.java +++ b/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeFieldSeedCohesionTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.biome; +import art.arcane.iris.testsupport.MockPackData; import art.arcane.iris.generation.noise.NoiseStyle; import art.arcane.iris.pack.loading.IrisData; import art.arcane.volmlib.util.math.RNG; @@ -20,23 +21,23 @@ import static org.mockito.Mockito.mock; public class IrisBiomeFieldSeedCohesionTest { @Test public void childrenGeneratorsSeparateSeedsSignaturesAndScales() { - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); IrisBiome shared = biome(data); for (long seed : new long[]{29L, 11L, 29L}) { for (int signature : new int[]{2137, 91}) { for (double scale : new double[]{4D, 0.25D}) { - assertArrayEquals(samples(biome(data).getChildrenGenerator(new RNG(seed), signature, scale)), - samples(shared.getChildrenGenerator(new RNG(seed), signature, scale)), 0D); + assertArrayEquals(samples(biome(data).getChildrenGenerator(data.standalonePackRuntime(), new RNG(seed), signature, scale)), + samples(shared.getChildrenGenerator(data.standalonePackRuntime(), new RNG(seed), signature, scale)), 0D); } } } - CNG first = shared.getChildrenGenerator(new RNG(29L), 2137, 4D); - assertSame(first, shared.getChildrenGenerator(new RNG(29L), 2137, 4D)); + CNG first = shared.getChildrenGenerator(data.standalonePackRuntime(), new RNG(29L), 2137, 4D); + assertSame(first, shared.getChildrenGenerator(data.standalonePackRuntime(), new RNG(29L), 2137, 4D)); } @Test(timeout = 15000) public void concurrentFloatingFieldsAndEvictionRetainSeedAssignments() throws Exception { - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); IrisFloatingChildBiomes shared = new IrisFloatingChildBiomes(); ExecutorService workers = Executors.newFixedThreadPool(4); try { @@ -65,12 +66,12 @@ public class IrisBiomeFieldSeedCohesionTest { double x = -71.25D; double z = 145.75D; return new double[]{ - entry.getFootprintCng(seed, data).noise(x, z), - entry.getPickerCng(seed, data).noise(x, z), - entry.getAltitudeCng(seed, data).noise(x, z), - entry.getTopShapeCng(seed, data).noise(x, z), - entry.getBottomCng(seed, data).noise(x, z), - entry.getEdgeTaperProfile(seed, data).fade(4, -71, 145) + entry.getFootprintCng(seed, data.standalonePackRuntime()).noise(x, z), + entry.getPickerCng(seed, data.standalonePackRuntime()).noise(x, z), + entry.getAltitudeCng(seed, data.standalonePackRuntime()).noise(x, z), + entry.getTopShapeCng(seed, data.standalonePackRuntime()).noise(x, z), + entry.getBottomCng(seed, data.standalonePackRuntime()).noise(x, z), + entry.getEdgeTaperProfile(seed, data.standalonePackRuntime()).fade(4, -71, 145) }; } diff --git a/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeGeneratorSeedIsolationTest.java b/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeGeneratorSeedIsolationTest.java index b289bcae9..238de2a1a 100644 --- a/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeGeneratorSeedIsolationTest.java +++ b/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeGeneratorSeedIsolationTest.java @@ -1,6 +1,7 @@ package art.arcane.iris.generation.biome; -import art.arcane.iris.pack.loading.IrisData; +import art.arcane.iris.testsupport.MockPackData; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.SeedManager; import art.arcane.volmlib.util.noise.CNG; @@ -11,7 +12,6 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; -import java.util.concurrent.atomic.AtomicReference; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; @@ -26,48 +26,47 @@ public class IrisBiomeGeneratorSeedIsolationTest { @Test public void engineSeedMakesPaperStyleFirstCallOrderIrrelevant() { - IrisData data = dataWithActiveEngine(new AtomicReference<>(engine(1337L))); - IrisBiome paperFirst = biome(data); - IrisBiome moddedFirst = biome(data); + Engine engine = engine(1337L); + IrisBiome paperFirst = biome(); + IrisBiome moddedFirst = biome(); - CNG paperGenerator = paperFirst.getBiomeGenerator(new RNG(8457289L)); - CNG moddedGenerator = moddedFirst.getBiomeGenerator(new RNG(-991245L)); + CNG paperGenerator = paperFirst.getBiomeGenerator(new RNG(8457289L), engine); + CNG moddedGenerator = moddedFirst.getBiomeGenerator(new RNG(-991245L), engine); assertEquals(paperGenerator.noise(SAMPLE_X, SAMPLE_Z), moddedGenerator.noise(SAMPLE_X, SAMPLE_Z), 0D); } @Test public void distinctEnginesKeepDistinctBiomeGenerators() { - Engine firstEngine = engine(1337L); - Engine secondEngine = engine(7331L); - IrisBiome biome = biome(dataWithActiveEngine(new AtomicReference<>(secondEngine))); + IrisBiome biome = biome(); - CNG first = biome.getBiomeGenerator(new RNG(1L), firstEngine); - CNG second = biome.getBiomeGenerator(new RNG(1L), secondEngine); + CNG first = biome.getBiomeGenerator(new RNG(1L), engine(1337L)); + CNG second = biome.getBiomeGenerator(new RNG(1L), engine(7331L)); assertNotSame(first, second); assertNotEquals(first.noise(SAMPLE_X, SAMPLE_Z), second.noise(SAMPLE_X, SAMPLE_Z), 0D); } @Test - public void sameSeedEnginesSharingBiomeReuseBiomeGenerator() { + public void sameSeedEnginesBuildEqualButOwnBiomeGenerators() { + IrisBiome biome = biome(); Engine firstEngine = engine(1337L); - Engine secondEngine = engine(1337L); - IrisBiome biome = biome(dataWithActiveEngine(new AtomicReference<>(secondEngine))); CNG first = biome.getBiomeGenerator(new RNG(11L), firstEngine); - CNG second = biome.getBiomeGenerator(new RNG(99L), secondEngine); + CNG second = biome.getBiomeGenerator(new RNG(99L), engine(1337L)); - assertSame(first, second); + assertSame(first, biome.getBiomeGenerator(new RNG(99L), firstEngine)); + assertNotSame(first, second); + assertEquals(first.noise(SAMPLE_X, SAMPLE_Z), second.noise(SAMPLE_X, SAMPLE_Z), 0D); } @Test public void engineLessToolingUsesSuppliedRngSeed() { - IrisBiome biome = biome(null); + IrisBiome biome = biome(); - CNG first = biome.getBiomeGenerator(new RNG(11L)); - CNG sameSeed = biome.getBiomeGenerator(new RNG(11L)); - CNG second = biome.getBiomeGenerator(new RNG(99L)); + CNG first = biome.getBiomeGenerator(new RNG(11L), null); + CNG sameSeed = biome.getBiomeGenerator(new RNG(11L), null); + CNG second = biome.getBiomeGenerator(new RNG(99L), null); assertSame(first, sameSeed); assertNotSame(first, second); @@ -75,10 +74,10 @@ public class IrisBiomeGeneratorSeedIsolationTest { } @Test - public void concurrentExactEnginesIgnoreLoaderEngine() throws Exception { + public void concurrentEnginesKeepTheirOwnGenerators() throws Exception { Engine firstEngine = engine(1337L); Engine secondEngine = engine(7331L); - IrisBiome biome = biome(dataWithActiveEngine(new AtomicReference<>(secondEngine))); + IrisBiome biome = biome(); CountDownLatch start = new CountDownLatch(1); ExecutorService executor = Executors.newFixedThreadPool(2); try { @@ -98,33 +97,29 @@ public class IrisBiomeGeneratorSeedIsolationTest { @Test public void biomeGeneratorCacheEvictsOldSeeds() { - IrisBiome biome = biome(null); - CNG first = biome.getBiomeGenerator(new RNG(0L)); + IrisBiome biome = biome(); + CNG first = biome.getBiomeGenerator(new RNG(0L), null); for (long seed = 1L; seed <= 8L; seed++) { - biome.getBiomeGenerator(new RNG(seed)); + biome.getBiomeGenerator(new RNG(seed), null); } - assertNotSame(first, biome.getBiomeGenerator(new RNG(0L))); + assertNotSame(first, biome.getBiomeGenerator(new RNG(0L), null)); } - private IrisBiome biome(IrisData data) { + private IrisBiome biome() { IrisBiome biome = new IrisBiome().setName("Scatter Test"); - biome.setLoader(data); + biome.setLoader(MockPackData.create()); return biome; } - private IrisData dataWithActiveEngine(AtomicReference activeEngine) { - IrisData data = mock(IrisData.class); - when(data.getEngine()).thenAnswer(ignored -> activeEngine.get()); - return data; - } - private Engine engine(long biomeSeed) { SeedManager seedManager = mock(SeedManager.class); when(seedManager.getBiome()).thenReturn(biomeSeed); Engine engine = mock(Engine.class); when(engine.getSeedManager()).thenReturn(seedManager); + PackRuntime runtime = PackRuntime.forEngine(engine, null); + when(engine.getPackRuntime()).thenReturn(runtime); return engine; } diff --git a/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeLayerHeightCacheTest.java b/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeLayerHeightCacheTest.java index 431ef092f..df59a6ea5 100644 --- a/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeLayerHeightCacheTest.java +++ b/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeLayerHeightCacheTest.java @@ -1,5 +1,7 @@ package art.arcane.iris.generation.biome; +import art.arcane.iris.generation.runtime.PackRuntime; +import art.arcane.iris.testsupport.MockPackData; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.terrain.IrisDimension; import art.arcane.iris.pack.loading.IrisData; @@ -26,6 +28,8 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class IrisBiomeLayerHeightCacheTest { + private static final PackRuntime RUNTIME = PackRuntime.standalone(null); + private static final long TERRAIN_SEED = 7191L; private static final long CARVE_SEED = -872315L; private static final long FLOATING_SEED = (TERRAIN_SEED ^ 0x7EB0A73F1DCE514DL) @@ -34,15 +38,15 @@ public class IrisBiomeLayerHeightCacheTest { @Test public void layerHeightUsesEachCallerSeedInEitherOrder() { IrisBiomePaletteLayer layer = layer(); - assertNoise(layer().getHeightGenerator(new RNG(CARVE_SEED), null), - layer.getHeightGenerator(new RNG(CARVE_SEED), null)); - assertNoise(layer().getHeightGenerator(new RNG(FLOATING_SEED), null), - layer.getHeightGenerator(new RNG(FLOATING_SEED), null)); + assertNoise(layer().getHeightGenerator(new RNG(CARVE_SEED), RUNTIME), + layer.getHeightGenerator(new RNG(CARVE_SEED), RUNTIME)); + assertNoise(layer().getHeightGenerator(new RNG(FLOATING_SEED), RUNTIME), + layer.getHeightGenerator(new RNG(FLOATING_SEED), RUNTIME)); IrisBiomePaletteLayer reversed = layer(); - assertNoise(layer.getHeightGenerator(new RNG(FLOATING_SEED), null), - reversed.getHeightGenerator(new RNG(FLOATING_SEED), null)); - assertNoise(layer.getHeightGenerator(new RNG(CARVE_SEED), null), - reversed.getHeightGenerator(new RNG(CARVE_SEED), null)); + assertNoise(layer.getHeightGenerator(new RNG(FLOATING_SEED), RUNTIME), + reversed.getHeightGenerator(new RNG(FLOATING_SEED), RUNTIME)); + assertNoise(layer.getHeightGenerator(new RNG(CARVE_SEED), RUNTIME), + reversed.getHeightGenerator(new RNG(CARVE_SEED), RUNTIME)); } @Test @@ -50,16 +54,16 @@ public class IrisBiomeLayerHeightCacheTest { IrisBiome biome = biome(); long[] seeds = {FLOATING_SEED, CARVE_SEED, TERRAIN_SEED, FLOATING_SEED + 733L}; for (long seed : seeds) { - assertGenerators(biome().getLayerHeightGenerators(new RNG(seed), null), - biome.getLayerHeightGenerators(new RNG(seed), null)); + assertGenerators(biome().getLayerHeightGenerators(new RNG(seed), RUNTIME), + biome.getLayerHeightGenerators(new RNG(seed), RUNTIME)); } IrisBiome reversed = biome(); for (int i = seeds.length - 1; i >= 0; i--) { - assertGenerators(biome.getLayerHeightGenerators(new RNG(seeds[i]), null), - reversed.getLayerHeightGenerators(new RNG(seeds[i]), null)); + assertGenerators(biome.getLayerHeightGenerators(new RNG(seeds[i]), RUNTIME), + reversed.getLayerHeightGenerators(new RNG(seeds[i]), RUNTIME)); } - assertNotEquals(biome.getLayerHeightGenerators(new RNG(TERRAIN_SEED), null).get(0).noise(13, -29), - biome.getLayerHeightGenerators(new RNG(FLOATING_SEED), null).get(0).noise(13, -29), 0D); + assertNotEquals(biome.getLayerHeightGenerators(new RNG(TERRAIN_SEED), RUNTIME).get(0).noise(13, -29), + biome.getLayerHeightGenerators(new RNG(FLOATING_SEED), RUNTIME).get(0).noise(13, -29), 0D); } @Test @@ -72,11 +76,11 @@ public class IrisBiomeLayerHeightCacheTest { try { for (int worker = 0; worker < 8; worker++) { long seed = seeds[worker % seeds.length]; - KList expected = biome().getLayerHeightGenerators(new RNG(seed), null); + KList expected = biome().getLayerHeightGenerators(new RNG(seed), RUNTIME); tasks.add(executor.submit(() -> { assertTrue(start.await(5, TimeUnit.SECONDS)); for (int sample = 0; sample < 30; sample++) { - assertGenerators(expected, shared.getLayerHeightGenerators(new RNG(seed), null)); + assertGenerators(expected, shared.getLayerHeightGenerators(new RNG(seed), RUNTIME)); } return null; })); @@ -91,28 +95,22 @@ public class IrisBiomeLayerHeightCacheTest { } @Test - public void runtimeAndDataIdentitiesDoNotReuseHeightGenerators() { + public void runtimeIdentitiesDoNotReuseHeightGenerators() { IrisBiome biome = biome(); - IrisData data = mock(IrisData.class); - IrisData otherData = mock(IrisData.class); - Engine first = mock(Engine.class); - Engine second = mock(Engine.class); - when(data.getEngine()).thenReturn(first); - when(otherData.getEngine()).thenReturn(first); + IrisData data = MockPackData.create(); + PackRuntime standalone = data.standalonePackRuntime(); + PackRuntime otherData = MockPackData.create().standalonePackRuntime(); + PackRuntime engineScope = PackRuntime.forEngine(mock(Engine.class), data); RNG rng = new RNG(TERRAIN_SEED); - KList original = biome.getLayerHeightGenerators(rng, data); - assertSame(original, biome.getLayerHeightGenerators(rng, data)); - KList other = biome.getLayerHeightGenerators(rng, otherData); - assertNotSame(original, other); - assertNotSame(original.get(0), other.get(0)); - assertGenerators(original, other); - when(data.getEngine()).thenReturn(second); - KList replacement = biome.getLayerHeightGenerators(rng, data); - assertNotSame(original, replacement); - assertNotSame(original.get(0), replacement.get(0)); - assertGenerators(original, replacement); - when(data.getEngine()).thenReturn(first); - assertSame(original, biome.getLayerHeightGenerators(rng, data)); + KList original = biome.getLayerHeightGenerators(rng, standalone); + assertSame(original, biome.getLayerHeightGenerators(rng, standalone)); + for (PackRuntime other : new PackRuntime[]{otherData, engineScope}) { + KList separate = biome.getLayerHeightGenerators(rng, other); + assertNotSame(original, separate); + assertNotSame(original.get(0), separate.get(0)); + assertGenerators(original, separate); + } + assertSame(original, biome.getLayerHeightGenerators(rng, standalone)); } @Test @@ -126,12 +124,12 @@ public class IrisBiomeLayerHeightCacheTest { IrisBiome isolated = materialBiome(first, second); RNG rng = new RNG(seed); for (int x = -65; x <= 65; x += 7) { - assertEquals(isolated.generateLayers(dimension, x, -x, rng, 64, 120, null, null), - shared.generateLayers(dimension, x, -x, rng, 64, 120, null, null)); - assertEquals(isolated.generateCeilingLayers(dimension, x, -x, rng, 64, 120, null, null), - shared.generateCeilingLayers(dimension, x, -x, rng, 64, 120, null, null)); - assertEquals(isolated.generateSeaLayers(x, -x, rng, 64, null), - shared.generateSeaLayers(x, -x, rng, 64, null)); + assertEquals(isolated.generateLayers(dimension, x, -x, rng, 64, 120, RUNTIME, null), + shared.generateLayers(dimension, x, -x, rng, 64, 120, RUNTIME, null)); + assertEquals(isolated.generateCeilingLayers(dimension, x, -x, rng, 64, 120, RUNTIME, null), + shared.generateCeilingLayers(dimension, x, -x, rng, 64, 120, RUNTIME, null)); + assertEquals(isolated.generateSeaLayers(x, -x, rng, 64, RUNTIME), + shared.generateSeaLayers(x, -x, rng, 64, RUNTIME)); } } } @@ -139,11 +137,11 @@ public class IrisBiomeLayerHeightCacheTest { @Test public void evictionRecomputesTheSameNoise() { IrisBiome biome = biome(); - KList original = biome.getLayerHeightGenerators(new RNG(TERRAIN_SEED), null); + KList original = biome.getLayerHeightGenerators(new RNG(TERRAIN_SEED), RUNTIME); for (int seed = 0; seed < 96; seed++) { - biome.getLayerHeightGenerators(new RNG(seed), null); + biome.getLayerHeightGenerators(new RNG(seed), RUNTIME); } - KList recomputed = biome.getLayerHeightGenerators(new RNG(TERRAIN_SEED), null); + KList recomputed = biome.getLayerHeightGenerators(new RNG(TERRAIN_SEED), RUNTIME); assertNotSame(original, recomputed); assertNotSame(original.get(0), recomputed.get(0)); assertGenerators(original, recomputed); diff --git a/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeLayerSlopeSourceTest.java b/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeLayerSlopeSourceTest.java index fccdf0d74..9335920c3 100644 --- a/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeLayerSlopeSourceTest.java +++ b/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeLayerSlopeSourceTest.java @@ -1,5 +1,7 @@ package art.arcane.iris.generation.biome; +import art.arcane.iris.generation.runtime.PackRuntime; +import art.arcane.iris.testsupport.MockPackData; import art.arcane.iris.generation.terrain.IrisDimension; import art.arcane.iris.generation.terrain.IrisSlopeClip; @@ -52,7 +54,7 @@ public final class IrisBiomeLayerSlopeSourceTest { @Test public void lowerLedgeSlopeControlsSurfacePaletteSelection() { - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); IrisComplex complex = mock(IrisComplex.class); IrisBiomePaletteLayer grass = mock(IrisBiomePaletteLayer.class); CNG heightGenerator = mock(CNG.class); @@ -66,14 +68,15 @@ public final class IrisBiomeLayerSlopeSourceTest { when(grass.getMinHeight()).thenReturn(1); when(grass.getMaxHeight()).thenReturn(1); when(grass.getSlopeCondition()).thenReturn(new IrisSlopeClip(0D, 2.6D)); - when(grass.getHeightGenerator(any(RNG.class), same(data))).thenReturn(heightGenerator); + when(grass.getHeightGenerator(any(RNG.class), MockPackData.runtimeOf(data))).thenReturn(heightGenerator); when(heightGenerator.fit(1, 1, 12D, -8D)).thenReturn(1); - when(grass.get(rng, 0, 12D, 0D, -8D, data)).thenReturn(block); + PaletteLayerRuntime grassRuntime = data.standalonePackRuntime().paletteLayer(grass); + when(grass.get(rng, 0, 12D, 0D, -8D, grassRuntime)).thenReturn(block); KList ledge = biome.generateLayers( - rockFallbackDimension(), 12D, -8D, rng, 1, 32, data, complex); + rockFallbackDimension(), 12D, -8D, rng, 1, 32, data.standalonePackRuntime(), complex); KList cap = biome.generateLayers( - rockFallbackDimension(), 12D, -8D, rng, 1, 96, data, complex); + rockFallbackDimension(), 12D, -8D, rng, 1, 96, data.standalonePackRuntime(), complex); assertEquals(1, ledge.size()); assertSame(block, ledge.get(0)); @@ -84,7 +87,7 @@ public final class IrisBiomeLayerSlopeSourceTest { @Test @SuppressWarnings("unchecked") public void explicitSlopeStreamControlsSurfacePaletteSelection() { - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); IrisComplex hostComplex = mock(IrisComplex.class); ProceduralStream hostSlope = mock(ProceduralStream.class); ProceduralStream sourceSlope = mock(ProceduralStream.class); @@ -106,14 +109,15 @@ public final class IrisBiomeLayerSlopeSourceTest { when(paletteLayer.getMinHeight()).thenReturn(1); when(paletteLayer.getMaxHeight()).thenReturn(1); when(paletteLayer.getSlopeCondition()).thenReturn(new IrisSlopeClip(5D, 5D)); - when(paletteLayer.getHeightGenerator(any(RNG.class), same(data))).thenReturn(heightGenerator); + when(paletteLayer.getHeightGenerator(any(RNG.class), MockPackData.runtimeOf(data))).thenReturn(heightGenerator); when(heightGenerator.fit(1, 1, 12D, -8D)).thenReturn(1); - when(paletteLayer.get(rng, 0, 12D, 0D, -8D, data)).thenReturn(surfaceBlock); + PaletteLayerRuntime paletteLayerRuntime = data.standalonePackRuntime().paletteLayer(paletteLayer); + when(paletteLayer.get(rng, 0, 12D, 0D, -8D, paletteLayerRuntime)).thenReturn(surfaceBlock); KList hostLayers = biome.generateLayers( - rockFallbackDimension(), 12D, -8D, rng, 1, 32, data, hostComplex); + rockFallbackDimension(), 12D, -8D, rng, 1, 32, data.standalonePackRuntime(), hostComplex); KList sourceLayers = biome.generateLayersWithSlope( - rockFallbackDimension(), 12D, -8D, rng, 1, 32, data, sourceSlope); + rockFallbackDimension(), 12D, -8D, rng, 1, 32, data.standalonePackRuntime(), sourceSlope); assertTrue(hostLayers.isEmpty()); assertEquals(1, sourceLayers.size()); diff --git a/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeLockedLayerTest.java b/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeLockedLayerTest.java index ea911a970..696578058 100644 --- a/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeLockedLayerTest.java +++ b/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeLockedLayerTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.biome; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.noise.NoiseStyle; import art.arcane.iris.generation.terrain.IrisSlopeClip; import art.arcane.volmlib.nativelib.terrain.NativeBlockState; @@ -24,6 +25,8 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; public class IrisBiomeLockedLayerTest { + private static final PackRuntime RUNTIME = PackRuntime.standalone(null); + @Test public void repeatsLockedLayersAcrossTheReferenceHeight() { NativeBlockState first = mock(NativeBlockState.class); @@ -38,7 +41,7 @@ public class IrisBiomeLockedLayerTest { int[][] expectedCycles = {{1, 2, 0}, {0, 1, 2}, {0, 1, 2}, {2, 0, 1}, {1, 2, 0}, {1, 2, 0}}; for (int index = 0; index < heights.length; index++) { KList blocks = biome.generateLockedLayers( - 13, -27, new RNG(37), 8, heights[index], null, null); + 13, -27, new RNG(37), 8, heights[index], RUNTIME, null); assertEquals(8, blocks.size()); for (int depth = 0; depth < blocks.size(); depth++) { assertEquals(cycle.get(expectedCycles[index][depth % 3]), blocks.get(depth)); @@ -56,8 +59,8 @@ public class IrisBiomeLockedLayerTest { IrisBiomeCeilingLayerTest.layer(second, 1), IrisBiomeCeilingLayerTest.layer(third, 1))); for (int surface : new int[]{-17, 20, 512, 1000}) { - KList lower = biome.generateLockedLayers(13, -27, new RNG(37), 8, surface, null, null); - KList higher = biome.generateLockedLayers(13, -27, new RNG(37), 9, surface + 1, null, null); + KList lower = biome.generateLockedLayers(13, -27, new RNG(37), 8, surface, RUNTIME, null); + KList higher = biome.generateLockedLayers(13, -27, new RNG(37), 9, surface + 1, RUNTIME, null); for (int depth = 0; depth < lower.size(); depth++) { assertEquals(lower.get(depth), higher.get(depth + 1)); } @@ -86,7 +89,7 @@ public class IrisBiomeLockedLayerTest { for (int height : heights) { for (int depth : depths) { assertEquals(expandedBands(biome, x, -x, rng, depth, height, 0D), - biome.generateLockedLayers(x, -x, rng, depth, height, null, null)); + biome.generateLockedLayers(x, -x, rng, depth, height, RUNTIME, null)); } } } @@ -100,17 +103,17 @@ public class IrisBiomeLockedLayerTest { palette(1, 1, 1D, block), palette(2, 2, 1D, (NativeBlockState) null))); RNG rng = new RNG(37L); assertEquals(expandedBands(biome, 3D, -11D, rng, 30, 1000, 0D), - biome.generateLockedLayers(3D, -11D, rng, 30, 1000, null, null)); + biome.generateLockedLayers(3D, -11D, rng, 30, 1000, RUNTIME, null)); } @Test public void zeroThicknessAndEmptyPalettesProduceNoBands() { IrisBiome biome = new IrisBiome().setLockLayers(true).setLayers(new KList<>()); RNG rng = new RNG(37L); - assertTrue(biome.generateLockedLayers(0D, 0D, rng, 7, 64, null, null).isEmpty()); + assertTrue(biome.generateLockedLayers(0D, 0D, rng, 7, 64, RUNTIME, null).isEmpty()); biome.setLayers(new KList<>(palette(0, 0, 1D, mock(NativeBlockState.class)))); - assertTrue(biome.generateLockedLayers(0D, 0D, rng, 7, 64, null, null).isEmpty()); - assertTrue(biome.generateLockedLayers(0D, 0D, rng, -1, 64, null, null).isEmpty()); + assertTrue(biome.generateLockedLayers(0D, 0D, rng, 7, 64, RUNTIME, null).isEmpty()); + assertTrue(biome.generateLockedLayers(0D, 0D, rng, -1, 64, RUNTIME, null).isEmpty()); } @Test @@ -119,8 +122,9 @@ public class IrisBiomeLockedLayerTest { mock(NativeBlockState.class), mock(NativeBlockState.class))); IrisBiome biome = new IrisBiome().setLockLayers(true).setLayers(new KList<>(layer)); RNG rng = new RNG(37L); - assertEquals(7, biome.generateLockedLayers(13D, -27D, rng, 7, 64, null, null).size()); - verify(layer, times(7)).get(same(rng), anyInt(), anyDouble(), anyDouble(), anyDouble(), isNull()); + assertEquals(7, biome.generateLockedLayers(13D, -27D, rng, 7, 64, RUNTIME, null).size()); + PaletteLayerRuntime layerRuntime = RUNTIME.paletteLayer(layer); + verify(layer, times(7)).get(same(rng), anyInt(), anyDouble(), anyDouble(), anyDouble(), same(layerRuntime)); } @Test @@ -129,8 +133,9 @@ public class IrisBiomeLockedLayerTest { mock(NativeBlockState.class), mock(NativeBlockState.class))); IrisBiome biome = new IrisBiome().setLockLayers(true).setLockLayersMax(100).setLayers(new KList<>(layer)); RNG rng = new RNG(37L); - assertEquals(100, biome.generateLockedLayers(13D, -27D, rng, 100, 64, null, null).size()); - verify(layer, times(3)).get(same(rng), anyInt(), anyDouble(), anyDouble(), anyDouble(), isNull()); + assertEquals(100, biome.generateLockedLayers(13D, -27D, rng, 100, 64, RUNTIME, null).size()); + PaletteLayerRuntime layerRuntime = RUNTIME.paletteLayer(layer); + verify(layer, times(3)).get(same(rng), anyInt(), anyDouble(), anyDouble(), anyDouble(), same(layerRuntime)); } @Test @@ -144,7 +149,7 @@ public class IrisBiomeLockedLayerTest { for (double slope : slopes) { ProceduralStream slopeStream = ProceduralStream.ofDouble((x, z) -> slope); assertEquals(expandedBands(biome, 13D, -27D, rng, 30, 64, slope), - biome.generateLayersWithSlope(null, 13D, -27D, rng, 30, 64, null, slopeStream)); + biome.generateLayersWithSlope(null, 13D, -27D, rng, 30, 64, RUNTIME, slopeStream)); } } @@ -154,8 +159,9 @@ public class IrisBiomeLockedLayerTest { IrisBiome biome = new IrisBiome().setLockLayers(true).setLayers(new KList<>(layer)); RNG rng = new RNG(37L); IllegalStateException failure = new IllegalStateException("Palette unavailable"); - doThrow(failure).when(layer).get(same(rng), anyInt(), anyDouble(), anyDouble(), anyDouble(), isNull()); - assertTrue(biome.generateLockedLayers(0D, 0D, rng, 7, 64, null, null).isEmpty()); + PaletteLayerRuntime layerRuntime = RUNTIME.paletteLayer(layer); + doThrow(failure).when(layer).get(same(rng), anyInt(), anyDouble(), anyDouble(), anyDouble(), same(layerRuntime)); + assertTrue(biome.generateLockedLayers(0D, 0D, rng, 7, 64, RUNTIME, null).isEmpty()); } private static IrisBiomePaletteLayer palette(int minimum, int maximum, double zoom, NativeBlockState... blocks) { @@ -169,7 +175,7 @@ public class IrisBiomeLockedLayerTest { int maxDepth, int height, double slope) { KList expanded = new KList<>(); KList result = new KList<>(); - KList heights = biome.getLayerHeightGenerators(rng, null); + KList heights = biome.getLayerHeightGenerators(rng, RUNTIME); for (int index = 0; index < biome.getLayers().size(); index++) { IrisBiomePaletteLayer layer = biome.getLayers().get(index); double zoom = layer.getZoom(); @@ -178,7 +184,7 @@ public class IrisBiomeLockedLayerTest { continue; } for (int offset = 0; offset < thickness; offset++) { - expanded.add(layer.get(rng, index + offset, (x + offset) / zoom, offset, (z - offset) / zoom, null)); + expanded.add(layer.get(rng, index + offset, (x + offset) / zoom, offset, (z - offset) / zoom, RUNTIME)); } } if (!expanded.isEmpty()) { diff --git a/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomePaletteLayerGeneratorCacheTest.java b/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomePaletteLayerGeneratorCacheTest.java index 4639cdad9..46e5f5262 100644 --- a/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomePaletteLayerGeneratorCacheTest.java +++ b/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomePaletteLayerGeneratorCacheTest.java @@ -1,5 +1,7 @@ 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.IrisGeneratorStyle; import art.arcane.iris.pack.loading.IrisData; @@ -31,11 +33,11 @@ public final class IrisBiomePaletteLayerGeneratorCacheTest { GeneratorFixture fixture = new GeneratorFixture(); assertSame(fixture.carveGenerator, - fixture.layer.getLayerGenerator(new RNG(11L), SIGNATURE, fixture.data)); + fixture.layer.getLayerGenerator(new RNG(11L), SIGNATURE, fixture.data.standalonePackRuntime())); assertSame(fixture.postGenerator, - fixture.layer.getLayerGenerator(new RNG(29L), SIGNATURE, fixture.data)); + fixture.layer.getLayerGenerator(new RNG(29L), SIGNATURE, fixture.data.standalonePackRuntime())); assertSame(fixture.carveGenerator, - fixture.layer.getLayerGenerator(new RNG(11L), SIGNATURE, fixture.data)); + fixture.layer.getLayerGenerator(new RNG(11L), SIGNATURE, fixture.data.standalonePackRuntime())); } @Test @@ -43,9 +45,9 @@ public final class IrisBiomePaletteLayerGeneratorCacheTest { GeneratorFixture fixture = new GeneratorFixture(); assertSame(fixture.postGenerator, - fixture.layer.getLayerGenerator(new RNG(29L), SIGNATURE, fixture.data)); + fixture.layer.getLayerGenerator(new RNG(29L), SIGNATURE, fixture.data.standalonePackRuntime())); assertSame(fixture.carveGenerator, - fixture.layer.getLayerGenerator(new RNG(11L), SIGNATURE, fixture.data)); + fixture.layer.getLayerGenerator(new RNG(11L), SIGNATURE, fixture.data.standalonePackRuntime())); } @Test @@ -56,11 +58,11 @@ public final class IrisBiomePaletteLayerGeneratorCacheTest { try { Future carve = executor.submit(() -> { assertTrue(start.await(5L, TimeUnit.SECONDS)); - return fixture.layer.getLayerGenerator(new RNG(11L), SIGNATURE, fixture.data); + return fixture.layer.getLayerGenerator(new RNG(11L), SIGNATURE, fixture.data.standalonePackRuntime()); }); Future post = executor.submit(() -> { assertTrue(start.await(5L, TimeUnit.SECONDS)); - return fixture.layer.getLayerGenerator(new RNG(29L), SIGNATURE, fixture.data); + return fixture.layer.getLayerGenerator(new RNG(29L), SIGNATURE, fixture.data.standalonePackRuntime()); }); start.countDown(); @@ -72,7 +74,7 @@ public final class IrisBiomePaletteLayerGeneratorCacheTest { } private static final class GeneratorFixture { - private final IrisData data = mock(IrisData.class); + private final IrisData data = MockPackData.create(); private final Engine engine = mock(Engine.class); private final IrisGeneratorStyle style = mock(IrisGeneratorStyle.class); private final CNG carveGenerator = mock(CNG.class); @@ -85,7 +87,7 @@ public final class IrisBiomePaletteLayerGeneratorCacheTest { 11L + SIGNATURE + LAYER_SIGNATURE, carveGenerator, 29L + SIGNATURE + LAYER_SIGNATURE, postGenerator ); - when(style.create(any(RNG.class), same(data), same(engine))).thenAnswer(invocation -> { + when(style.createNoCache(any(RNG.class), any())).thenAnswer(invocation -> { RNG rng = invocation.getArgument(0); return generators.get(rng.getSeed()); }); diff --git a/core/src/test/java/art/arcane/iris/generation/biome/IrisSurfaceLayerFallbackTest.java b/core/src/test/java/art/arcane/iris/generation/biome/IrisSurfaceLayerFallbackTest.java index a3258ac5d..c6f7c8102 100644 --- a/core/src/test/java/art/arcane/iris/generation/biome/IrisSurfaceLayerFallbackTest.java +++ b/core/src/test/java/art/arcane/iris/generation/biome/IrisSurfaceLayerFallbackTest.java @@ -1,5 +1,7 @@ package art.arcane.iris.generation.biome; +import art.arcane.iris.generation.runtime.PackRuntime; +import art.arcane.iris.testsupport.MockPackData; import art.arcane.iris.generation.terrain.IrisDimension; import art.arcane.iris.generation.terrain.IrisSlopeClip; @@ -20,7 +22,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public final class IrisSurfaceLayerFallbackTest { - private final IrisData data = mock(IrisData.class); + private final IrisData data = MockPackData.create(); private final IrisBiomePaletteLayer layer = mock(IrisBiomePaletteLayer.class); private final CNG heightGenerator = mock(CNG.class); private final NativeBlockState surfaceBlock = mock(NativeBlockState.class); @@ -34,16 +36,17 @@ public final class IrisSurfaceLayerFallbackTest { when(layer.getZoom()).thenReturn(1D); when(layer.getMinHeight()).thenReturn(1); when(layer.getMaxHeight()).thenReturn(2); - when(layer.getHeightGenerator(any(RNG.class), same(data))).thenReturn(heightGenerator); + when(layer.getHeightGenerator(any(RNG.class), MockPackData.runtimeOf(data))).thenReturn(heightGenerator); when(heightGenerator.fit(1, 2, 12D, -8D)).thenReturn(2); - when(layer.get(rng, 0, 12D, 0D, -8D, data)).thenReturn(surfaceBlock); - when(layer.get(rng, 1, 13D, 1D, -9D, data)).thenReturn(secondBlock); + PaletteLayerRuntime layerRuntime = data.standalonePackRuntime().paletteLayer(layer); + when(layer.get(rng, 0, 12D, 0D, -8D, layerRuntime)).thenReturn(surfaceBlock); + when(layer.get(rng, 1, 13D, 1D, -9D, layerRuntime)).thenReturn(secondBlock); when(slopeStream.getDouble(12D, -8D)).thenReturn(9D); return new IrisBiome().setLayers(new KList<>(layer)); } private KList generate(IrisBiome biome, IrisDimension dim) { - return biome.generateLayersWithSlope(dim, 12D, -8D, rng, 4, 32, data, slopeStream); + return biome.generateLayersWithSlope(dim, 12D, -8D, rng, 4, 32, data.standalonePackRuntime(), slopeStream); } @Test @@ -125,7 +128,7 @@ public final class IrisSurfaceLayerFallbackTest { when(layer.getSlopeCondition()).thenReturn(new IrisSlopeClip(0D, 4D)); IrisDimension dimension = new IrisDimension(); - assertTrue(biome.generateLayersWithSlope(dimension, 12D, -8D, rng, 0, 32, data, slopeStream).isEmpty()); + assertTrue(biome.generateLayersWithSlope(dimension, 12D, -8D, rng, 0, 32, data.standalonePackRuntime(), slopeStream).isEmpty()); assertTrue(generate(biome.setLockLayersMax(0), dimension).isEmpty()); assertTrue(generate(biome.setLockLayersMax(7).setLayers(new KList<>()), dimension).isEmpty()); } diff --git a/core/src/test/java/art/arcane/iris/generation/cache/LazyBoundedCacheTest.java b/core/src/test/java/art/arcane/iris/generation/cache/LazyBoundedCacheTest.java deleted file mode 100644 index 1d9df8b36..000000000 --- a/core/src/test/java/art/arcane/iris/generation/cache/LazyBoundedCacheTest.java +++ /dev/null @@ -1,139 +0,0 @@ -package art.arcane.iris.generation.cache; - -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -public class LazyBoundedCacheTest { - @Test - public void backingStorageIsLazy() { - LazyBoundedCache cache = new LazyBoundedCache<>(8); - - assertFalse(cache.isInitialized()); - assertEquals(0, cache.size()); - assertNull(cache.computeIfAbsent("missing", ignored -> null)); - assertFalse(cache.isInitialized()); - - Object expected = new Object(); - assertSame(expected, cache.computeIfAbsent("present", ignored -> expected)); - assertTrue(cache.isInitialized()); - assertEquals(1, cache.size()); - } - - @Test - public void capacityUsesAccessOrder() { - LazyBoundedCache cache = new LazyBoundedCache<>(8); - Object first = new Object(); - cache.computeIfAbsent(0, ignored -> first); - for (int key = 1; key < 8; key++) { - cache.computeIfAbsent(key, ignored -> new Object()); - } - - assertSame(first, cache.computeIfAbsent(0, ignored -> new Object())); - cache.computeIfAbsent(8, ignored -> new Object()); - - AtomicInteger reloads = new AtomicInteger(); - cache.computeIfAbsent(1, ignored -> { - reloads.incrementAndGet(); - return new Object(); - }); - assertEquals(1, reloads.get()); - assertEquals(8, cache.size()); - assertSame(first, cache.computeIfAbsent(0, ignored -> new Object())); - } - - @Test - public void concurrentSameKeyComputesOnce() throws Exception { - int threadCount = 16; - LazyBoundedCache cache = new LazyBoundedCache<>(8); - CountDownLatch start = new CountDownLatch(1); - CountDownLatch resolverEntered = new CountDownLatch(1); - CountDownLatch releaseResolver = new CountDownLatch(1); - AtomicInteger computations = new AtomicInteger(); - Object expected = new Object(); - ExecutorService executor = Executors.newFixedThreadPool(threadCount); - List> futures = new ArrayList<>(threadCount); - try { - for (int index = 0; index < threadCount; index++) { - futures.add(executor.submit(() -> { - start.await(); - return cache.computeIfAbsent("shared", ignored -> { - computations.incrementAndGet(); - resolverEntered.countDown(); - await(releaseResolver); - return expected; - }); - })); - } - start.countDown(); - assertTrue(resolverEntered.await(5L, TimeUnit.SECONDS)); - releaseResolver.countDown(); - for (Future future : futures) { - assertSame(expected, future.get(5L, TimeUnit.SECONDS)); - } - } finally { - releaseResolver.countDown(); - executor.shutdownNow(); - assertTrue(executor.awaitTermination(5L, TimeUnit.SECONDS)); - } - - assertEquals(1, computations.get()); - assertEquals(1, cache.size()); - } - - @Test - public void keysRetainIdentityEqualitySemantics() { - Object firstIdentity = new String("same"); - Object secondIdentity = new String("same"); - LazyBoundedCache cache = new LazyBoundedCache<>(8); - Object firstValue = new Object(); - - assertSame(firstValue, cache.computeIfAbsent(new IdentityKey(firstIdentity), ignored -> firstValue)); - assertSame(firstValue, cache.computeIfAbsent(new IdentityKey(firstIdentity), ignored -> new Object())); - assertNotSame(firstValue, cache.computeIfAbsent(new IdentityKey(secondIdentity), ignored -> new Object())); - assertEquals(2, cache.size()); - } - - private static void await(CountDownLatch latch) { - try { - if (!latch.await(5L, TimeUnit.SECONDS)) { - throw new IllegalStateException("Timed out waiting for cache test latch"); - } - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new IllegalStateException(e); - } - } - - private static final class IdentityKey { - private final Object identity; - - private IdentityKey(Object identity) { - this.identity = identity; - } - - @Override - public boolean equals(Object other) { - return other instanceof IdentityKey key && identity == key.identity; - } - - @Override - public int hashCode() { - return System.identityHashCode(identity); - } - } -} diff --git a/core/src/test/java/art/arcane/iris/generation/cave/IrisCaveProfileSamplerTest.java b/core/src/test/java/art/arcane/iris/generation/cave/IrisCaveProfileSamplerTest.java index 3eeac84a4..419a80da1 100644 --- a/core/src/test/java/art/arcane/iris/generation/cave/IrisCaveProfileSamplerTest.java +++ b/core/src/test/java/art/arcane/iris/generation/cave/IrisCaveProfileSamplerTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.cave; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.NoiseStyle; import art.arcane.iris.generation.noise.IrisStyledRange; @@ -26,7 +27,7 @@ public class IrisCaveProfileSamplerTest { public void resolvesThresholdNoiseOnceWhilePreservingCoordinateDecisions() { IrisGeneratorStyle style = mock(IrisGeneratorStyle.class); CNG thresholdNoise = mock(CNG.class); - when(style.create(any(), isNull())).thenReturn(thresholdNoise); + when(style.create(any(), any(PackRuntime.class))).thenReturn(thresholdNoise); when(thresholdNoise.fitDouble(anyDouble(), anyDouble(), anyDouble(), anyDouble())) .thenAnswer(invocation -> (double) invocation.getArgument(2) * 0.003D + (double) invocation.getArgument(3) * 0.005D); @@ -41,7 +42,7 @@ public class IrisCaveProfileSamplerTest { assertEquals(density <= threshold, sampler.shouldCarve(x, y, z, 0.75D)); } } - verify(style, times(1)).create(any(), isNull()); + verify(style, times(1)).create(any(), any(PackRuntime.class)); verify(thresholdNoise, times(585)).fitDouble(anyDouble(), anyDouble(), anyDouble(), anyDouble()); } @@ -58,7 +59,7 @@ public class IrisCaveProfileSamplerTest { for (int z : coordinates) { for (int y = -60; y <= 60; y += 3) { for (double floatingThreshold : floatingThresholds) { - double threshold = range.get(thresholdRng, x, z, null) - profile.getThresholdBias(); + double threshold = range.get(thresholdRng, x, z, PackRuntime.standalone(null)) - profile.getThresholdBias(); threshold += (1D - Math.max(0D, Math.min(1D, floatingThreshold))) * 0.2D; assertEquals("x=" + x + " y=" + y + " z=" + z + " floating=" + floatingThreshold, density(x, y, z) <= threshold, sampler.shouldCarve(x, y, z, floatingThreshold)); @@ -98,7 +99,7 @@ public class IrisCaveProfileSamplerTest { when(densityNoise.noiseFastSigned3D(anyDouble(), anyDouble(), anyDouble())).thenAnswer(invocation -> density(invocation.getArgument(0), invocation.getArgument(1), invocation.getArgument(2))); IrisGeneratorStyle densityStyle = mock(IrisGeneratorStyle.class); - when(densityStyle.create(any(), isNull())).thenReturn(densityNoise); + when(densityStyle.create(any(), any(PackRuntime.class))).thenReturn(densityNoise); IrisCaveProfile profile = mock(IrisCaveProfile.class); when(profile.getBaseDensityStyle()).thenReturn(densityStyle); when(profile.getDetailDensityStyle()).thenReturn(densityStyle); diff --git a/core/src/test/java/art/arcane/iris/generation/decoration/DecorationFailureContainmentTest.java b/core/src/test/java/art/arcane/iris/generation/decoration/DecorationFailureContainmentTest.java index 6b93c0ff4..96d589b9e 100644 --- a/core/src/test/java/art/arcane/iris/generation/decoration/DecorationFailureContainmentTest.java +++ b/core/src/test/java/art/arcane/iris/generation/decoration/DecorationFailureContainmentTest.java @@ -8,7 +8,7 @@ import art.arcane.iris.generation.runtime.IrisComplex; import art.arcane.iris.generation.runtime.SeedManager; import art.arcane.iris.generation.terrain.InferredType; import art.arcane.iris.generation.terrain.IrisDimension; -import art.arcane.iris.pack.loading.IrisData; +import art.arcane.iris.testsupport.MockPackData; import art.arcane.iris.spi.IrisPlatform; import art.arcane.iris.spi.IrisPlatforms; import art.arcane.iris.spi.PlatformRegistries; @@ -89,7 +89,7 @@ public class DecorationFailureContainmentTest { doReturn("minecraft:vine").when(vine).materialKey(); IrisDecorator decorator = mock(IrisDecorator.class); - doReturn(true).when(decorator).passesChanceGate(any(), anyDouble(), anyDouble(), any()); + doReturn(true).when(decorator).passesChanceGate(any(), anyDouble(), anyDouble(), any(DecoratorRuntime.class)); doReturn(true).when(decorator).isForcePlace(); doReturn(vine).when(decorator).pickBlockData(any(), any(), anyDouble(), anyDouble()); doReturn(new NativeBlockState[]{vine}).when(decorator).getBlockDataArray(any()); @@ -121,7 +121,7 @@ public class DecorationFailureContainmentTest { private static Engine engine() { Engine engine = mock(Engine.class); doReturn(mock(SeedManager.class)).when(engine).getSeedManager(); - doReturn(mock(IrisData.class)).when(engine).getData(); + doReturn(MockPackData.create()).when(engine).getData(); IrisDimension dimension = mock(IrisDimension.class); doReturn(63).when(dimension).getFluidHeight(); doReturn(dimension).when(engine).getDimension(); diff --git a/core/src/test/java/art/arcane/iris/generation/decoration/DecoratorCoreTest.java b/core/src/test/java/art/arcane/iris/generation/decoration/DecoratorCoreTest.java index ef27a1269..cf4a68eb0 100644 --- a/core/src/test/java/art/arcane/iris/generation/decoration/DecoratorCoreTest.java +++ b/core/src/test/java/art/arcane/iris/generation/decoration/DecoratorCoreTest.java @@ -1,5 +1,7 @@ package art.arcane.iris.generation.decoration; +import art.arcane.iris.generation.runtime.PackRuntime; +import art.arcane.iris.testsupport.MockPackData; import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.block.IrisBlockData; @@ -86,39 +88,42 @@ public class DecoratorCoreTest { @Test public void pickDecorator_emptyBucket_returnsNull() { IrisBiome biome = mock(IrisBiome.class); - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); + PackRuntime runtime = data.standalonePackRuntime(); when(biome.getDecoratorBucket(IrisDecorationPart.NONE)).thenReturn(new IrisDecorator[0]); IrisDecorator result = DecoratorCore.pickDecorator( - biome, IrisDecorationPart.NONE, new RNG(1L), new RNG(2L), data, 0.0, 0.0); + biome, IrisDecorationPart.NONE, new RNG(1L), new RNG(2L), runtime, 0.0, 0.0); assertNull(result); } @Test public void pickDecorator_nonePassChanceGate_returnsNull() { IrisBiome biome = mock(IrisBiome.class); - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); + PackRuntime runtime = data.standalonePackRuntime(); IrisDecorator d = mock(IrisDecorator.class); - when(d.passesChanceGate(any(RNG.class), anyDouble(), anyDouble(), any(IrisData.class))).thenReturn(false); + when(d.passesChanceGate(any(RNG.class), anyDouble(), anyDouble(), any(DecoratorRuntime.class))).thenReturn(false); when(biome.getDecoratorBucket(IrisDecorationPart.NONE)).thenReturn(new IrisDecorator[]{d}); IrisDecorator result = DecoratorCore.pickDecorator( - biome, IrisDecorationPart.NONE, new RNG(1L), new RNG(2L), data, 0.0, 0.0); + biome, IrisDecorationPart.NONE, new RNG(1L), new RNG(2L), runtime, 0.0, 0.0); assertNull(result); } @Test public void pickDecorator_singleCandidate_alwaysReturnsThat() { IrisBiome biome = mock(IrisBiome.class); - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); + PackRuntime runtime = data.standalonePackRuntime(); IrisDecorator d = mock(IrisDecorator.class); - when(d.passesChanceGate(any(RNG.class), anyDouble(), anyDouble(), any(IrisData.class))).thenReturn(true); + when(d.passesChanceGate(any(RNG.class), anyDouble(), anyDouble(), any(DecoratorRuntime.class))).thenReturn(true); when(biome.getDecoratorBucket(IrisDecorationPart.NONE)).thenReturn(new IrisDecorator[]{d}); RNG gRNG = new RNG(42L); for (int t = 0; t < 50; t++) { IrisDecorator result = DecoratorCore.pickDecorator( - biome, IrisDecorationPart.NONE, gRNG, new RNG(t * 13L + 7), data, 0.0, 0.0); + biome, IrisDecorationPart.NONE, gRNG, new RNG(t * 13L + 7), runtime, 0.0, 0.0); assertSame(d, result); } } @@ -126,13 +131,14 @@ public class DecoratorCoreTest { @Test public void pickDecorator_multiplePassingCandidates_selectsUniformly() { IrisBiome biome = mock(IrisBiome.class); - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); + PackRuntime runtime = data.standalonePackRuntime(); int n = 4; IrisDecorator[] decorators = new IrisDecorator[n]; for (int i = 0; i < n; i++) { IrisDecorator d = mock(IrisDecorator.class); - when(d.passesChanceGate(any(RNG.class), anyDouble(), anyDouble(), any(IrisData.class))).thenReturn(true); + when(d.passesChanceGate(any(RNG.class), anyDouble(), anyDouble(), any(DecoratorRuntime.class))).thenReturn(true); decorators[i] = d; } when(biome.getDecoratorBucket(IrisDecorationPart.NONE)).thenReturn(decorators); @@ -143,7 +149,7 @@ public class DecoratorCoreTest { for (int t = 0; t < trials; t++) { IrisDecorator picked = DecoratorCore.pickDecorator( - biome, IrisDecorationPart.NONE, gRNG, new RNG(t * 31L + 3), data, 0.0, 0.0); + biome, IrisDecorationPart.NONE, gRNG, new RNG(t * 31L + 3), runtime, 0.0, 0.0); assertNotNull(picked); for (int i = 0; i < n; i++) { if (picked == decorators[i]) { @@ -164,22 +170,23 @@ public class DecoratorCoreTest { @Test public void singleStackTargetsBlockAboveSupport() { IrisDecorator decorator = mock(IrisDecorator.class); - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); + PackRuntime runtime = data.standalonePackRuntime(); NativeBlockState support = sturdyState(); NativeBlockState air = mock(NativeBlockState.class); NativeBlockState decorant = mock(NativeBlockState.class); when(air.isAir()).thenReturn(true); when(decorant.key()).thenReturn("minecraft:stone"); when(decorant.canPlaceOnto(support)).thenReturn(true); - when(decorator.getHeight(any(RNG.class), anyDouble(), anyDouble(), eq(data))).thenReturn(1); - when(decorator.pickBlockDataTop(any(RNG.class), eq(data), anyDouble(), anyDouble())).thenReturn(decorant); + when(decorator.getHeight(any(RNG.class), anyDouble(), anyDouble(), eq(runtime))).thenReturn(1); + when(decorator.pickBlockDataTop(any(RNG.class), eq(runtime), anyDouble(), anyDouble())).thenReturn(decorant); Hunk output = Hunk.newArrayHunk(1, 4, 1); output.set(0, 1, 0, support); output.set(0, 2, 0, air); DecoratorCore.PlaceOpts opts = new DecoratorCore.PlaceOpts(); - DecoratorCore.placeStackUp(decorator, 0, 0, 0, 0, 1, 3, output, new RNG(1L), data, opts); + DecoratorCore.placeStackUp(decorator, 0, 0, 0, 0, 1, 3, output, new RNG(1L), runtime, opts); assertSame(support, output.get(0, 1, 0)); assertSame(decorant, output.get(0, 2, 0)); @@ -188,21 +195,22 @@ public class DecoratorCoreTest { @Test public void singleStackDoesNotOverwriteOccupiedTarget() { IrisDecorator decorator = mock(IrisDecorator.class); - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); + PackRuntime runtime = data.standalonePackRuntime(); NativeBlockState support = sturdyState(); NativeBlockState occupied = mock(NativeBlockState.class); NativeBlockState decorant = mock(NativeBlockState.class); when(occupied.isAir()).thenReturn(false); when(occupied.isFluid()).thenReturn(false); - when(decorator.getHeight(any(RNG.class), anyDouble(), anyDouble(), eq(data))).thenReturn(1); - when(decorator.pickBlockDataTop(any(RNG.class), eq(data), anyDouble(), anyDouble())).thenReturn(decorant); + when(decorator.getHeight(any(RNG.class), anyDouble(), anyDouble(), eq(runtime))).thenReturn(1); + when(decorator.pickBlockDataTop(any(RNG.class), eq(runtime), anyDouble(), anyDouble())).thenReturn(decorant); Hunk output = Hunk.newArrayHunk(1, 4, 1); output.set(0, 1, 0, support); output.set(0, 2, 0, occupied); DecoratorCore.PlaceOpts opts = new DecoratorCore.PlaceOpts(); - DecoratorCore.placeStackUp(decorator, 0, 0, 0, 0, 1, 3, output, new RNG(1L), data, opts); + DecoratorCore.placeStackUp(decorator, 0, 0, 0, 0, 1, 3, output, new RNG(1L), runtime, opts); assertSame(support, output.get(0, 1, 0)); assertSame(occupied, output.get(0, 2, 0)); @@ -211,7 +219,8 @@ public class DecoratorCoreTest { @Test public void multiStackStopsBeforeOccupiedTarget() { IrisDecorator decorator = mock(IrisDecorator.class); - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); + PackRuntime runtime = data.standalonePackRuntime(); NativeBlockState support = sturdyState(); NativeBlockState air = mock(NativeBlockState.class); NativeBlockState occupied = mock(NativeBlockState.class); @@ -221,10 +230,10 @@ public class DecoratorCoreTest { when(occupied.isFluid()).thenReturn(false); when(decorant.key()).thenReturn("minecraft:tall_grass"); when(decorant.canPlaceOnto(support)).thenReturn(true); - when(decorator.getHeight(any(RNG.class), anyDouble(), anyDouble(), eq(data))).thenReturn(3); + when(decorator.getHeight(any(RNG.class), anyDouble(), anyDouble(), eq(runtime))).thenReturn(3); when(decorator.getTopThreshold()).thenReturn(0.75); - when(decorator.pickBlockData(any(RNG.class), eq(data), anyDouble(), anyDouble())).thenReturn(decorant); - when(decorator.pickBlockDataTop(any(RNG.class), eq(data), anyDouble(), anyDouble())).thenReturn(decorant); + when(decorator.pickBlockData(any(RNG.class), eq(runtime), anyDouble(), anyDouble())).thenReturn(decorant); + when(decorator.pickBlockDataTop(any(RNG.class), eq(runtime), anyDouble(), anyDouble())).thenReturn(decorant); Hunk output = Hunk.newArrayHunk(1, 5, 1); output.set(0, 1, 0, support); @@ -233,7 +242,7 @@ public class DecoratorCoreTest { output.set(0, 4, 0, air); DecoratorCore.PlaceOpts opts = new DecoratorCore.PlaceOpts(); - DecoratorCore.placeStackUp(decorator, 0, 0, 0, 0, 1, 4, output, new RNG(1L), data, opts); + DecoratorCore.placeStackUp(decorator, 0, 0, 0, 0, 1, 4, output, new RNG(1L), runtime, opts); assertSame(decorant, output.get(0, 2, 0)); assertSame(occupied, output.get(0, 3, 0)); @@ -243,19 +252,20 @@ public class DecoratorCoreTest { @Test public void descendingStackStopsAtLocalWorldFloor() { IrisDecorator decorator = mock(IrisDecorator.class); - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); + PackRuntime runtime = data.standalonePackRuntime(); NativeBlockState decorant = mock(NativeBlockState.class); when(decorant.key()).thenReturn("minecraft:stone"); - when(decorator.getHeight(any(RNG.class), anyDouble(), anyDouble(), eq(data))).thenReturn(2); + when(decorator.getHeight(any(RNG.class), anyDouble(), anyDouble(), eq(runtime))).thenReturn(2); when(decorator.getTopThreshold()).thenReturn(1.0); - when(decorator.pickBlockData(any(RNG.class), eq(data), anyDouble(), anyDouble())).thenReturn(decorant); - when(decorator.pickBlockDataTop(any(RNG.class), eq(data), anyDouble(), anyDouble())).thenReturn(decorant); + when(decorator.pickBlockData(any(RNG.class), eq(runtime), anyDouble(), anyDouble())).thenReturn(decorant); + when(decorator.pickBlockDataTop(any(RNG.class), eq(runtime), anyDouble(), anyDouble())).thenReturn(decorant); Hunk output = Hunk.newArrayHunk(1, 2, 1); DecoratorCore.PlaceOpts opts = new DecoratorCore.PlaceOpts(); DecoratorCore.placeStackDown( - decorator, 0, 0, 0, 0, 0, -64, output, new RNG(1L), data, 2, opts, null); + decorator, 0, 0, 0, 0, 0, -64, output, new RNG(1L), runtime, 2, opts, null); assertSame(decorant, output.get(0, 0, 0)); } @@ -263,16 +273,17 @@ public class DecoratorCoreTest { @Test public void singleDescendingStackPreservesTargetWhenPickIsNull() { IrisDecorator decorator = mock(IrisDecorator.class); - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); + PackRuntime runtime = data.standalonePackRuntime(); NativeBlockState existing = mock(NativeBlockState.class); - when(decorator.getHeight(any(RNG.class), anyDouble(), anyDouble(), eq(data))).thenReturn(1); + when(decorator.getHeight(any(RNG.class), anyDouble(), anyDouble(), eq(runtime))).thenReturn(1); Hunk output = Hunk.newArrayHunk(1, 2, 1); output.set(0, 0, 0, existing); DecoratorCore.PlaceOpts opts = new DecoratorCore.PlaceOpts(); DecoratorCore.placeStackDown( - decorator, 0, 0, 0, 0, 0, 0, output, new RNG(1L), data, 1, opts, null); + decorator, 0, 0, 0, 0, 0, 0, output, new RNG(1L), runtime, 1, opts, null); assertSame(existing, output.get(0, 0, 0)); } @@ -280,10 +291,11 @@ public class DecoratorCoreTest { @Test public void multiDescendingStackStopsWhenPickIsNull() { IrisDecorator decorator = mock(IrisDecorator.class); - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); + PackRuntime runtime = data.standalonePackRuntime(); NativeBlockState lowerExisting = mock(NativeBlockState.class); NativeBlockState upperExisting = mock(NativeBlockState.class); - when(decorator.getHeight(any(RNG.class), anyDouble(), anyDouble(), eq(data))).thenReturn(2); + when(decorator.getHeight(any(RNG.class), anyDouble(), anyDouble(), eq(runtime))).thenReturn(2); when(decorator.getTopThreshold()).thenReturn(1.0); Hunk output = Hunk.newArrayHunk(1, 2, 1); @@ -292,7 +304,7 @@ public class DecoratorCoreTest { DecoratorCore.PlaceOpts opts = new DecoratorCore.PlaceOpts(); DecoratorCore.placeStackDown( - decorator, 0, 0, 0, 0, 1, 0, output, new RNG(1L), data, 2, opts, null); + decorator, 0, 0, 0, 0, 1, 0, output, new RNG(1L), runtime, 2, opts, null); assertSame(lowerExisting, output.get(0, 0, 0)); assertSame(upperExisting, output.get(0, 1, 0)); @@ -301,18 +313,19 @@ public class DecoratorCoreTest { @Test public void floatingStackStopsAtHunkCeiling() { IrisDecorator decorator = mock(IrisDecorator.class); - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); + PackRuntime runtime = data.standalonePackRuntime(); NativeBlockState decorant = mock(NativeBlockState.class); when(decorant.key()).thenReturn("minecraft:stone"); - when(decorator.getHeight(any(RNG.class), anyDouble(), anyDouble(), eq(data))).thenReturn(3); + when(decorator.getHeight(any(RNG.class), anyDouble(), anyDouble(), eq(runtime))).thenReturn(3); when(decorator.getTopThreshold()).thenReturn(1.0); - when(decorator.pickBlockData(any(RNG.class), eq(data), anyDouble(), anyDouble())).thenReturn(decorant); - when(decorator.pickBlockDataTop(any(RNG.class), eq(data), anyDouble(), anyDouble())).thenReturn(decorant); + when(decorator.pickBlockData(any(RNG.class), eq(runtime), anyDouble(), anyDouble())).thenReturn(decorant); + when(decorator.pickBlockDataTop(any(RNG.class), eq(runtime), anyDouble(), anyDouble())).thenReturn(decorant); Hunk output = Hunk.newArrayHunk(1, 2, 1); output.set(0, 0, 0, sturdyState()); int placed = DecoratorCore.placeFloatingStacked( - decorator, 0, 0, 0, 0, 0, 3, output, new RNG(1L), data, null); + decorator, 0, 0, 0, 0, 0, 3, output, new RNG(1L), runtime, null); assertEquals(1, placed); assertSame(decorant, output.get(0, 1, 0)); @@ -321,7 +334,8 @@ public class DecoratorCoreTest { @Test public void floatingDecoratorsRejectUnsupportedSurface() { IrisDecorator decorator = mock(IrisDecorator.class); - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); + PackRuntime runtime = data.standalonePackRuntime(); NativeBlockState decorant = mock(NativeBlockState.class); NativeBlockState air = airState(); NativeBlockState fluid = mock(NativeBlockState.class); @@ -329,10 +343,10 @@ public class DecoratorCoreTest { when(plant.key()).thenReturn("minecraft:short_grass"); when(fluid.isFluid()).thenReturn(true); when(decorant.key()).thenReturn("minecraft:cobblestone_slab"); - when(decorator.getHeight(any(RNG.class), anyDouble(), anyDouble(), eq(data))).thenReturn(2); + when(decorator.getHeight(any(RNG.class), anyDouble(), anyDouble(), eq(runtime))).thenReturn(2); when(decorator.getTopThreshold()).thenReturn(1.0); - when(decorator.pickBlockData(any(RNG.class), eq(data), anyDouble(), anyDouble())).thenReturn(decorant); - when(decorator.pickBlockDataTop(any(RNG.class), eq(data), anyDouble(), anyDouble())).thenReturn(decorant); + when(decorator.pickBlockData(any(RNG.class), eq(runtime), anyDouble(), anyDouble())).thenReturn(decorant); + when(decorator.pickBlockDataTop(any(RNG.class), eq(runtime), anyDouble(), anyDouble())).thenReturn(decorant); for (NativeBlockState surface : new NativeBlockState[]{null, air, fluid, plant}) { Hunk output = Hunk.newArrayHunk(1, 5, 1); @@ -342,11 +356,11 @@ public class DecoratorCoreTest { output.set(0, 4, 0, air); DecoratorCore.placeFloatingSimple( - decorator, 0, 0, 0, 0, 2, 3, output, new RNG(1L), data, null); + decorator, 0, 0, 0, 0, 2, 3, output, new RNG(1L), runtime, null); assertSame(air, output.get(0, 3, 0)); int placed = DecoratorCore.placeFloatingStacked( - decorator, 0, 0, 0, 0, 2, 3, output, new RNG(1L), data, null); + decorator, 0, 0, 0, 0, 2, 3, output, new RNG(1L), runtime, null); assertEquals(0, placed); assertSame(surface, output.get(0, 2, 0)); assertSame(air, output.get(0, 3, 0)); @@ -357,27 +371,28 @@ public class DecoratorCoreTest { @Test public void floatingDecoratorsPreserveSupportedPlacementWithoutMaterialGating() { IrisDecorator decorator = mock(IrisDecorator.class); - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); + PackRuntime runtime = data.standalonePackRuntime(); NativeBlockState surface = mock(NativeBlockState.class); NativeBlockState decorant = mock(NativeBlockState.class); when(surface.isSolid()).thenReturn(true); when(decorant.key()).thenReturn("minecraft:cobblestone_slab"); - when(decorator.getHeight(any(RNG.class), anyDouble(), anyDouble(), eq(data))).thenReturn(2); + when(decorator.getHeight(any(RNG.class), anyDouble(), anyDouble(), eq(runtime))).thenReturn(2); when(decorator.getTopThreshold()).thenReturn(1.0); - when(decorator.pickBlockData(any(RNG.class), eq(data), anyDouble(), anyDouble())).thenReturn(decorant); - when(decorator.pickBlockDataTop(any(RNG.class), eq(data), anyDouble(), anyDouble())).thenReturn(decorant); + when(decorator.pickBlockData(any(RNG.class), eq(runtime), anyDouble(), anyDouble())).thenReturn(decorant); + when(decorator.pickBlockDataTop(any(RNG.class), eq(runtime), anyDouble(), anyDouble())).thenReturn(decorant); Hunk output = Hunk.newArrayHunk(1, 4, 1); output.set(0, 1, 0, surface); output.set(0, 2, 0, airState()); output.set(0, 3, 0, airState()); DecoratorCore.placeFloatingSimple( - decorator, 0, 0, 0, 0, 1, 3, output, new RNG(1L), data, null); + decorator, 0, 0, 0, 0, 1, 3, output, new RNG(1L), runtime, null); assertSame(decorant, output.get(0, 2, 0)); output.set(0, 2, 0, airState()); int placed = DecoratorCore.placeFloatingStacked( - decorator, 0, 0, 0, 0, 1, 3, output, new RNG(1L), data, null); + decorator, 0, 0, 0, 0, 1, 3, output, new RNG(1L), runtime, null); assertEquals(2, placed); assertSame(surface, output.get(0, 1, 0)); assertSame(decorant, output.get(0, 2, 0)); @@ -387,12 +402,13 @@ public class DecoratorCoreTest { @Test public void tallSurfacePlantDoesNotPlaceWhenUpperTargetIsOccupied() { IrisDecorator decorator = mock(IrisDecorator.class); - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); + PackRuntime runtime = data.standalonePackRuntime(); NativeBlockState support = sturdyState(); NativeBlockState air = airState(); NativeBlockState occupied = mock(NativeBlockState.class); NativeBlockState plant = tallPlantState(); - when(decorator.pickBlockData(any(RNG.class), eq(data), anyDouble(), anyDouble())).thenReturn(plant); + when(decorator.pickBlockData(any(RNG.class), eq(runtime), anyDouble(), anyDouble())).thenReturn(plant); Hunk output = Hunk.newArrayHunk(1, 4, 1); output.set(0, 0, 0, support); @@ -400,7 +416,7 @@ public class DecoratorCoreTest { output.set(0, 2, 0, occupied); DecoratorCore.placeSurfaceSingle( - decorator, 0, 0, 0, 0, 0, output, new RNG(1L), data, false, false, null); + decorator, 0, 0, 0, 0, 0, output, new RNG(1L), runtime, false, false, null); assertSame(air, output.get(0, 1, 0)); assertSame(occupied, output.get(0, 2, 0)); @@ -409,11 +425,12 @@ public class DecoratorCoreTest { @Test public void tallFloatingPlantDoesNotPlaceWhenUpperTargetIsOccupied() { IrisDecorator decorator = mock(IrisDecorator.class); - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); + PackRuntime runtime = data.standalonePackRuntime(); NativeBlockState air = airState(); NativeBlockState occupied = mock(NativeBlockState.class); NativeBlockState plant = tallPlantState(); - when(decorator.pickBlockData(any(RNG.class), eq(data), anyDouble(), anyDouble())).thenReturn(plant); + when(decorator.pickBlockData(any(RNG.class), eq(runtime), anyDouble(), anyDouble())).thenReturn(plant); Hunk output = Hunk.newArrayHunk(1, 4, 1); output.set(0, 0, 0, sturdyState()); @@ -421,7 +438,7 @@ public class DecoratorCoreTest { output.set(0, 2, 0, occupied); DecoratorCore.placeFloatingSimple( - decorator, 0, 0, 0, 0, 0, 3, output, new RNG(1L), data, null); + decorator, 0, 0, 0, 0, 0, 3, output, new RNG(1L), runtime, null); assertSame(air, output.get(0, 1, 0)); assertSame(occupied, output.get(0, 2, 0)); @@ -430,7 +447,8 @@ public class DecoratorCoreTest { @Test public void tallSurfacePlantPlacesBothHalvesTogether() { IrisDecorator decorator = mock(IrisDecorator.class); - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); + PackRuntime runtime = data.standalonePackRuntime(); NativeBlockState support = sturdyState(); NativeBlockState lowerAir = airState(); NativeBlockState upperAir = airState(); @@ -438,7 +456,7 @@ public class DecoratorCoreTest { NativeBlockState upper = mock(NativeBlockState.class); NativeBlockState plant = tallPlantState(lower, upper); when(plant.canPlaceOnto(support)).thenReturn(true); - when(decorator.pickBlockData(any(RNG.class), eq(data), anyDouble(), anyDouble())).thenReturn(plant); + when(decorator.pickBlockData(any(RNG.class), eq(runtime), anyDouble(), anyDouble())).thenReturn(plant); Hunk output = Hunk.newArrayHunk(1, 4, 1); output.set(0, 0, 0, support); @@ -446,7 +464,7 @@ public class DecoratorCoreTest { output.set(0, 2, 0, upperAir); DecoratorCore.placeSurfaceSingle( - decorator, 0, 0, 0, 0, 0, output, new RNG(1L), data, false, false, null); + decorator, 0, 0, 0, 0, 0, output, new RNG(1L), runtime, false, false, null); assertSame(lower, output.get(0, 1, 0)); assertSame(upper, output.get(0, 2, 0)); @@ -455,19 +473,20 @@ public class DecoratorCoreTest { @Test public void surfaceDecorantRejectsInvalidNativeSupport() { IrisDecorator decorator = mock(IrisDecorator.class); - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); + PackRuntime runtime = data.standalonePackRuntime(); NativeBlockState support = sturdyState(); NativeBlockState air = airState(); NativeBlockState decorant = mock(NativeBlockState.class); when(decorant.canPlaceOnto(support)).thenReturn(false); - when(decorator.pickBlockData(any(RNG.class), eq(data), anyDouble(), anyDouble())).thenReturn(decorant); + when(decorator.pickBlockData(any(RNG.class), eq(runtime), anyDouble(), anyDouble())).thenReturn(decorant); Hunk output = Hunk.newArrayHunk(1, 3, 1); output.set(0, 0, 0, support); output.set(0, 1, 0, air); DecoratorCore.placeSurfaceSingle( - decorator, 0, 0, 0, 0, 0, output, new RNG(1L), data, false, false, null); + decorator, 0, 0, 0, 0, 0, output, new RNG(1L), runtime, false, false, null); assertSame(air, output.get(0, 1, 0)); } @@ -476,7 +495,8 @@ public class DecoratorCoreTest { public void forcedSurfaceBlockStillPlacesDecorantAboveIt() { IrisDecorator decorator = mock(IrisDecorator.class); IrisBlockData forcedBlock = mock(IrisBlockData.class); - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); + PackRuntime runtime = data.standalonePackRuntime(); NativeBlockState support = sturdyState(); NativeBlockState farmland = sturdyState(); NativeBlockState air = airState(); @@ -484,14 +504,14 @@ public class DecoratorCoreTest { when(wheat.key()).thenReturn("minecraft:wheat[age=7]"); when(decorator.getForceBlock()).thenReturn(forcedBlock); when(forcedBlock.getBlockData(data)).thenReturn(farmland); - when(decorator.pickBlockData(any(RNG.class), eq(data), anyDouble(), anyDouble())).thenReturn(wheat); + when(decorator.pickBlockData(any(RNG.class), eq(runtime), anyDouble(), anyDouble())).thenReturn(wheat); Hunk output = Hunk.newArrayHunk(1, 3, 1); output.set(0, 0, 0, support); output.set(0, 1, 0, air); DecoratorCore.placeSurfaceSingle( - decorator, 0, 0, 0, 0, 0, output, new RNG(1L), data, false, false, null); + decorator, 0, 0, 0, 0, 0, output, new RNG(1L), runtime, false, false, null); assertSame(farmland, output.get(0, 0, 0)); assertSame(wheat, output.get(0, 1, 0)); @@ -667,10 +687,10 @@ public class DecoratorCoreTest { SpikeFixture fixture = new SpikeFixture(1, upward); if (upward) { DecoratorCore.placeSurfaceSingle(fixture.decorator, 0, 0, 0, 0, 0, - fixture.output, new RNG(1L), fixture.data, false, false, null); + fixture.output, new RNG(1L), fixture.runtime, false, false, null); } else { DecoratorCore.placeSingleAt(fixture.decorator, 0, 0, 0, 1, 0, - fixture.output, new RNG(1L), fixture.data, true, null); + fixture.output, new RNG(1L), fixture.runtime, true, null); } assertEquals("tip", fixture.property(1, "thickness")); assertEquals(upward ? "up" : "down", fixture.property(1, "vertical_direction")); @@ -703,7 +723,7 @@ public class DecoratorCoreTest { when(fixture.decorator.getWhitelistArray(fixture.data)).thenReturn(new NativeBlockState[]{original}); DecoratorCore.placeSurfaceSingle(fixture.decorator, 0, 0, 0, 0, 0, - fixture.output, new RNG(1L), fixture.data, false, false, null); + fixture.output, new RNG(1L), fixture.runtime, false, false, null); assertSame(replacement, fixture.output.get(0, 0, 0)); assertEquals("tip", fixture.property(1, "thickness")); @@ -717,8 +737,8 @@ public class DecoratorCoreTest { NativeBlockState obstruction = sturdyState(); when(plant.key()).thenReturn("minecraft:weeping_vines_plant"); when(tip.key()).thenReturn("minecraft:weeping_vines"); - when(fixture.decorator.pickBlockData(any(RNG.class), eq(fixture.data), anyDouble(), anyDouble())).thenReturn(tip); - when(fixture.decorator.pickBlockDataTop(any(RNG.class), eq(fixture.data), anyDouble(), anyDouble())).thenReturn(tip); + when(fixture.decorator.pickBlockData(any(RNG.class), eq(fixture.runtime), anyDouble(), anyDouble())).thenReturn(tip); + when(fixture.decorator.pickBlockDataTop(any(RNG.class), eq(fixture.runtime), anyDouble(), anyDouble())).thenReturn(tip); fixture.output.set(0, 3, 0, obstruction); try (MockedStatic blocks = mockStatic(B.class, CALLS_REAL_METHODS)) { blocks.when(() -> B.getState("minecraft:weeping_vines_plant")).thenReturn(plant); @@ -756,18 +776,19 @@ public class DecoratorCoreTest { @Test public void stackedVineCurtainHangsFromTheWallItsTopStrandFaces() { IrisDecorator decorator = mock(IrisDecorator.class); - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); + PackRuntime runtime = data.standalonePackRuntime(); NativeBlockState vine = facingState(VINE, VINE_FACES, EnumSet.of(BlockFace.NORTH)); - when(decorator.getHeight(any(RNG.class), anyDouble(), anyDouble(), eq(data))).thenReturn(3); + when(decorator.getHeight(any(RNG.class), anyDouble(), anyDouble(), eq(runtime))).thenReturn(3); when(decorator.getTopThreshold()).thenReturn(1.0); - when(decorator.pickBlockData(any(RNG.class), eq(data), anyDouble(), anyDouble())).thenReturn(vine); - when(decorator.pickBlockDataTop(any(RNG.class), eq(data), anyDouble(), anyDouble())).thenReturn(vine); + when(decorator.pickBlockData(any(RNG.class), eq(runtime), anyDouble(), anyDouble())).thenReturn(vine); + when(decorator.pickBlockDataTop(any(RNG.class), eq(runtime), anyDouble(), anyDouble())).thenReturn(vine); Hunk output = Hunk.newArrayHunk(16, 8, 16); output.set(8, 6, 8, sturdyState()); output.set(8, 5, 7, sturdyState()); output.set(9, 4, 8, sturdyState()); - DecoratorCore.placeStackDown(decorator, 8, 8, 8, 8, 5, 0, output, new RNG(1L), data, 3, + DecoratorCore.placeStackDown(decorator, 8, 8, 8, 8, 5, 0, output, new RNG(1L), runtime, 3, new DecoratorCore.PlaceOpts(), null); assertEquals(EnumSet.of(BlockFace.NORTH, BlockFace.UP), faces(output.get(8, 5, 8))); @@ -778,16 +799,17 @@ public class DecoratorCoreTest { @Test public void stackedVineCurtainHangsUnderAnOpenCeiling() { IrisDecorator decorator = mock(IrisDecorator.class); - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); + PackRuntime runtime = data.standalonePackRuntime(); NativeBlockState vine = facingState(VINE, VINE_FACES, EnumSet.of(BlockFace.NORTH)); - when(decorator.getHeight(any(RNG.class), anyDouble(), anyDouble(), eq(data))).thenReturn(3); + when(decorator.getHeight(any(RNG.class), anyDouble(), anyDouble(), eq(runtime))).thenReturn(3); when(decorator.getTopThreshold()).thenReturn(1.0); - when(decorator.pickBlockData(any(RNG.class), eq(data), anyDouble(), anyDouble())).thenReturn(vine); - when(decorator.pickBlockDataTop(any(RNG.class), eq(data), anyDouble(), anyDouble())).thenReturn(vine); + when(decorator.pickBlockData(any(RNG.class), eq(runtime), anyDouble(), anyDouble())).thenReturn(vine); + when(decorator.pickBlockDataTop(any(RNG.class), eq(runtime), anyDouble(), anyDouble())).thenReturn(vine); Hunk output = Hunk.newArrayHunk(16, 8, 16); output.set(8, 6, 8, sturdyState()); - DecoratorCore.placeStackDown(decorator, 8, 8, 8, 8, 5, 0, output, new RNG(1L), data, 3, + DecoratorCore.placeStackDown(decorator, 8, 8, 8, 8, 5, 0, output, new RNG(1L), runtime, 3, new DecoratorCore.PlaceOpts(), null); assertEquals(EnumSet.of(BlockFace.NORTH, BlockFace.UP), faces(output.get(8, 5, 8))); @@ -915,14 +937,15 @@ public class DecoratorCoreTest { private Hunk placeSpikeColumn(String material, int height, boolean upward, boolean waterlogged, boolean submerged) { IrisDecorator decorator = mock(IrisDecorator.class); - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); + PackRuntime runtime = data.standalonePackRuntime(); NativeBlockState spike = spikeState(material, Map.of( "thickness", "tip_merge", "vertical_direction", upward ? "down" : "up", "waterlogged", Boolean.toString(waterlogged))); - when(decorator.getHeight(any(RNG.class), anyDouble(), anyDouble(), eq(data))).thenReturn(height); + when(decorator.getHeight(any(RNG.class), anyDouble(), anyDouble(), eq(runtime))).thenReturn(height); when(decorator.getTopThreshold()).thenReturn(0.75); - when(decorator.pickBlockData(any(RNG.class), eq(data), anyDouble(), anyDouble())).thenReturn(spike); - when(decorator.pickBlockDataTop(any(RNG.class), eq(data), anyDouble(), anyDouble())).thenReturn(spike); + when(decorator.pickBlockData(any(RNG.class), eq(runtime), anyDouble(), anyDouble())).thenReturn(spike); + when(decorator.pickBlockDataTop(any(RNG.class), eq(runtime), anyDouble(), anyDouble())).thenReturn(spike); Hunk output = Hunk.newArrayHunk(1, height + 2, 1); NativeBlockState target = airState(); @@ -941,9 +964,9 @@ public class DecoratorCoreTest { opts.underwater = submerged; opts.fluidHeight = height; if (upward) { - DecoratorCore.placeStackUp(decorator, 0, 0, 0, 0, 0, height, output, new RNG(1L), data, opts); + DecoratorCore.placeStackUp(decorator, 0, 0, 0, 0, 0, height, output, new RNG(1L), runtime, opts); } else { - DecoratorCore.placeStackDown(decorator, 0, 0, 0, 0, height, 1, output, new RNG(1L), data, height, opts, null); + DecoratorCore.placeStackDown(decorator, 0, 0, 0, 0, height, 1, output, new RNG(1L), runtime, height, opts, null); } assertSame(support, output.get(0, upward ? 0 : height + 1, 0)); return output; @@ -987,23 +1010,24 @@ public class DecoratorCoreTest { private void assertSingleVoxelHalfPlacement(boolean floating) { for (String key : new String[]{"minecraft:oak_stairs[half=bottom]", "minecraft:oak_trapdoor[half=top]"}) { IrisDecorator decorator = mock(IrisDecorator.class); - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); + PackRuntime runtime = data.standalonePackRuntime(); NativeBlockState support = sturdyState(); NativeBlockState air = airState(); NativeBlockState occupied = mock(NativeBlockState.class); NativeBlockState block = mock(NativeBlockState.class); when(block.key()).thenReturn(key); when(block.canPlaceOnto(support)).thenReturn(true); - when(decorator.pickBlockData(any(RNG.class), eq(data), anyDouble(), anyDouble())).thenReturn(block); + when(decorator.pickBlockData(any(RNG.class), eq(runtime), anyDouble(), anyDouble())).thenReturn(block); Hunk output = Hunk.newArrayHunk(1, 4, 1); output.set(0, 0, 0, support); output.set(0, 1, 0, air); output.set(0, 2, 0, occupied); if (floating) { - DecoratorCore.placeFloatingSimple(decorator, 0, 0, 0, 0, 0, 3, output, new RNG(1L), data, null); + DecoratorCore.placeFloatingSimple(decorator, 0, 0, 0, 0, 0, 3, output, new RNG(1L), runtime, null); } else { - DecoratorCore.placeSurfaceSingle(decorator, 0, 0, 0, 0, 0, output, new RNG(1L), data, false, false, null); + DecoratorCore.placeSurfaceSingle(decorator, 0, 0, 0, 0, 0, output, new RNG(1L), runtime, false, false, null); } assertSame(key, block, output.get(0, 1, 0)); @@ -1033,7 +1057,8 @@ public class DecoratorCoreTest { } private class SpikeFixture { private final IrisDecorator decorator = mock(IrisDecorator.class); - private final IrisData data = mock(IrisData.class); + private final IrisData data = MockPackData.create(); + private final PackRuntime runtime = data.standalonePackRuntime(); private final DecoratorCore.PlaceOpts opts = new DecoratorCore.PlaceOpts(); private final Hunk output; private final int height; @@ -1049,17 +1074,17 @@ public class DecoratorCoreTest { output.set(0, upward ? 0 : height + 1, 0, sturdyState()); NativeBlockState spike = spikeState("minecraft:sulfur_spike", Map.of( "thickness", "tip_merge", "vertical_direction", upward ? "down" : "up", "waterlogged", "false")); - when(decorator.getHeight(any(RNG.class), anyDouble(), anyDouble(), eq(data))).thenReturn(height); + when(decorator.getHeight(any(RNG.class), anyDouble(), anyDouble(), eq(runtime))).thenReturn(height); when(decorator.getTopThreshold()).thenReturn(0.75); - when(decorator.pickBlockData(any(RNG.class), eq(data), anyDouble(), anyDouble())).thenReturn(spike); - when(decorator.pickBlockDataTop(any(RNG.class), eq(data), anyDouble(), anyDouble())).thenReturn(spike); + when(decorator.pickBlockData(any(RNG.class), eq(runtime), anyDouble(), anyDouble())).thenReturn(spike); + when(decorator.pickBlockDataTop(any(RNG.class), eq(runtime), anyDouble(), anyDouble())).thenReturn(spike); } private void place() { if (upward) { - DecoratorCore.placeStackUp(decorator, 0, 0, 0, 0, 0, height, output, new RNG(1L), data, opts); + DecoratorCore.placeStackUp(decorator, 0, 0, 0, 0, 0, height, output, new RNG(1L), runtime, opts); } else { - DecoratorCore.placeStackDown(decorator, 0, 0, 0, 0, height, 1, output, new RNG(1L), data, height, opts, null); + DecoratorCore.placeStackDown(decorator, 0, 0, 0, 0, height, 1, output, new RNG(1L), runtime, height, opts, null); } } diff --git a/core/src/test/java/art/arcane/iris/generation/decoration/DecoratorStackSamplingTest.java b/core/src/test/java/art/arcane/iris/generation/decoration/DecoratorStackSamplingTest.java index e5b43f76a..5e8ec8ed6 100644 --- a/core/src/test/java/art/arcane/iris/generation/decoration/DecoratorStackSamplingTest.java +++ b/core/src/test/java/art/arcane/iris/generation/decoration/DecoratorStackSamplingTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.decoration; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.pack.loading.IrisData; import art.arcane.volmlib.nativelib.terrain.NativeBlockState; import art.arcane.volmlib.util.hunk.Hunk; @@ -36,6 +37,7 @@ public class DecoratorStackSamplingTest { private static void assertEquivalentStack(long seed, int height, int direction, int coordinate) { IrisData data = mock(IrisData.class); + PackRuntime runtime = PackRuntime.standalone(data); RNG rng = new RNG(seed); RNG controlRng = new RNG(seed); CNG variance = new CNG(new RNG(seed + 11L)); @@ -46,7 +48,7 @@ public class DecoratorStackSamplingTest { .setStackMin(height).setStackMax(height).setTopThreshold(0.4D)); doReturn(body).when(decorator).getBlockDataArray(data); doReturn(top).when(decorator).getBlockDataTopsArray(data); - doReturn(variance).when(decorator).getVarianceGenerator(rng, data); + doReturn(variance).when(decorator).getVarianceGenerator(rng, runtime); NativeBlockState air = block("minecraft:air"); doReturn(true).when(air).isAir(); NativeBlockState support = block("minecraft:stone"); @@ -64,11 +66,11 @@ public class DecoratorStackSamplingTest { int z = coordinate * 3 - 7; switch (direction) { case 0 -> DecoratorCore.placeStackUp(decorator, 0, 0, coordinate, z, 0, height, - output, rng, data, opts); + output, rng, runtime, opts); case 1 -> DecoratorCore.placeStackDown(decorator, 0, 0, coordinate, z, height, 0, - output, rng, data, height, opts, null); + output, rng, runtime, height, opts, null); case 2 -> assertEquals(height, DecoratorCore.placeFloatingStacked(decorator, 0, 0, - coordinate, z, 0, height + 1, output, rng, data, null)); + coordinate, z, 0, height + 1, output, rng, runtime, null)); default -> throw new IllegalArgumentException("Unknown stack direction"); } boolean usedBody = false; @@ -84,8 +86,8 @@ public class DecoratorStackSamplingTest { usedTop |= topSegment; } assertSame(support, output.get(0, supportY, 0)); - verify(decorator, times(usedBody ? 1 : 0)).pickBlockData(rng, data, coordinate, z); - verify(decorator, times(usedTop ? 1 : 0)).pickBlockDataTop(rng, data, coordinate, z); + verify(decorator, times(usedBody ? 1 : 0)).pickBlockData(rng, runtime, coordinate, z); + verify(decorator, times(usedTop ? 1 : 0)).pickBlockDataTop(rng, runtime, coordinate, z); assertEquals(controlRng.nextLong(), rng.nextLong()); } diff --git a/core/src/test/java/art/arcane/iris/generation/decoration/HydrologyVegetationTest.java b/core/src/test/java/art/arcane/iris/generation/decoration/HydrologyVegetationTest.java index cd8e8a35f..e02d7d470 100644 --- a/core/src/test/java/art/arcane/iris/generation/decoration/HydrologyVegetationTest.java +++ b/core/src/test/java/art/arcane/iris/generation/decoration/HydrologyVegetationTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.decoration; +import art.arcane.iris.testsupport.MockPackData; import art.arcane.iris.generation.block.IrisBlockData; import art.arcane.iris.generation.hydrology.config.IrisHydrology; import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster; @@ -41,7 +42,7 @@ public class HydrologyVegetationTest { private static final Set WATER_PLANTS = Set.of("minecraft:seagrass", "minecraft:tall_seagrass", "minecraft:kelp", "minecraft:kelp_plant"); private static final int[][] SIDES = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; - private final IrisData data = mock(IrisData.class); + private final IrisData data = MockPackData.create(); private PlantPlatform platform; @Before @@ -591,7 +592,7 @@ public class HydrologyVegetationTest { for (int lz = 0; lz < 16; lz++) { int x = (chunkX << 4) + lx; int z = (chunkZ << 4) + lz; - vegetation.decorate(chunk, lx, lz, x, z, role(x, z), this, data); + vegetation.decorate(chunk, lx, lz, x, z, role(x, z), this, data.standalonePackRuntime()); } } return chunk; @@ -663,7 +664,7 @@ public class HydrologyVegetationTest { for (int lz = 0; lz < 16; lz++) { int x = (chunkX << 4) + lx; int z = (chunkZ << 4) + lz; - vegetation.decorate(chunk, lx, lz, x, z, role(x, z), this, data); + vegetation.decorate(chunk, lx, lz, x, z, role(x, z), this, data.standalonePackRuntime()); } } } diff --git a/core/src/test/java/art/arcane/iris/generation/decoration/IrisDecoratorCaveContextTest.java b/core/src/test/java/art/arcane/iris/generation/decoration/IrisDecoratorCaveContextTest.java index 77f6b7858..67c3865ac 100644 --- a/core/src/test/java/art/arcane/iris/generation/decoration/IrisDecoratorCaveContextTest.java +++ b/core/src/test/java/art/arcane/iris/generation/decoration/IrisDecoratorCaveContextTest.java @@ -1,6 +1,7 @@ package art.arcane.iris.generation.decoration; import art.arcane.iris.pack.loading.IrisData; +import art.arcane.iris.testsupport.MockPackData; import art.arcane.iris.generation.runtime.IrisComplex; import art.arcane.iris.generation.mantle.EngineMantle; import art.arcane.iris.generation.runtime.Engine; @@ -63,7 +64,7 @@ public class IrisDecoratorCaveContextTest { Engine engine = mock(Engine.class); SeedManager seedManager = mock(SeedManager.class); doReturn(seedManager).when(engine).getSeedManager(); - doReturn(mock(IrisData.class)).when(engine).getData(); + doReturn(MockPackData.create()).when(engine).getData(); IrisDimension dimension = mock(IrisDimension.class); doReturn(63).when(dimension).getFluidHeight(); doReturn(dimension).when(engine).getDimension(); @@ -74,7 +75,7 @@ public class IrisDecoratorCaveContextTest { doReturn(63).when(mantle).getFluidHeight(anyInt(), anyInt()); IrisDecorator decorator = mock(IrisDecorator.class); - doReturn(true).when(decorator).passesChanceGate(any(), anyDouble(), anyDouble(), any()); + doReturn(true).when(decorator).passesChanceGate(any(), anyDouble(), anyDouble(), any(DecoratorRuntime.class)); doReturn(true).when(decorator).isStacking(); doReturn(true).when(decorator).isForcePlace(); doReturn(1).when(decorator).getHeight(any(), anyDouble(), anyDouble(), any()); @@ -113,7 +114,7 @@ public class IrisDecoratorCaveContextTest { public void dryBlendedSurfaceRunsBiomeDecoratorDespiteHigherModeledWater() { Engine engine = mock(Engine.class); doReturn(mock(SeedManager.class)).when(engine).getSeedManager(); - doReturn(mock(IrisData.class)).when(engine).getData(); + doReturn(MockPackData.create()).when(engine).getData(); doReturn(7L).when(engine).getGenerationSessionId(); IrisDimension dimension = mock(IrisDimension.class); doReturn(dimension).when(engine).getDimension(); @@ -122,7 +123,7 @@ public class IrisDecoratorCaveContextTest { doReturn(63).when(mantle).getFluidHeight(anyInt(), anyInt()); IrisDecorator decorator = mock(IrisDecorator.class); - doReturn(true).when(decorator).passesChanceGate(any(), anyDouble(), anyDouble(), any()); + doReturn(true).when(decorator).passesChanceGate(any(), anyDouble(), anyDouble(), any(DecoratorRuntime.class)); doReturn(true).when(decorator).isStacking(); doReturn(true).when(decorator).isForcePlace(); doReturn(1).when(decorator).getHeight(any(), anyDouble(), anyDouble(), any()); @@ -143,7 +144,7 @@ public class IrisDecoratorCaveContextTest { assertEquals(63, surface.surfaceFluidHeight(16, 0)); } - verify(decorator).passesChanceGate(any(), anyDouble(), anyDouble(), any()); + verify(decorator).passesChanceGate(any(), anyDouble(), anyDouble(), any(DecoratorRuntime.class)); assertFalse(DecoratorCore.SCRATCH_OPTS.get().underwater); assertEquals(63, surface.surfaceFluidHeight(0, 0)); try (IrisContext.Scope scope = IrisContext.open(engine, 8L, chunk)) { diff --git a/core/src/test/java/art/arcane/iris/generation/decoration/IrisDecoratorHeightTest.java b/core/src/test/java/art/arcane/iris/generation/decoration/IrisDecoratorHeightTest.java index 7cf0f4b1b..27ac64eed 100644 --- a/core/src/test/java/art/arcane/iris/generation/decoration/IrisDecoratorHeightTest.java +++ b/core/src/test/java/art/arcane/iris/generation/decoration/IrisDecoratorHeightTest.java @@ -1,6 +1,6 @@ package art.arcane.iris.generation.decoration; -import art.arcane.iris.pack.loading.IrisData; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.volmlib.util.noise.CNG; import art.arcane.volmlib.util.math.RNG; import org.junit.Test; @@ -18,13 +18,13 @@ public class IrisDecoratorHeightTest { when(generator.fit(eq(1), eq(2), anyDouble(), anyDouble())).thenReturn(2); IrisDecorator decorator = new IrisDecorator() { @Override - public CNG getHeightGenerator(RNG rng, IrisData data) { + public CNG getHeightGenerator(RNG rng, PackRuntime runtime) { return generator; } }; decorator.setStackMin(1); decorator.setStackMax(2); - assertEquals(2, decorator.getHeight(new RNG(1L), 0, 0, mock(IrisData.class))); + assertEquals(2, decorator.getHeight(new RNG(1L), 0, 0, PackRuntime.standalone(null))); } } diff --git a/core/src/test/java/art/arcane/iris/generation/decoration/IrisDecoratorPaletteSelectionTest.java b/core/src/test/java/art/arcane/iris/generation/decoration/IrisDecoratorPaletteSelectionTest.java index 0afbba5bf..a32a16aa4 100644 --- a/core/src/test/java/art/arcane/iris/generation/decoration/IrisDecoratorPaletteSelectionTest.java +++ b/core/src/test/java/art/arcane/iris/generation/decoration/IrisDecoratorPaletteSelectionTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.decoration; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.pack.loading.IrisData; import art.arcane.volmlib.nativelib.terrain.NativeBlockState; @@ -21,6 +22,7 @@ public class IrisDecoratorPaletteSelectionTest { @Test public void multipleTopEntriesVaryEvenWhenTheBodyPaletteIsASingleBlock() { IrisData data = mock(IrisData.class); + PackRuntime runtime = PackRuntime.standalone(data); IrisBiome biome = mock(IrisBiome.class); IrisDecorator decorator = spy(new IrisDecorator().setChance(1D)); NativeBlockState body = mock(NativeBlockState.class); @@ -32,13 +34,13 @@ public class IrisDecoratorPaletteSelectionTest { RNG rng = new RNG(37L); doReturn(new KList<>(body)).when(decorator).getBlockData(data); doReturn(tops).when(decorator).getBlockDataTops(data); - doReturn(chance).when(decorator).getGenerator(rng, data); - doReturn(variance).when(decorator).getVarianceGenerator(rng, data); + doReturn(chance).when(decorator).getGenerator(rng, runtime); + doReturn(variance).when(decorator).getVarianceGenerator(rng, runtime); doReturn(second).when(variance).fit(tops, 23D, 9D, 17D); doReturn(first).when(variance).fit(tops, 24D, 9D, 17D); - assertSame(second, decorator.getBlockDataForTop(biome, rng, 17D, 9D, 23D, data)); - assertSame(first, decorator.getBlockDataForTop(biome, rng, 17D, 9D, 24D, data)); + assertSame(second, decorator.getBlockDataForTop(biome, rng, 17D, 9D, 23D, runtime)); + assertSame(first, decorator.getBlockDataForTop(biome, rng, 17D, 9D, 24D, runtime)); verify(variance).fit(tops, 23D, 9D, 17D); verify(variance).fit(tops, 24D, 9D, 17D); } @@ -46,6 +48,7 @@ public class IrisDecoratorPaletteSelectionTest { @Test public void aSingleTopEntryDoesNotBuildOrSampleTheVarianceGenerator() { IrisData data = mock(IrisData.class); + PackRuntime runtime = PackRuntime.standalone(data); IrisBiome biome = mock(IrisBiome.class); IrisDecorator decorator = spy(new IrisDecorator().setChance(1D)); NativeBlockState firstBody = mock(NativeBlockState.class); @@ -54,16 +57,17 @@ public class IrisDecoratorPaletteSelectionTest { RNG rng = new RNG(37L); doReturn(new KList<>(firstBody, secondBody)).when(decorator).getBlockData(data); doReturn(new KList<>(top)).when(decorator).getBlockDataTops(data); - doReturn(mock(CNG.class)).when(decorator).getGenerator(rng, data); + doReturn(mock(CNG.class)).when(decorator).getGenerator(rng, runtime); - assertSame(top, decorator.getBlockDataForTop(biome, rng, 17D, 9D, 23D, data)); - verify(decorator, never()).getVarianceGenerator(rng, data); + assertSame(top, decorator.getBlockDataForTop(biome, rng, 17D, 9D, 23D, runtime)); + verify(decorator, never()).getVarianceGenerator(rng, runtime); verify(decorator, times(1)).getBlockDataTops(data); } @Test public void bodySamplingResolvesPaletteOnceAndPreservesCoordinatesAndRngConsumption() { IrisData data = mock(IrisData.class); + PackRuntime runtime = PackRuntime.standalone(data); IrisBiome biome = mock(IrisBiome.class); IrisDecorator decorator = spy(new IrisDecorator()); NativeBlockState first = mock(NativeBlockState.class); @@ -73,13 +77,13 @@ public class IrisDecoratorPaletteSelectionTest { RNG rng = new RNG(37L); RNG control = new RNG(37L); doReturn(palette).when(decorator).getBlockData(data); - doReturn(variance).when(decorator).getVarianceGenerator(rng, data); + doReturn(variance).when(decorator).getVarianceGenerator(rng, runtime); for (int x = -8; x < 8; x++) { for (int y = 0; y < 4; y++) { double z = x * 3D - 2D; NativeBlockState expected = variance.fit(palette, z, y, x); - assertSame(expected, decorator.getBlockData100(biome, rng, x, y, z, data)); + assertSame(expected, decorator.getBlockData100(biome, rng, x, y, z, runtime)); } } verify(decorator, times(64)).getBlockData(data); diff --git a/core/src/test/java/art/arcane/iris/generation/decoration/IrisDecoratorSeedCohesionTest.java b/core/src/test/java/art/arcane/iris/generation/decoration/IrisDecoratorSeedCohesionTest.java index 049638623..f608669ba 100644 --- a/core/src/test/java/art/arcane/iris/generation/decoration/IrisDecoratorSeedCohesionTest.java +++ b/core/src/test/java/art/arcane/iris/generation/decoration/IrisDecoratorSeedCohesionTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.decoration; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.NoiseStyle; @@ -113,6 +114,8 @@ public class IrisDecoratorSeedCohesionTest { private Fixture(long seed, IrisDecorator decorator, IrisData data) { when(engine.getData()).thenReturn(data); + PackRuntime runtime = PackRuntime.forEngine(engine, data); + when(engine.getPackRuntime()).thenReturn(runtime); when(engine.getHeight()).thenReturn(32); when(engine.getSeedManager().getComponent()).thenReturn(seed); when(engine.getAllBiomes()).thenReturn(new KList<>(biome)); diff --git a/core/src/test/java/art/arcane/iris/generation/decoration/IrisDecoratorVarianceGeneratorTest.java b/core/src/test/java/art/arcane/iris/generation/decoration/IrisDecoratorVarianceGeneratorTest.java index a5cb2be26..e3e68eea3 100644 --- a/core/src/test/java/art/arcane/iris/generation/decoration/IrisDecoratorVarianceGeneratorTest.java +++ b/core/src/test/java/art/arcane/iris/generation/decoration/IrisDecoratorVarianceGeneratorTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.decoration; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.block.IrisBlockData; import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.NoiseStyle; @@ -26,7 +27,7 @@ public class IrisDecoratorVarianceGeneratorTest { } private double[] sampleSharedVarianceStyleGeneratorAfterVarianceBuilt() { - decorator.getVarianceGenerator(new RNG(WORLD_SEED), packData); + decorator.getVarianceGenerator(new RNG(WORLD_SEED), PackRuntime.of(packData.getEngine(), packData)); return sampleSharedVarianceStyleGenerator(decorator.getVariance()); } @@ -35,7 +36,7 @@ public class IrisDecoratorVarianceGeneratorTest { } private double[] sampleSharedVarianceStyleGenerator(IrisGeneratorStyle varianceStyle) { - return sampleSharedGenerator(varianceStyle, decorator.deriveVarianceSeed(new RNG(WORLD_SEED), packData), packData); + return sampleSharedGenerator(varianceStyle, decorator.deriveVarianceSeed(new RNG(WORLD_SEED), packData), PackRuntime.of(packData.getEngine(), packData)); } private static IrisDecorator createDecoratorWithZoomedSimplexVariance() { diff --git a/core/src/test/java/art/arcane/iris/generation/decoration/IrisDepositTuningTest.java b/core/src/test/java/art/arcane/iris/generation/decoration/IrisDepositTuningTest.java index 8dbe4df6a..3c2552cdd 100644 --- a/core/src/test/java/art/arcane/iris/generation/decoration/IrisDepositTuningTest.java +++ b/core/src/test/java/art/arcane/iris/generation/decoration/IrisDepositTuningTest.java @@ -1,6 +1,9 @@ package art.arcane.iris.generation.decoration; 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.block.IrisBlockData; import art.arcane.iris.generation.block.VectorMap; import art.arcane.iris.structure.object.IrisObject; @@ -24,6 +27,7 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; 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.mockStatic; @@ -163,17 +167,52 @@ public class IrisDepositTuningTest { } @Test - public void clumpCachesAreScopedByWorldSeedAndSize() { - IrisDepositGenerator.ClumpCacheKey firstWorld = - new IrisDepositGenerator.ClumpCacheKey(41L, 4, 8); - IrisDepositGenerator.ClumpCacheKey secondWorld = - new IrisDepositGenerator.ClumpCacheKey(42L, 4, 8); - IrisDepositGenerator.ClumpCacheKey largerVein = - new IrisDepositGenerator.ClumpCacheKey(41L, 8, 16); + public void clumpVariantsAreScopedByWorldSeedAndSize() { + IrisData data = mock(IrisData.class); + IrisDepositGenerator generator = paletteGenerator(data).setMinSize(4).setMaxSize(8); + DepositRuntime firstWorld = PackRuntime.forEngine(engineWithDepositSeed(41L), data).deposit(generator); + DepositRuntime secondWorld = PackRuntime.forEngine(engineWithDepositSeed(42L), data).deposit(generator); + DepositRuntime sameSeedWorld = PackRuntime.forEngine(engineWithDepositSeed(41L), data).deposit(generator); - assertNotEquals(firstWorld, secondWorld); - assertNotEquals(firstWorld, largerVein); - assertEquals(firstWorld, new IrisDepositGenerator.ClumpCacheKey(41L, 4, 8)); + assertSame(firstWorld.clumps(), firstWorld.clumps()); + assertSame(firstWorld.scaledClumps(4, 8), firstWorld.scaledClumps(4, 8)); + assertEquals(blocks(firstWorld.clumps()), blocks(sameSeedWorld.clumps())); + assertNotEquals(blocks(firstWorld.clumps()), blocks(secondWorld.clumps())); + assertNotEquals(blocks(firstWorld.scaledClumps(4, 8)), blocks(firstWorld.scaledClumps(8, 16))); + assertNotEquals(blocks(firstWorld.clumps()), blocks(firstWorld.scaledClumps(4, 8))); + } + + private static IrisDepositGenerator paletteGenerator(IrisData data) { + IrisDepositGenerator generator = new IrisDepositGenerator(); + for (String key : new String[]{"minecraft:iron_ore", "minecraft:gold_ore", "minecraft:copper_ore"}) { + IrisBlockData block = mock(IrisBlockData.class); + NativeBlockState state = mock(NativeBlockState.class); + when(block.getBlockData(data)).thenReturn(state); + when(state.key()).thenReturn(key); + generator.getPalette().add(block); + } + return generator; + } + + private static Engine engineWithDepositSeed(long depositSeed) { + SeedManager seeds = mock(SeedManager.class); + when(seeds.getDeposit()).thenReturn(depositSeed); + Engine engine = mock(Engine.class); + when(engine.getSeedManager()).thenReturn(seeds); + return engine; + } + + private static List blocks(KList clumps) { + List blocks = new ArrayList<>(); + for (IrisObject clump : clumps) { + VectorMap.Cursor cursor = clump.getBlocks().cursor(); + while (cursor.next()) { + blocks.add(cursor.key().getBlockX() + "," + cursor.key().getBlockY() + "," + + cursor.key().getBlockZ() + "=" + cursor.value().key()); + } + blocks.add("|"); + } + return blocks; } @Test @@ -237,7 +276,7 @@ public class IrisDepositTuningTest { generator.setMinSize(size).setMaxSize(size); for (long seed = 0; seed < 300; seed++) { RNG built = new RNG(seed); - IrisObject clump = generator.getClump(null, built, data); + IrisObject clump = generator.getClump(PackRuntime.standalone(data), built); RNG sampled = new RNG(seed); IrisDepositGenerator.ClumpFootprint footprint = generator.sampleClumpFootprint(sampled, data); assertNotNull(footprint); @@ -269,7 +308,7 @@ public class IrisDepositTuningTest { generator.setMinSize(size).setMaxSize(size); for (long seed = 0; seed < 300; seed++) { RNG built = new RNG(seed); - IrisObject clump = generator.getClump(null, built, data); + IrisObject clump = generator.getClump(PackRuntime.standalone(data), built); long expectedNext = built.nextLong(); List expected = new ArrayList<>(); VectorMap.Cursor cursor = clump.getBlocks().cursor(); @@ -325,7 +364,7 @@ public class IrisDepositTuningTest { for (int size : new int[]{0, 1, 3, 4, 9, 17, 25, 64}) { generator.setMinSize(size).setMaxSize(size); for (long seed = 0; seed < 300; seed++) { - IrisObject clump = generator.getClump(null, new RNG(seed), data); + IrisObject clump = generator.getClump(PackRuntime.standalone(data), new RNG(seed)); List expected = new ArrayList<>(); VectorMap.Cursor cursor = clump.getBlocks().cursor(); while (cursor.next()) { diff --git a/core/src/test/java/art/arcane/iris/generation/decoration/IrisOreBandsTest.java b/core/src/test/java/art/arcane/iris/generation/decoration/IrisOreBandsTest.java index f9ca00b29..389e34805 100644 --- a/core/src/test/java/art/arcane/iris/generation/decoration/IrisOreBandsTest.java +++ b/core/src/test/java/art/arcane/iris/generation/decoration/IrisOreBandsTest.java @@ -1,7 +1,7 @@ package art.arcane.iris.generation.decoration; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.block.IrisBlockData; -import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.testsupport.KeyedBlockState; import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.NoiseStyle; @@ -48,7 +48,7 @@ public class IrisOreBandsTest { } for (int x = -3; x <= 3; x++) { assertSame("trial " + trial + " y " + y + " x " + x, - scan(ores, x, y, 5 - x), bands.generate(x, y, 5 - x, RNG_SOURCE, null, null)); + scan(ores, x, y, 5 - x), generate(bands, x, y, 5 - x)); } } } @@ -71,7 +71,7 @@ public class IrisOreBandsTest { IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.FLAT).setZoom(2.5D).setExponent(1.3D) .setFracture(new IrisGeneratorStyle(NoiseStyle.SIMPLEX).setMultiplier(9D)); flat.setPalette(palette).setChanceStyle(style).setRange(new IrisRange(0, 100)); - CNG reference = style.create(RNG_SOURCE, null); + CNG reference = style.create(RNG_SOURCE, PackRuntime.standalone(null)); for (double threshold : new double[]{0.1D, 0.5D, 0.99D, 1D}) { flat.setThreshold(threshold); for (int index = 0; index < 100; index++) { @@ -79,14 +79,18 @@ public class IrisOreBandsTest { int y = index % 101; int z = 400 - index * 11; NativeBlockState expected = reference.noise(x, y, z) > threshold ? null : ore; - assertSame(expected, flat.generate(x, y, z, RNG_SOURCE, null)); + assertSame(expected, flat.generate(x, y, z, RNG_SOURCE, PackRuntime.standalone(null))); } } } + private static NativeBlockState generate(IrisOreBands bands, int x, int y, int z) { + return PackRuntime.standalone(null).oreBands(bands, RNG_SOURCE.getSeed()).generate(x, y, z, RNG_SOURCE); + } + private static NativeBlockState scan(KList ores, int x, int y, int z) { for (IrisOreGenerator ore : ores) { - NativeBlockState state = ore.generate(x, y, z, RNG_SOURCE, null); + NativeBlockState state = ore.generate(x, y, z, RNG_SOURCE, PackRuntime.standalone(null)); if (state != null) { return state; } @@ -110,10 +114,10 @@ public class IrisOreBandsTest { ores.add(generator(1D, 57D, 1D, 2L)); ores.add(generator(58D, 58D, 1D, 3L)); IrisOreBands bands = IrisOreBands.of(ores); - assertSame(scan(ores, 0, 0, 0), bands.generate(0, 0, 0, RNG_SOURCE, null, null)); - assertSame(scan(ores, 0, 30, 0), bands.generate(0, 30, 0, RNG_SOURCE, null, null)); - assertSame(scan(ores, 0, 58, 0), bands.generate(0, 58, 0, RNG_SOURCE, null, null)); - assertNull(bands.contains(59) ? bands.generate(0, 59, 0, RNG_SOURCE, null, null) : null); + assertSame(scan(ores, 0, 0, 0), generate(bands, 0, 0, 0)); + assertSame(scan(ores, 0, 30, 0), generate(bands, 0, 30, 0)); + assertSame(scan(ores, 0, 58, 0), generate(bands, 0, 58, 0)); + assertNull(bands.contains(59) ? generate(bands, 0, 59, 0) : null); } private static final class FixedPalette extends IrisMaterialPalette { private final NativeBlockState state; @@ -124,7 +128,7 @@ public class IrisOreBandsTest { } @Override - public NativeBlockState get(RNG rng, double x, double y, double z, IrisData data) { + public NativeBlockState get(RNG rng, double x, double y, double z, PackRuntime runtime) { return state; } } @@ -137,7 +141,7 @@ public class IrisOreBandsTest { } @Override - public CNG create(RNG rng, IrisData data) { + public CNG create(RNG rng, PackRuntime runtime) { return chance; } } diff --git a/core/src/test/java/art/arcane/iris/generation/decoration/IrisOreGeneratorTest.java b/core/src/test/java/art/arcane/iris/generation/decoration/IrisOreGeneratorTest.java index 8fa663482..24d227754 100644 --- a/core/src/test/java/art/arcane/iris/generation/decoration/IrisOreGeneratorTest.java +++ b/core/src/test/java/art/arcane/iris/generation/decoration/IrisOreGeneratorTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.decoration; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.block.IrisBlockData; import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.terrain.IrisMaterialPalette; @@ -25,7 +26,7 @@ public class IrisOreGeneratorTest { Fixture fixture = new Fixture(0.0); fixture.generator.setThreshold(0.0); - assertNull(fixture.generator.generate(2, 40, 3, fixture.rng, null)); + assertNull(fixture.generator.generate(2, 40, 3, fixture.rng, PackRuntime.standalone(null))); verifyNoInteractions(fixture.noise, fixture.style); } @@ -34,12 +35,12 @@ public class IrisOreGeneratorTest { Fixture fixture = new Fixture(0.5); fixture.generator.setThreshold(0.5); - assertSame(fixture.ore, fixture.generator.generate(2, 30, 3, fixture.rng, null)); - assertSame(fixture.ore, fixture.generator.generate(2, 80, 3, fixture.rng, null)); - assertNull(fixture.generator.generate(2, 29, 3, fixture.rng, null)); - assertNull(fixture.generator.generate(2, 81, 3, fixture.rng, null)); + assertSame(fixture.ore, fixture.generator.generate(2, 30, 3, fixture.rng, PackRuntime.standalone(null))); + assertSame(fixture.ore, fixture.generator.generate(2, 80, 3, fixture.rng, PackRuntime.standalone(null))); + assertNull(fixture.generator.generate(2, 29, 3, fixture.rng, PackRuntime.standalone(null))); + assertNull(fixture.generator.generate(2, 81, 3, fixture.rng, PackRuntime.standalone(null))); fixture.generator.setThreshold(0.49); - assertNull(fixture.generator.generate(2, 40, 3, fixture.rng, null)); + assertNull(fixture.generator.generate(2, 40, 3, fixture.rng, PackRuntime.standalone(null))); } @Test @@ -47,7 +48,7 @@ public class IrisOreGeneratorTest { Fixture fixture = new Fixture(1.0); fixture.generator.setThreshold(1.0); - assertSame(fixture.ore, fixture.generator.generate(2, 40, 3, fixture.rng, null)); + assertSame(fixture.ore, fixture.generator.generate(2, 40, 3, fixture.rng, PackRuntime.standalone(null))); } private static final class Fixture { @@ -60,9 +61,9 @@ public class IrisOreGeneratorTest { private Fixture(double sample) { IrisMaterialPalette palette = mock(IrisMaterialPalette.class); when(palette.getPalette()).thenReturn(new KList<>(mock(IrisBlockData.class))); - when(palette.get(any(), anyDouble(), anyDouble(), anyDouble(), isNull())).thenReturn(ore); + when(palette.get(any(), anyDouble(), anyDouble(), anyDouble(), any(PackRuntime.class))).thenReturn(ore); when(noise.noise(anyDouble(), anyDouble(), anyDouble())).thenReturn(sample); - when(style.create(any(), isNull())).thenReturn(noise); + when(style.create(any(), any(PackRuntime.class))).thenReturn(noise); generator.setPalette(palette); generator.setChanceStyle(style); } diff --git a/core/src/test/java/art/arcane/iris/generation/decoration/IrisOreSeedCohesionTest.java b/core/src/test/java/art/arcane/iris/generation/decoration/IrisOreSeedCohesionTest.java index b0cda3c3f..32a63b44f 100644 --- a/core/src/test/java/art/arcane/iris/generation/decoration/IrisOreSeedCohesionTest.java +++ b/core/src/test/java/art/arcane/iris/generation/decoration/IrisOreSeedCohesionTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.decoration; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.NoiseStyle; import art.arcane.iris.generation.terrain.IrisMaterialPalette; @@ -36,7 +37,7 @@ public class IrisOreSeedCohesionTest { for (int i = SEEDS.length - 1; i >= 0; i--) { IrisOreGenerator cold = generator(); long[] expected = sample(cold, new RNG(SEEDS[i]), data, false); - shared.warm(new RNG(SEEDS[(i + 1) % SEEDS.length]), data); + shared.warm(new RNG(SEEDS[(i + 1) % SEEDS.length]), PackRuntime.of(data.getEngine(), data)); assertArrayEquals(expected, sample(shared, new RNG(SEEDS[i]), data, true)); RNG consumed = new RNG(SEEDS[i]); for (int draw = 0; draw < 128; draw++) { @@ -93,7 +94,7 @@ public class IrisOreSeedCohesionTest { for (int index = 0; index < SAMPLES; index++) { int sample = reverse ? SAMPLES - index - 1 : index; NativeBlockState block = generator.generate(sample * 13 - 901, - sample % 257, sample * 7 - 713, rng, data); + sample % 257, sample * 7 - 713, rng, PackRuntime.of(data.getEngine(), data)); output[sample] = block == null ? 0L : block.key().hashCode(); } return output; diff --git a/core/src/test/java/art/arcane/iris/generation/decoration/IrisSeaDecoratorBoundsTest.java b/core/src/test/java/art/arcane/iris/generation/decoration/IrisSeaDecoratorBoundsTest.java index 5959fbe71..dd29bfbf5 100644 --- a/core/src/test/java/art/arcane/iris/generation/decoration/IrisSeaDecoratorBoundsTest.java +++ b/core/src/test/java/art/arcane/iris/generation/decoration/IrisSeaDecoratorBoundsTest.java @@ -1,6 +1,8 @@ package art.arcane.iris.generation.decoration; import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.pack.loading.IrisData; +import art.arcane.iris.testsupport.MockPackData; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.volmlib.nativelib.terrain.NativeBlockState; import art.arcane.volmlib.util.hunk.Hunk; @@ -121,10 +123,13 @@ public class IrisSeaDecoratorBoundsTest { private Fixture(int height, boolean surface) { when(engine.getHeight()).thenReturn(height); + IrisData data = MockPackData.create(); + when(engine.getPackRuntime()).thenReturn(null); + when(engine.getData()).thenReturn(data); output = Hunk.newArrayHunk(1, height, 1); IrisDecorationPart part = surface ? IrisDecorationPart.SEA_SURFACE : IrisDecorationPart.SEA_FLOOR; when(biome.getDecoratorBucket(part)).thenReturn(new IrisDecorator[]{decorator}); - when(decorator.passesChanceGate(any(), anyDouble(), anyDouble(), any())).thenReturn(true); + when(decorator.passesChanceGate(any(), anyDouble(), anyDouble(), any(DecoratorRuntime.class))).thenReturn(true); when(decorator.getBlockData100(any(), any(), anyDouble(), anyDouble(), anyDouble(), any())).thenReturn(body); when(decorator.getBlockDataForTop(any(), any(), anyDouble(), anyDouble(), anyDouble(), any())).thenReturn(top); when(decorator.getTopThreshold()).thenReturn(1D); diff --git a/core/src/test/java/art/arcane/iris/generation/decoration/IrisShoreLineDecoratorTest.java b/core/src/test/java/art/arcane/iris/generation/decoration/IrisShoreLineDecoratorTest.java index a6d61fa3a..378346ffc 100644 --- a/core/src/test/java/art/arcane/iris/generation/decoration/IrisShoreLineDecoratorTest.java +++ b/core/src/test/java/art/arcane/iris/generation/decoration/IrisShoreLineDecoratorTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.decoration; +import art.arcane.iris.testsupport.MockPackData; import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.generation.runtime.IrisComplex; import art.arcane.iris.generation.mantle.EngineMantle; @@ -70,9 +71,9 @@ public class IrisShoreLineDecoratorTest { output, fixture.biome, FLUID_HEIGHT, output.getHeight()); assertSame(targetAir, output.get(0, FLUID_HEIGHT + 1, 0)); - verify(fixture.decorator).passesChanceGate(any(), anyDouble(), anyDouble(), eq(fixture.data)); + verify(fixture.decorator).passesChanceGate(any(), anyDouble(), anyDouble(), MockPackData.decoratorRuntimeOf(fixture.data)); verify(fixture.decorator, never()).getBlockData100( - eq(fixture.biome), any(), anyDouble(), anyDouble(), anyDouble(), eq(fixture.data)); + eq(fixture.biome), any(), anyDouble(), anyDouble(), anyDouble(), MockPackData.runtimeOf(fixture.data)); } @Test @@ -88,7 +89,7 @@ public class IrisShoreLineDecoratorTest { assertSame(targetAir, output.get(0, FLUID_HEIGHT + 1, 0)); verify(fixture.decorator, never()).getBlockData100( - eq(fixture.biome), any(), anyDouble(), anyDouble(), anyDouble(), eq(fixture.data)); + eq(fixture.biome), any(), anyDouble(), anyDouble(), anyDouble(), MockPackData.runtimeOf(fixture.data)); } @Test @@ -199,13 +200,13 @@ public class IrisShoreLineDecoratorTest { when(fixture.decorator.isStacking()).thenReturn(true); when(fixture.decorator.isScaleStack()).thenReturn(false); when(fixture.decorator.getStackMax()).thenReturn(2); - when(fixture.decorator.getHeight(any(), anyDouble(), anyDouble(), eq(fixture.data))).thenReturn(2); + when(fixture.decorator.getHeight(any(), anyDouble(), anyDouble(), MockPackData.runtimeOf(fixture.data))).thenReturn(2); when(fixture.decorator.getTopThreshold()).thenReturn(1D); when(fixture.decorator.getBlockDataArray(fixture.data)).thenReturn(new NativeBlockState[0]); when(fixture.decorator.getBlockDataTopsArray(fixture.data)) .thenReturn(new NativeBlockState[]{waterloggedTop}); when(fixture.decorator.getBlockDataForTop( - eq(fixture.biome), any(), anyDouble(), anyDouble(), anyDouble(), eq(fixture.data))) + eq(fixture.biome), any(), anyDouble(), anyDouble(), anyDouble(), MockPackData.runtimeOf(fixture.data))) .thenReturn(waterloggedTop); Hunk output = Hunk.newArrayHunk(1, FLUID_HEIGHT + 3, 1); @@ -239,7 +240,7 @@ public class IrisShoreLineDecoratorTest { SeedManager seedManager = mock(SeedManager.class); IrisDimension dimension = mock(IrisDimension.class); IrisComplex complex = mock(IrisComplex.class); - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); IrisBiome biome = mock(IrisBiome.class); IrisDecorator decorator = mock(IrisDecorator.class); IrisSlopeClip slope = mock(IrisSlopeClip.class); @@ -263,11 +264,11 @@ public class IrisShoreLineDecoratorTest { when(engine.getData()).thenReturn(data); when(biome.getDecoratorBucket(IrisDecorationPart.SHORE_LINE)) .thenReturn(new IrisDecorator[]{decorator}); - when(decorator.passesChanceGate(any(), anyDouble(), anyDouble(), eq(data))).thenReturn(true); + when(decorator.passesChanceGate(any(), anyDouble(), anyDouble(), MockPackData.decoratorRuntimeOf(data))).thenReturn(true); when(decorator.isForcePlace()).thenReturn(forcePlace); when(decorator.getSlopeCondition()).thenReturn(slope); when(slope.isDefault()).thenReturn(true); - when(decorator.getBlockData100(eq(biome), any(), anyDouble(), anyDouble(), anyDouble(), eq(data))) + when(decorator.getBlockData100(eq(biome), any(), anyDouble(), anyDouble(), anyDouble(), MockPackData.runtimeOf(data))) .thenReturn(decorant); return new Fixture(new IrisShoreLineDecorator(engine), data, biome, decorator, decorant); @@ -282,10 +283,10 @@ public class IrisShoreLineDecoratorTest { when(fixture.decorator.isStacking()).thenReturn(true); when(fixture.decorator.isScaleStack()).thenReturn(true); when(fixture.decorator.getAbsoluteMaxStack()).thenReturn(3); - when(fixture.decorator.getHeight(any(), anyDouble(), anyDouble(), eq(fixture.data))).thenReturn(100); + when(fixture.decorator.getHeight(any(), anyDouble(), anyDouble(), MockPackData.runtimeOf(fixture.data))).thenReturn(100); when(fixture.decorator.getTopThreshold()).thenReturn(0.9D); when(fixture.decorator.getBlockDataForTop(eq(fixture.biome), any(), anyDouble(), anyDouble(), - anyDouble(), eq(fixture.data))).thenReturn(top); + anyDouble(), MockPackData.runtimeOf(fixture.data))).thenReturn(top); Hunk output = Hunk.newArrayHunk(1, 64, 1); for (int y = FLUID_HEIGHT + 1; y < output.getHeight(); y++) { output.set(0, y, 0, airState()); diff --git a/core/src/test/java/art/arcane/iris/generation/decoration/IrisSugarCanePlacementTest.java b/core/src/test/java/art/arcane/iris/generation/decoration/IrisSugarCanePlacementTest.java index d4e311505..5e8a3265f 100644 --- a/core/src/test/java/art/arcane/iris/generation/decoration/IrisSugarCanePlacementTest.java +++ b/core/src/test/java/art/arcane/iris/generation/decoration/IrisSugarCanePlacementTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.decoration; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.runtime.IrisComplex; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.hydrology.raster.WaterRole; @@ -122,13 +123,13 @@ public class IrisSugarCanePlacementTest { int world = -16 + local; switch (placement) { case FLOATING_SINGLE -> DecoratorCore.placeFloatingSimple(decorator, local, local, world, world, - 3, 4, output, new RNG(1L), null, mantle); + 3, 4, output, new RNG(1L), PackRuntime.standalone(null), mantle); case FLOATING_STACK -> DecoratorCore.placeFloatingStacked(decorator, local, local, world, world, - 3, 4, output, new RNG(1L), null, mantle); + 3, 4, output, new RNG(1L), PackRuntime.standalone(null), mantle); case CEILING_SINGLE -> DecoratorCore.placeSingleAt(decorator, local, local, world, 4, world, - output, new RNG(1L), null, false, mantle); + output, new RNG(1L), PackRuntime.standalone(null), false, mantle); case CEILING_STACK -> DecoratorCore.placeStackDown(decorator, local, local, world, world, - 4, 0, output, new RNG(1L), null, 2, new DecoratorCore.PlaceOpts(), mantle); + 4, 0, output, new RNG(1L), PackRuntime.standalone(null), 2, new DecoratorCore.PlaceOpts(), mantle); } } } diff --git a/core/src/test/java/art/arcane/iris/generation/decoration/formation/FormationBlockResolverTest.java b/core/src/test/java/art/arcane/iris/generation/decoration/formation/FormationBlockResolverTest.java index edf506ec1..d30c8ae79 100644 --- a/core/src/test/java/art/arcane/iris/generation/decoration/formation/FormationBlockResolverTest.java +++ b/core/src/test/java/art/arcane/iris/generation/decoration/formation/FormationBlockResolverTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.decoration.formation; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.block.IrisBlockData; import art.arcane.iris.generation.terrain.IrisMaterialPalette; import art.arcane.volmlib.nativelib.terrain.NativeBlockState; @@ -51,7 +52,7 @@ public class FormationBlockResolverTest { long sampleSeed = formation.getSeed() + (expectedPalette == strata ? sampleY * 31L : 0L); RNG fresh = new RNG(sampleSeed); NativeBlockState expected = expectedPalette.get(fresh, - position.getBlockX(), sampleY, position.getBlockZ(), null); + position.getBlockX(), sampleY, position.getBlockZ(), PackRuntime.forPack(null)); assertSame(expected, resolver.resolve(role, position)); assertEquals(new RNG(sampleSeed).nextLong(), fresh.nextLong()); materials.add(expected.key()); diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/IrisCaveCarver3DCellKernelTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/IrisCaveCarver3DCellKernelTest.java index 0949188db..e9dd47f93 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/IrisCaveCarver3DCellKernelTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/IrisCaveCarver3DCellKernelTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.mantle; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.cave.IrisCaveFieldModule; import art.arcane.iris.generation.cave.IrisCaveProfile; import art.arcane.iris.generation.noise.IrisGeneratorStyle; @@ -154,6 +155,7 @@ public class IrisCaveCarver3DCellKernelTest { IrisDimension dimension = mock(IrisDimension.class, withSettings().stubOnly()); SeedManager seedManager = mock(SeedManager.class, withSettings().stubOnly()); doReturn(data).when(engine).getData(); + doReturn(PackRuntime.forEngine(engine, data)).when(engine).getPackRuntime(); doReturn(dimension).when(engine).getDimension(); doReturn(seedManager).when(engine).getSeedManager(); doReturn(CARVE_SEED).when(seedManager).getCarve(); diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/IrisCaveCarver3DLatticeTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/IrisCaveCarver3DLatticeTest.java index 2f0d6aab3..566449ad3 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/IrisCaveCarver3DLatticeTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/IrisCaveCarver3DLatticeTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.mantle; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.cave.IrisCaveFieldModule; import art.arcane.iris.generation.cave.IrisCaveProfile; import art.arcane.iris.generation.noise.IrisGeneratorStyle; @@ -162,6 +163,7 @@ public class IrisCaveCarver3DLatticeTest { IrisDimension dimension = mock(IrisDimension.class, withSettings().stubOnly()); SeedManager seedManager = mock(SeedManager.class, withSettings().stubOnly()); doReturn(data).when(engine).getData(); + doReturn(PackRuntime.forEngine(engine, data)).when(engine).getPackRuntime(); doReturn(dimension).when(engine).getDimension(); doReturn(seedManager).when(engine).getSeedManager(); doReturn(CARVE_SEED).when(seedManager).getCarve(); diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/IrisCaveCarver3DNearParityTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/IrisCaveCarver3DNearParityTest.java index b9c2b1206..14db525fe 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/IrisCaveCarver3DNearParityTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/IrisCaveCarver3DNearParityTest.java @@ -1,5 +1,7 @@ package art.arcane.iris.generation.mantle; +import art.arcane.iris.generation.runtime.ThreadSlots; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.EngineMetrics; @@ -209,7 +211,7 @@ public class IrisCaveCarver3DNearParityTest { }).when(density).noiseFastSigned3D(anyDouble(), anyDouble(), anyDouble()); IrisGeneratorStyle style = mock(IrisGeneratorStyle.class, withSettings().stubOnly()); doReturn("density_expression").when(style).getExpression(); - doReturn(density).when(style).create(any(RNG.class), any(IrisData.class)); + doReturn(density).when(style).create(any(RNG.class), any()); IrisCaveProfile profile = createProfile(false, false).setBaseDensityStyle(style) .setDetailWeight(0D).setAllowFluid(false) .setDensityThreshold(new IrisStyledRange(0.15D, 0.15D, new IrisGeneratorStyle(NoiseStyle.FLAT))); @@ -377,7 +379,7 @@ public class IrisCaveCarver3DNearParityTest { } Field scratchField = IrisCaveCarver3D.class.getDeclaredField("scratchCache"); scratchField.setAccessible(true); - ThreadLocal scratchCache = (ThreadLocal) scratchField.get(carver); + ThreadSlots scratchCache = (ThreadSlots) scratchField.get(carver); CaveCarveScratch scratch = (CaveCarveScratch) scratchCache.get(); assertTrue(scratch.sectionMatter.length > 0); for (Matter matter : scratch.sectionMatter) { @@ -1304,7 +1306,7 @@ public class IrisCaveCarver3DNearParityTest { .noiseFastSigned3D(anyDouble(), anyDouble(), anyDouble()); IrisGeneratorStyle style = mock(IrisGeneratorStyle.class, withSettings().stubOnly()); doReturn("density_expression").when(style).getExpression(); - doReturn(density).when(style).create(any(RNG.class), any(IrisData.class)); + doReturn(density).when(style).create(any(RNG.class), any()); AtomicInteger lookups = new AtomicInteger(); CaveDensityGrid grid = countingGrid(4, lookups); IrisCaveCarver3D carver = new IrisCaveCarver3D(engine, @@ -1470,7 +1472,7 @@ public class IrisCaveCarver3DNearParityTest { continue; } - passThreshold[columnIndex] = profile.getDensityThreshold().get(thresholdRng, x, z, data) - profile.getThresholdBias(); + passThreshold[columnIndex] = profile.getDensityThreshold().get(thresholdRng, x, z, PackRuntime.standalone(data)) - profile.getThresholdBias(); } } @@ -1642,6 +1644,7 @@ public class IrisCaveCarver3DNearParityTest { IrisWorld world = IrisWorld.builder().minHeight(0).maxHeight(worldHeight).build(); doReturn(data).when(engine).getData(); + doReturn(PackRuntime.forEngine(engine, data)).when(engine).getPackRuntime(); doReturn(dimension).when(engine).getDimension(); doReturn(seedManager).when(engine).getSeedManager(); doReturn(CARVE_SEED).when(seedManager).getCarve(); diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/IrisStructureFoundationWriteTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/IrisStructureFoundationWriteTest.java index d7bff947e..9e94db9c1 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/IrisStructureFoundationWriteTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/IrisStructureFoundationWriteTest.java @@ -1,6 +1,6 @@ package art.arcane.iris.generation.mantle; -import art.arcane.iris.pack.loading.IrisData; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.terrain.IrisMaterialPalette; import art.arcane.volmlib.nativelib.terrain.NativeBlockState; import art.arcane.volmlib.util.matter.MatterCavern; @@ -20,15 +20,15 @@ public class IrisStructureFoundationWriteTest { MantleWriter writer = mock(MantleWriter.class); IrisMaterialPalette palette = mock(IrisMaterialPalette.class); RNG rng = new RNG(1337L); - IrisData data = mock(IrisData.class); + PackRuntime runtime = PackRuntime.standalone(null); NativeBlockState deepslateBricks = mock(NativeBlockState.class); - when(palette.get(rng, 12, -247, -18, data)).thenReturn(deepslateBricks); + when(palette.get(rng, 12, -247, -18, runtime)).thenReturn(deepslateBricks); IrisStructureComponent.writeFoundationSupport( - writer, palette, rng, data, 12, 9, -18, -256); + writer, palette, rng, runtime, 12, 9, -18, -256); InOrder order = inOrder(palette, writer); - order.verify(palette).get(rng, 12, -247, -18, data); + order.verify(palette).get(rng, 12, -247, -18, runtime); order.verify(writer).clearData(12, 9, -18, MatterCavern.class); order.verify(writer).set(12, 9, -18, deepslateBricks); } @@ -38,11 +38,11 @@ public class IrisStructureFoundationWriteTest { MantleWriter writer = mock(MantleWriter.class); IrisMaterialPalette palette = mock(IrisMaterialPalette.class); RNG rng = new RNG(1337L); - IrisData data = mock(IrisData.class); + PackRuntime runtime = PackRuntime.standalone(null); try { IrisStructureComponent.writeFoundationSupport( - writer, palette, rng, data, 12, 9, -18, -256); + writer, palette, rng, runtime, 12, 9, -18, -256); } catch (IllegalStateException error) { assertTrue(error.getMessage().contains("12,-247,-18")); verifyNoInteractions(writer); diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/MantleCarvedTerrainTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/MantleCarvedTerrainTest.java index ba0455eeb..58e48945c 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/MantleCarvedTerrainTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/MantleCarvedTerrainTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.mantle; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.terrain.transform.IrisTerrainTransform; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.hydrology.cave.HydrologyCaveAction; @@ -366,6 +367,7 @@ public class MantleCarvedTerrainTest { case "getWorld" -> world; case "getPlatformHooks" -> hooks; case "getData" -> null; + case "getPackRuntime" -> null; default -> InvocationHandler.invokeDefault(proxy, method, arguments); }); } diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/MantleFloatingObjectComponentEmptyTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/MantleFloatingObjectComponentEmptyTest.java index 9d743a033..ee48e75ce 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/MantleFloatingObjectComponentEmptyTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/MantleFloatingObjectComponentEmptyTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.mantle; +import art.arcane.iris.testsupport.MockPackData; import art.arcane.iris.generation.biome.FloatingIslandBoundarySampler; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.biome.IrisFloatingChildBiomes; @@ -201,7 +202,7 @@ public class MantleFloatingObjectComponentEmptyTest { private Fixture(IrisBiome biome) { biomes = mock(ResourceLoader.class); ResourceLoader objects = mock(ResourceLoader.class); - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); when(data.getBiomeLoader()).thenReturn(biomes); when(data.getObjectLoader()).thenReturn(objects); when(dimension.isUseMantle()).thenReturn(true); diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/PlacementReachTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/PlacementReachTest.java index f32449792..ee6239092 100644 --- a/core/src/test/java/art/arcane/iris/generation/mantle/PlacementReachTest.java +++ b/core/src/test/java/art/arcane/iris/generation/mantle/PlacementReachTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.mantle; +import art.arcane.iris.testsupport.MockPackData; import art.arcane.iris.generation.block.TileData; import art.arcane.iris.generation.decoration.IrisStiltSettings; import art.arcane.iris.generation.decoration.IrisVacuumSettings; @@ -78,9 +79,9 @@ public class PlacementReachTest { when(engine.getHeight()).thenReturn(256); when(engine.getMinHeight()).thenReturn(0); when(engine.getComplex()).thenReturn(complex); - data = mock(IrisData.class, withSettings().stubOnly()); + data = MockPackData.stubOnly(); when(data.getEngine()).thenReturn(engine); - objectData = mock(IrisData.class, withSettings().stubOnly()); + objectData = MockPackData.stubOnly(); } @After diff --git a/core/src/test/java/art/arcane/iris/generation/noise/GeneratorProgramParityTest.java b/core/src/test/java/art/arcane/iris/generation/noise/GeneratorProgramParityTest.java index 016d1c6cb..6c98a3732 100644 --- a/core/src/test/java/art/arcane/iris/generation/noise/GeneratorProgramParityTest.java +++ b/core/src/test/java/art/arcane/iris/generation/noise/GeneratorProgramParityTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.noise; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.volmlib.util.collection.KList; import org.junit.Test; @@ -8,6 +9,8 @@ import java.util.SplittableRandom; import static org.junit.Assert.assertEquals; public class GeneratorProgramParityTest { + private final PackRuntime runtime = PackRuntime.standalone(null); + private static final NoiseStyle[] STYLES = { NoiseStyle.SIMPLEX, NoiseStyle.PERLIN, NoiseStyle.IRIS, NoiseStyle.IRIS_HALF, NoiseStyle.FRACTAL_SMOKE, NoiseStyle.FRACTAL_WATER, NoiseStyle.CLOVER, NoiseStyle.CELLULAR, NoiseStyle.NOWHERE, @@ -24,7 +27,7 @@ public class GeneratorProgramParityTest { IrisGenerator scalar = generator(new SplittableRandom(shapeSeed)); IrisGenerator batch = generator(new SplittableRandom(shapeSeed)); long superSeed = random.nextLong(); - GeneratorProgram program = batch.compileProgram(superSeed); + GeneratorProgram program = batch.compileProgram(runtime, superSeed); int count = 1 + random.nextInt(600); double[] xs = new double[count]; double[] zs = new double[count]; @@ -33,7 +36,7 @@ public class GeneratorProgramParityTest { program.heights(scratch, xs, zs, count, out); for (int index = 0; index < count; index++) { assertEquals("generator " + generatorIndex + " point " + xs[index] + "," + zs[index], - Double.doubleToRawLongBits(scalar.getHeight(xs[index], zs[index], superSeed)), + Double.doubleToRawLongBits(scalar.getHeight(runtime, xs[index], zs[index], superSeed)), Double.doubleToRawLongBits(out[index])); } } @@ -48,12 +51,12 @@ public class GeneratorProgramParityTest { IrisGenerator scalar = generator(new SplittableRandom(shapeSeed)); IrisGenerator compiled = generator(new SplittableRandom(shapeSeed)); long superSeed = random.nextLong(); - GeneratorProgram program = compiled.compileProgram(superSeed); + GeneratorProgram program = compiled.compileProgram(runtime, superSeed); for (int sample = 0; sample < 400; sample++) { double x = coordinate(random); double z = random.nextInt(5) == 0 ? x : coordinate(random); assertEquals("generator " + generatorIndex + " point " + x + "," + z, - Double.doubleToRawLongBits(scalar.getHeight(x, z, superSeed)), + Double.doubleToRawLongBits(scalar.getHeight(runtime, x, z, superSeed)), Double.doubleToRawLongBits(program.height(scratch, x, z))); } } @@ -71,7 +74,7 @@ public class GeneratorProgramParityTest { IrisGenerator scalar = generator(new SplittableRandom(shapeSeed)); IrisGenerator batch = generator(new SplittableRandom(shapeSeed)); long superSeed = random.nextLong(); - GeneratorProgram program = batch.compileProgram(superSeed); + GeneratorProgram program = batch.compileProgram(runtime, superSeed); for (int chunk = 0; chunk < 4; chunk++) { int originX = random.nextInt(-200_000, 200_000) << 4; int originZ = random.nextInt(-200_000, 200_000) << 4; @@ -81,7 +84,7 @@ public class GeneratorProgramParityTest { } program.heights(scratch, xs, zs, 256, out); for (int index = 0; index < 256; index++) { - assertEquals(Double.doubleToRawLongBits(scalar.getHeight(xs[index], zs[index], superSeed)), + assertEquals(Double.doubleToRawLongBits(scalar.getHeight(runtime, xs[index], zs[index], superSeed)), Double.doubleToRawLongBits(out[index])); } } diff --git a/core/src/test/java/art/arcane/iris/generation/noise/IrisExpressionCoordinateTest.java b/core/src/test/java/art/arcane/iris/generation/noise/IrisExpressionCoordinateTest.java index d903d2fce..dbf08d868 100644 --- a/core/src/test/java/art/arcane/iris/generation/noise/IrisExpressionCoordinateTest.java +++ b/core/src/test/java/art/arcane/iris/generation/noise/IrisExpressionCoordinateTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.noise; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; import org.junit.Test; @@ -10,17 +11,17 @@ public class IrisExpressionCoordinateTest { @Test public void planarEvaluationBindsHorizontalAxesAndAbsentHeight() { RNG rng = new RNG(17L); - assertEquals(23.5D, expression("x").evaluate(rng, 23.5D, -94.75D), 0D); - assertEquals(-94.75D, expression("y").evaluate(rng, 23.5D, -94.75D), 0D); - assertEquals(-1D, expression("z").evaluate(rng, 23.5D, -94.75D), 0D); + assertEquals(23.5D, runtimeOf(expression("x")).evaluate(rng, 23.5D, -94.75D), 0D); + assertEquals(-94.75D, runtimeOf(expression("y")).evaluate(rng, 23.5D, -94.75D), 0D); + assertEquals(-1D, runtimeOf(expression("z")).evaluate(rng, 23.5D, -94.75D), 0D); } @Test public void volumetricEvaluationBindsEachAxis() { RNG rng = new RNG(17L); - assertEquals(23.5D, expression("x").evaluate(rng, 23.5D, 61D, -94.75D), 0D); - assertEquals(61D, expression("y").evaluate(rng, 23.5D, 61D, -94.75D), 0D); - assertEquals(-94.75D, expression("z").evaluate(rng, 23.5D, 61D, -94.75D), 0D); + assertEquals(23.5D, runtimeOf(expression("x")).evaluate(rng, 23.5D, 61D, -94.75D), 0D); + assertEquals(61D, runtimeOf(expression("y")).evaluate(rng, 23.5D, 61D, -94.75D), 0D); + assertEquals(-94.75D, runtimeOf(expression("z")).evaluate(rng, 23.5D, 61D, -94.75D), 0D); } @Test @@ -28,16 +29,20 @@ public class IrisExpressionCoordinateTest { IrisExpression expression = expression("value + x + 10 * y + 100 * z") .setVariables(new KList<>(new IrisExpressionLoad().setName("value").setStaticValue(7D))); RNG rng = new RNG(17L); - assertEquals(-1017D, expression.evaluate(rng, 23.5D, -94.75D), 0D); - assertEquals(-8834.5D, expression.evaluate(rng, 23.5D, 61D, -94.75D), 0D); + assertEquals(-1017D, runtimeOf(expression).evaluate(rng, 23.5D, -94.75D), 0D); + assertEquals(-8834.5D, runtimeOf(expression).evaluate(rng, 23.5D, 61D, -94.75D), 0D); } @Test public void expressionStreamsAndNoiseUsePlanarCoordinates() { IrisExpression expression = expression("x + 100 * y"); RNG rng = new RNG(17L); - assertEquals(-9451.5D, expression.stream(rng).getDouble(23.5D, -94.75D), 0D); - assertEquals(-9451.5D, new ExpressionNoise(rng, expression).noise(23.5D, -94.75D), 0D); + assertEquals(-9451.5D, runtimeOf(expression).stream(rng).getDouble(23.5D, -94.75D), 0D); + assertEquals(-9451.5D, new ExpressionNoise(rng, runtimeOf(expression)).noise(23.5D, -94.75D), 0D); + } + + private static ExpressionRuntime runtimeOf(IrisExpression expression) { + return PackRuntime.standalone(null).expression(expression); } private static IrisExpression expression(String source) { diff --git a/core/src/test/java/art/arcane/iris/generation/noise/IrisExpressionLoadEngineCacheTest.java b/core/src/test/java/art/arcane/iris/generation/noise/IrisExpressionLoadEngineCacheTest.java index 95ed01f68..a94a99d8a 100644 --- a/core/src/test/java/art/arcane/iris/generation/noise/IrisExpressionLoadEngineCacheTest.java +++ b/core/src/test/java/art/arcane/iris/generation/noise/IrisExpressionLoadEngineCacheTest.java @@ -1,68 +1,60 @@ package art.arcane.iris.generation.noise; +import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.generation.runtime.IrisComplex; import art.arcane.iris.generation.runtime.IrisEngineStreamType; import art.arcane.iris.generation.runtime.IrisEngineValueType; - +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.pack.loading.IrisData; -import art.arcane.iris.generation.runtime.IrisComplex; -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.volmlib.util.stream.ProceduralStream; +import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.stream.ProceduralStream; import org.junit.Test; -import java.util.concurrent.atomic.AtomicReference; - import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class IrisExpressionLoadEngineCacheTest { @Test - public void engineValuesAreCachedPerEngineIdentity() { + public void engineValuesBelongToTheEngineRuntime() { Engine first = mock(Engine.class); Engine second = mock(Engine.class); when(first.getHeight()).thenReturn(128); when(second.getHeight()).thenReturn(320); - AtomicReference active = new AtomicReference<>(first); - IrisData data = data(active); - IrisExpressionLoad load = new IrisExpressionLoad() + IrisExpression expression = expression(new IrisExpressionLoad() .setName("height") - .setEngineValue(IrisEngineValueType.ENGINE_HEIGHT); + .setEngineValue(IrisEngineValueType.ENGINE_HEIGHT)); + IrisData data = mock(IrisData.class); - assertEquals(128D, load.getValue(new RNG(1L), data, 0D, 0D), 0D); - active.set(second); - assertEquals(320D, load.getValue(new RNG(1L), data, 0D, 0D), 0D); + assertEquals(128D, PackRuntime.forEngine(first, data).expression(expression).evaluate(new RNG(1L), 0D, 0D), 0D); + assertEquals(320D, PackRuntime.forEngine(second, data).expression(expression).evaluate(new RNG(1L), 0D, 0D), 0D); } @Test - public void engineStreamsAreCachedPerEngineIdentity() { - Engine first = streamEngine(12D); - Engine second = streamEngine(27D); - AtomicReference active = new AtomicReference<>(first); - IrisData data = data(active); - IrisExpressionLoad load = new IrisExpressionLoad() + public void engineStreamsBelongToTheEngineRuntime() { + IrisExpression expression = expression(new IrisExpressionLoad() .setName("height") - .setEngineStreamValue(IrisEngineStreamType.HEIGHT); + .setEngineStreamValue(IrisEngineStreamType.HEIGHT)); + IrisData data = mock(IrisData.class); - assertEquals(12D, load.getValue(new RNG(1L), data, 4D, 8D), 0D); - active.set(second); - assertEquals(27D, load.getValue(new RNG(1L), data, 4D, 8D), 0D); + assertEquals(12D, PackRuntime.forEngine(streamEngine(12D), data).expression(expression) + .evaluate(new RNG(1L), 4D, 8D), 0D); + assertEquals(27D, PackRuntime.forEngine(streamEngine(27D), data).expression(expression) + .evaluate(new RNG(1L), 4D, 8D), 0D); } @Test(expected = IllegalStateException.class) - public void engineBackedValueFailsWithoutUnambiguousEngine() { - IrisData data = mock(IrisData.class); - IrisExpressionLoad load = new IrisExpressionLoad() + public void engineBackedValueFailsWithoutAnEngine() { + IrisExpression expression = expression(new IrisExpressionLoad() .setName("height") - .setEngineValue(IrisEngineValueType.ENGINE_HEIGHT); + .setEngineValue(IrisEngineValueType.ENGINE_HEIGHT)); - load.getValue(new RNG(1L), data, 0D, 0D); + PackRuntime.standalone(mock(IrisData.class)).expression(expression).evaluate(new RNG(1L), 0D, 0D); } - private IrisData data(AtomicReference active) { - IrisData data = mock(IrisData.class); - when(data.getEngine()).thenAnswer(ignored -> active.get()); - return data; + private static IrisExpression expression(IrisExpressionLoad variable) { + return new IrisExpression().setExpression("height").setVariables(new KList<>(variable)); } private Engine streamEngine(double value) { diff --git a/core/src/test/java/art/arcane/iris/generation/noise/IrisExpressionScratchTest.java b/core/src/test/java/art/arcane/iris/generation/noise/IrisExpressionScratchTest.java index 5cdcbba6e..f88879d1e 100644 --- a/core/src/test/java/art/arcane/iris/generation/noise/IrisExpressionScratchTest.java +++ b/core/src/test/java/art/arcane/iris/generation/noise/IrisExpressionScratchTest.java @@ -1,10 +1,12 @@ package art.arcane.iris.generation.noise; -import art.arcane.iris.pack.loading.IrisData; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; import com.dfsek.paralithic.Expression; import com.dfsek.paralithic.functions.dynamic.Context; +import com.dfsek.paralithic.functions.dynamic.DynamicFunction; +import com.dfsek.paralithic.node.Statefulness; import org.junit.Test; import java.util.ArrayList; @@ -15,6 +17,7 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; @@ -27,9 +30,8 @@ import static org.mockito.Mockito.mock; public class IrisExpressionScratchTest { @Test public void sequentialPlanarAndVolumetricSamplesReuseTheArgumentArrayAndKeepRngState() { - IrisExpression expression = new IrisExpression(); Expression compiled = mock(Expression.class); - expression.getExpressionCache().aquire(() -> compiled); + ExpressionRuntime expression = runtimeOf(parsedAs(new IrisExpression(), compiled)); AtomicReference first = new AtomicReference<>(); doAnswer(invocation -> { double[] arguments = (double[]) invocation.getRawArguments()[1]; @@ -51,21 +53,16 @@ public class IrisExpressionScratchTest { } @Test - public void recursiveVariableEvaluationKeepsOuterArgumentsBeyondTheRetainedDepth() { - AtomicReference expression = new AtomicReference<>(); - IrisExpressionLoad recursive = new IrisExpressionLoad() { - @Override - public double getValue(RNG rng, IrisData data, double x, double z) { - return x <= 0D ? 7D : expression.get().evaluate(rng, x - 1D, z); - } - }.setName("prior"); - expression.set(new IrisExpression().setExpression("prior + 17 * x + 31 * y + z") - .setVariables(new KList<>(recursive))); + public void recursiveEvaluationWithVariablesKeepsOuterArgumentsBeyondTheRetainedDepth() { + AtomicReference expression = new AtomicReference<>(); + IrisExpression config = recursive(new IrisExpression().setExpression("prior(x, y) + value + 17 * x + 31 * y + z") + .setVariables(new KList<>(new IrisExpressionLoad().setName("value").setStaticValue(-1D))), expression); + expression.set(runtimeOf(config)); RNG rng = new RNG(78264193L); RNG control = new RNG(78264193L); double expected = 7D; for (int x = 0; x <= 31; x++) { - expected = expected + 17D * x + 31D * 3.75D - 1D; + expected = expected + 17D * x + 31D * 3.75D - 2D; } assertEquals(expected, expression.get().evaluate(rng, 31D, 3.75D), 0D); @@ -75,22 +72,9 @@ public class IrisExpressionScratchTest { @Test public void recursiveFunctionEvaluationDoesNotOverwriteTheOuterCoordinates() { - AtomicReference expression = new AtomicReference<>(); - IrisExpressionFunction recursive = new IrisExpressionFunction() { - @Override - public boolean isValid() { - return true; - } - - @Override - public double eval(Context context, double... coordinates) { - RNG rng = ((FunctionContext) context).rng(); - return coordinates[0] <= 0D ? 7D - : expression.get().evaluate(rng, coordinates[0] - 1D, coordinates[1]); - } - }.setName("prior"); - expression.set(new IrisExpression().setExpression("prior(x, y) + 17 * x + 31 * y + z") - .setFunctions(new KList<>(recursive))); + AtomicReference expression = new AtomicReference<>(); + expression.set(runtimeOf(recursive(new IrisExpression().setExpression("prior(x, y) + 17 * x + 31 * y + z"), + expression))); double expected = 7D; for (int x = 0; x <= 31; x++) { expected = expected + 17D * x + 31D * 3.75D - 1D; @@ -102,9 +86,8 @@ public class IrisExpressionScratchTest { @Test public void failedEvaluationUnwindsTheRetainedFrame() { - IrisExpression expression = new IrisExpression(); Expression compiled = mock(Expression.class); - expression.getExpressionCache().aquire(() -> compiled); + ExpressionRuntime expression = runtimeOf(parsedAs(new IrisExpression(), compiled)); AtomicBoolean fail = new AtomicBoolean(true); AtomicReference failedArguments = new AtomicReference<>(); doAnswer(invocation -> { @@ -124,14 +107,12 @@ public class IrisExpressionScratchTest { @Test public void largeArgumentListsRemainSupportedWithoutRetainingTheirArrays() { - IrisExpression expression = new IrisExpression(); KList variables = new KList<>(); for (int i = 0; i < 300; i++) { variables.add(new IrisExpressionLoad().setName("value" + i).setStaticValue(i)); } - expression.setVariables(variables); Expression compiled = mock(Expression.class); - expression.getExpressionCache().aquire(() -> compiled); + ExpressionRuntime expression = runtimeOf(parsedAs(new IrisExpression().setVariables(variables), compiled)); AtomicReference first = new AtomicReference<>(); doAnswer(invocation -> { double[] arguments = (double[]) invocation.getRawArguments()[1]; @@ -152,7 +133,7 @@ public class IrisExpressionScratchTest { @Test(timeout = 15000) public void sharedExpressionKeepsExactSamplesAcrossThreadsAndDimensions() throws Exception { - IrisExpression expression = new IrisExpression().setExpression("sin(x) + cos(y) + z / 7"); + ExpressionRuntime expression = runtimeOf(new IrisExpression().setExpression("sin(x) + cos(y) + z / 7")); RNG control = new RNG(17L); long[] expected = new long[128]; for (int i = 0; i < expected.length; i++) { @@ -182,4 +163,54 @@ public class IrisExpressionScratchTest { executor.awaitTermination(5, TimeUnit.SECONDS); } } + + private static ExpressionRuntime runtimeOf(IrisExpression expression) { + return PackRuntime.standalone(null).expression(expression); + } + + private static IrisExpression parsedAs(IrisExpression template, Expression compiled) { + return new IrisExpression() { + @Override + public Expression parse(Function functionRuntime) { + return compiled; + } + }.setVariables(template.getVariables()); + } + + private static IrisExpression recursive(IrisExpression template, AtomicReference expression) { + IrisExpression config = new IrisExpression() { + @Override + public Expression parse(Function functionRuntime) { + return super.parse(function -> new PriorFunction(expression)); + } + }; + config.setExpression(template.getExpression()); + config.setVariables(template.getVariables()); + config.setFunctions(new KList<>(new IrisExpressionFunction().setName("prior") + .setStyleValue(new IrisGeneratorStyle()))); + return config; + } + + private record PriorFunction(AtomicReference expression) implements DynamicFunction { + @Override + public int getArgNumber() { + return 2; + } + + @Override + public Statefulness statefulness() { + return Statefulness.STATEFUL; + } + + @Override + public double eval(double... coordinates) { + return 0D; + } + + @Override + public double eval(Context context, double... coordinates) { + RNG rng = ((ExpressionRuntime.FunctionContext) context).rng(); + return coordinates[0] <= 0D ? 7D : expression.get().evaluate(rng, coordinates[0] - 1D, coordinates[1]); + } + } } diff --git a/core/src/test/java/art/arcane/iris/generation/noise/IrisExpressionSeedCohesionTest.java b/core/src/test/java/art/arcane/iris/generation/noise/IrisExpressionSeedCohesionTest.java index 647b1090b..64660e2d1 100644 --- a/core/src/test/java/art/arcane/iris/generation/noise/IrisExpressionSeedCohesionTest.java +++ b/core/src/test/java/art/arcane/iris/generation/noise/IrisExpressionSeedCohesionTest.java @@ -3,6 +3,7 @@ package art.arcane.iris.generation.noise; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.IrisComplex; import art.arcane.iris.generation.runtime.IrisEngineStreamType; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.pack.loading.IrisData; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; @@ -15,7 +16,6 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; @@ -26,9 +26,9 @@ public class IrisExpressionSeedCohesionTest { @Test public void expressionStreamsSeparateSeedsAndInitializationOrder() { IrisData data = mock(IrisData.class); - IrisExpression expression = expression(data); - double first = expression(data).evaluate(new RNG(17L), 23.5D, -94.75D); - double second = expression(data).evaluate(new RNG(53L), 23.5D, -94.75D); + ExpressionRuntime expression = PackRuntime.standalone(data).expression(expression(data)); + double first = PackRuntime.standalone(data).expression(expression(data)).evaluate(new RNG(17L), 23.5D, -94.75D); + double second = PackRuntime.standalone(data).expression(expression(data)).evaluate(new RNG(53L), 23.5D, -94.75D); ProceduralStream secondStream = expression.stream(new RNG(53L)); ProceduralStream firstStream = expression.stream(new RNG(17L)); assertEquals(second, secondStream.get(23.5D, -94.75D), 0D); @@ -37,41 +37,39 @@ public class IrisExpressionSeedCohesionTest { } @Test - public void expressionFunctionTracksEngineIdentity() { - Engine firstEngine = engine(17D); - Engine secondEngine = engine(53D); - AtomicReference active = new AtomicReference<>(firstEngine); + public void expressionFunctionReadsItsOwnEngine() { IrisData data = mock(IrisData.class); - when(data.getEngine()).thenAnswer(ignored -> active.get()); - IrisExpressionFunction function = new IrisExpressionFunction() - .setName("height") - .setData(data) - .setEngineStreamValue(IrisEngineStreamType.HEIGHT); - IrisExpressionFunction.FunctionContext context = new IrisExpressionFunction.FunctionContext(new RNG(91L)); - assertEquals(17D, function.eval(context, 4D, -8D), 0D); - active.set(secondEngine); - assertEquals(53D, function.eval(context, 4D, -8D), 0D); - active.set(firstEngine); - assertEquals(17D, function.eval(context, 4D, -8D), 0D); + IrisExpression expression = new IrisExpression() + .setExpression("height(x, z)") + .setFunctions(new KList<>(new IrisExpressionFunction() + .setName("height") + .setEngineStreamValue(IrisEngineStreamType.HEIGHT))); + ExpressionRuntime first = PackRuntime.forEngine(engine(17D), data).expression(expression); + ExpressionRuntime second = PackRuntime.forEngine(engine(53D), data).expression(expression); + RNG rng = new RNG(91L); + + assertEquals(17D, first.evaluate(rng, 4D, -8D), 0D); + assertEquals(53D, second.evaluate(rng, 4D, -8D), 0D); + assertEquals(17D, first.evaluate(rng, 4D, -8D), 0D); } @Test(timeout = 15000) public void concurrentFunctionInitializationAndEvictionRetainSeedSamples() throws Exception { IrisData data = mock(IrisData.class); - IrisExpressionFunction shared = function(data); + IrisExpression config = new IrisExpression().setExpression("field(x, z)").setFunctions(new KList<>(function())); + ExpressionRuntime shared = PackRuntime.standalone(data).expression(config); ExecutorService workers = Executors.newFixedThreadPool(4); try { List> results = new ArrayList<>(32); double[] expected = new double[32]; for (int index = 0; index < 32; index++) { long seed = index; - expected[index] = function(data).eval(new IrisExpressionFunction.FunctionContext(new RNG(seed)), 23.5D, -94.75D); - results.add(workers.submit(() -> shared.eval( - new IrisExpressionFunction.FunctionContext(new RNG(seed)), 23.5D, -94.75D))); + expected[index] = PackRuntime.standalone(data).expression(config).evaluate(new RNG(seed), 23.5D, -94.75D); + results.add(workers.submit(() -> shared.evaluate(new RNG(seed), 23.5D, -94.75D))); } for (int index = 0; index < results.size(); index++) { assertEquals(expected[index], results.get(index).get(5L, TimeUnit.SECONDS), 0D); - assertEquals(expected[index], shared.eval(new IrisExpressionFunction.FunctionContext(new RNG(index)), 23.5D, -94.75D), 0D); + assertEquals(expected[index], shared.evaluate(new RNG(index), 23.5D, -94.75D), 0D); } } finally { workers.shutdownNow(); @@ -81,14 +79,14 @@ public class IrisExpressionSeedCohesionTest { private static IrisExpression expression(IrisData data) { IrisExpression expression = new IrisExpression() .setExpression("field(x, z) + value") - .setFunctions(new KList<>(function(data))) + .setFunctions(new KList<>(function())) .setVariables(new KList<>(new IrisExpressionLoad().setName("value").setStyleValue(NoiseStyle.PERLIN.style()))); expression.setLoader(data); return expression; } - private static IrisExpressionFunction function(IrisData data) { - return new IrisExpressionFunction().setName("field").setStyleValue(NoiseStyle.SIMPLEX.style()).setData(data); + private static IrisExpressionFunction function() { + return new IrisExpressionFunction().setName("field").setStyleValue(NoiseStyle.SIMPLEX.style()); } private static Engine engine(double height) { diff --git a/core/src/test/java/art/arcane/iris/generation/noise/IrisGeneratorBatchTest.java b/core/src/test/java/art/arcane/iris/generation/noise/IrisGeneratorBatchTest.java index 144f8da56..f2cf01ebd 100644 --- a/core/src/test/java/art/arcane/iris/generation/noise/IrisGeneratorBatchTest.java +++ b/core/src/test/java/art/arcane/iris/generation/noise/IrisGeneratorBatchTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.noise; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.volmlib.util.collection.KList; import org.junit.Test; @@ -8,13 +9,15 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; public class IrisGeneratorBatchTest { + private final PackRuntime runtime = PackRuntime.standalone(null); + private static final double[] XS = {-0D, 0D, -12D, -5.75D, 18D, 18D, 8191.25D, -29999999.5D, 2147483647D}; private static final double[] ZS = {0D, -0D, 6D, 2.5D, -6D, -6D, -4096.75D, 29999998D, -2147483648D}; @@ -31,10 +34,10 @@ public class IrisGeneratorBatchTest { assertTrue(batch.supportsBatch()); double[] sampled = new double[XS.length]; for (long seed : seeds) { - batch.compileProgram(seed).heights(new TerrainBatchScratch(), XS, ZS, sampled.length, sampled); + batch.compileProgram(runtime, seed).heights(new TerrainBatchScratch(), XS, ZS, sampled.length, sampled); for (int index = 0; index < sampled.length; index++) { assertEquals(style + " detail=" + detail + " seed=" + seed + " index=" + index, - Double.doubleToRawLongBits(scalar.getHeight(XS[index], ZS[index], seed)), + Double.doubleToRawLongBits(scalar.getHeight(runtime, XS[index], ZS[index], seed)), Double.doubleToRawLongBits(sampled[index])); } } @@ -51,9 +54,9 @@ public class IrisGeneratorBatchTest { IrisGenerator batch = generator(style, detail, false).setCliffHeightMax(0D).setCellFractureHeight(0D); double[] values = new double[XS.length]; for (long seed : new long[]{-1337L, Long.MAX_VALUE - 37L}) { - batch.compileProgram(seed).heights(new TerrainBatchScratch(), XS, ZS, XS.length, values); + batch.compileProgram(runtime, seed).heights(new TerrainBatchScratch(), XS, ZS, XS.length, values); for (int index = 0; index < XS.length; index++) { - assertEquals(Double.doubleToRawLongBits(scalar.getHeight(XS[index], ZS[index], seed)), + assertEquals(Double.doubleToRawLongBits(scalar.getHeight(runtime, XS[index], ZS[index], seed)), Double.doubleToRawLongBits(values[index])); } } @@ -66,27 +69,27 @@ public class IrisGeneratorBatchTest { IrisNoiseGenerator layer = spy(new IrisNoiseGenerator().setStyle(NoiseStyle.SIMPLEX.style())); IrisGenerator generator = new IrisGenerator().setComposite(new KList<>(layer)); double[] sampled = new double[XS.length]; - GeneratorProgram program = generator.compileProgram(99L); - verify(layer, times(1)).getGenerator(anyLong(), isNull(), isNull()); + GeneratorProgram program = generator.compileProgram(runtime, 99L); + verify(layer, times(1)).getGenerator(anyLong(), same(runtime)); clearInvocations(layer); program.heights(new TerrainBatchScratch(), XS, ZS, XS.length, sampled); - verify(layer, times(0)).getGenerator(anyLong(), isNull(), isNull()); + verify(layer, times(0)).getGenerator(anyLong(), same(runtime)); for (int index = 0; index < XS.length; index++) { - generator.getHeight(XS[index], ZS[index], 99L); + generator.getHeight(runtime, XS[index], ZS[index], 99L); } - verify(layer, times(XS.length)).getGenerator(anyLong(), isNull(), isNull()); + verify(layer, times(XS.length)).getGenerator(anyLong(), same(runtime)); } @Test public void customGeneratorsCannotCompile() { IrisGenerator generator = new IrisGenerator() { @Override - public double getHeight(double x, double z, long seed) { + public double getHeight(PackRuntime runtime, double x, double z, long seed) { return x; } }; assertFalse(generator.supportsBatch()); - assertThrows(IllegalStateException.class, () -> generator.compileProgram(0L)); + assertThrows(IllegalStateException.class, () -> generator.compileProgram(runtime, 0L)); } @Test diff --git a/core/src/test/java/art/arcane/iris/generation/noise/IrisGeneratorStyleCacheIsolationTest.java b/core/src/test/java/art/arcane/iris/generation/noise/IrisGeneratorStyleCacheIsolationTest.java index 346cc9196..213b6d19c 100644 --- a/core/src/test/java/art/arcane/iris/generation/noise/IrisGeneratorStyleCacheIsolationTest.java +++ b/core/src/test/java/art/arcane/iris/generation/noise/IrisGeneratorStyleCacheIsolationTest.java @@ -1,14 +1,13 @@ package art.arcane.iris.generation.noise; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.pack.loading.IrisData; -import art.arcane.iris.generation.runtime.Engine; import art.arcane.volmlib.util.noise.CNG; import art.arcane.volmlib.util.math.RNG; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; -import java.util.concurrent.atomic.AtomicReference; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; @@ -32,39 +31,34 @@ public class IrisGeneratorStyleCacheIsolationTest { } @Test - public void cacheSeparatesSeedsAndEngineIdentity() throws Exception { - Engine firstEngine = mock(Engine.class); - Engine secondEngine = mock(Engine.class); - AtomicReference activeEngine = new AtomicReference<>(firstEngine); + public void runtimeSeparatesSeedsAndOwners() throws Exception { IrisData data = mock(IrisData.class); - when(data.getEngine()).thenAnswer(ignored -> activeEngine.get()); when(data.getDataFolder()).thenReturn(temporaryFolder.newFolder("pack")); + PackRuntime owner = PackRuntime.standalone(data); + PackRuntime otherOwner = PackRuntime.standalone(data); IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.SIMPLEX); - CNG first = style.create(new RNG(41L), data); - CNG firstAgain = style.create(new RNG(41L), data); - CNG differentSeed = style.create(new RNG(42L), data); - activeEngine.set(secondEngine); - CNG differentEngine = style.create(new RNG(41L), data); + CNG first = style.create(new RNG(41L), owner); + CNG firstAgain = style.create(new RNG(41L), owner); + CNG differentSeed = style.create(new RNG(42L), owner); + CNG differentOwner = style.create(new RNG(41L), otherOwner); assertSame(first, firstAgain); assertNotSame(first, differentSeed); - assertNotSame(first, differentEngine); + assertNotSame(first, differentOwner); assertNotEquals(first.noise(12D, -7D), differentSeed.noise(12D, -7D), 0D); } @Test - public void cacheEvictsOldEngineSeedEntries() { - IrisData data = mock(IrisData.class); - Engine engine = mock(Engine.class); - when(data.getEngine()).thenReturn(engine); + public void runtimeEvictsOldSeedEntries() { + PackRuntime owner = PackRuntime.standalone(mock(IrisData.class)); IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.SIMPLEX); - CNG first = style.create(new RNG(0L), data); + CNG first = style.create(new RNG(0L), owner); for (long seed = 1L; seed <= 8L; seed++) { - style.create(new RNG(seed), data); + style.create(new RNG(seed), owner); } - assertNotSame(first, style.create(new RNG(0L), data)); + assertNotSame(first, style.create(new RNG(0L), owner)); } } diff --git a/core/src/test/java/art/arcane/iris/generation/noise/IrisGeneratorStyleOverrideTest.java b/core/src/test/java/art/arcane/iris/generation/noise/IrisGeneratorStyleOverrideTest.java index ffecaa1a6..cdbc76e39 100644 --- a/core/src/test/java/art/arcane/iris/generation/noise/IrisGeneratorStyleOverrideTest.java +++ b/core/src/test/java/art/arcane/iris/generation/noise/IrisGeneratorStyleOverrideTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.noise; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.image.IrisImage; import art.arcane.iris.generation.image.IrisImageMap; import art.arcane.iris.generation.image.IrisImageMapOutOfBounds; @@ -41,13 +42,14 @@ public class IrisGeneratorStyleOverrideTest { IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.FLAT).setExpression("height"); IrisStyledRange range = new IrisStyledRange().setMin(2D).setMax(14D).setStyle(style); RNG rng = new RNG(78264193L); - double first = style.create(rng, data).fitDouble(2D, 14D, 0D, 0D); - double second = style.create(rng, data).fitDouble(2D, 14D, 1D, 0D); + PackRuntime runtime = PackRuntime.standalone(data); + double first = style.create(rng, runtime).fitDouble(2D, 14D, 0D, 0D); + double second = style.create(rng, runtime).fitDouble(2D, 14D, 1D, 0D); assertNotEquals(8D, first, 0D); assertNotEquals(first, second, 0D); - assertEquals(first, range.get(rng, 0D, 0D, data), 0D); - assertEquals(second, range.get(rng, 1D, 0D, data), 0D); + assertEquals(first, range.get(rng, 0D, 0D, runtime), 0D); + assertEquals(second, range.get(rng, 1D, 0D, runtime), 0D); } @Test @@ -66,7 +68,8 @@ public class IrisGeneratorStyleOverrideTest { IrisStyledRange range = new IrisStyledRange().setMin(2D).setMax(14D).setStyle(style); RNG rng = new RNG(78264193L); - assertEquals(2D, range.get(rng, 0D, 0D, data), 0D); - assertEquals(14D, range.get(rng, 1D, 0D, data), 0D); + PackRuntime runtime = PackRuntime.standalone(data); + assertEquals(2D, range.get(rng, 0D, 0D, runtime), 0D); + assertEquals(14D, range.get(rng, 1D, 0D, runtime), 0D); } } diff --git a/core/src/test/java/art/arcane/iris/generation/noise/IrisGeneratorSurfaceDetailTest.java b/core/src/test/java/art/arcane/iris/generation/noise/IrisGeneratorSurfaceDetailTest.java index 65f600876..d43f1c997 100644 --- a/core/src/test/java/art/arcane/iris/generation/noise/IrisGeneratorSurfaceDetailTest.java +++ b/core/src/test/java/art/arcane/iris/generation/noise/IrisGeneratorSurfaceDetailTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.noise; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.pack.loading.IrisData; import art.arcane.volmlib.util.collection.KList; @@ -20,6 +21,8 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class IrisGeneratorSurfaceDetailTest { + private final PackRuntime runtime = PackRuntime.standalone(null); + @Test public void defaultUsesTheOriginalSampleOnce() { AtomicInteger samples = new AtomicInteger(); @@ -28,7 +31,7 @@ public class IrisGeneratorSurfaceDetailTest { return x * 0.01D + z * 0.02D; }); - assertEquals(0.07D, generator.getHeight(1, 3, 27L), 1e-12D); + assertEquals(0.07D, generator.getHeight(runtime, 1, 3, 27L), 1e-12D); assertEquals(1, samples.get()); } @@ -41,7 +44,7 @@ public class IrisGeneratorSurfaceDetailTest { for (int z = -12; z <= 12; z++) { for (int x = -12; x <= 12; x++) { double expected = x % 6 == 0 && z % 6 == 0 ? 0.2D : 0.5D; - assertEquals(expected, generator.getHeight(x, z, 27L), 1e-12D); + assertEquals(expected, generator.getHeight(runtime, x, z, 27L), 1e-12D); } } } @@ -54,7 +57,7 @@ public class IrisGeneratorSurfaceDetailTest { for (double z = -4.25D; z < 4D; z += 0.5D) { for (double x = -4.75D; x < 4D; x += 0.5D) { assertEquals(0.5D + x * 0.01D + z * 0.02D, - generator.getHeight(x, z, 27L), 1e-12D); + generator.getHeight(runtime, x, z, 27L), 1e-12D); } } } @@ -70,7 +73,7 @@ public class IrisGeneratorSurfaceDetailTest { for (int z = 0; z < 16; z++) { for (int x = 0; x < 16; x++) { - assertEquals(0.5D, generator.getHeight(x, z, 27L), 0D); + assertEquals(0.5D, generator.getHeight(runtime, x, z, 27L), 0D); } } @@ -89,7 +92,7 @@ public class IrisGeneratorSurfaceDetailTest { for (int z = -16; z < 16; z += 4) { for (int x = -16; x < 16; x += 4) { - generator.getHeight(x, z, 27L); + generator.getHeight(runtime, x, z, 27L); } } @@ -108,10 +111,9 @@ public class IrisGeneratorSurfaceDetailTest { }; for (double[] point : points) { - cold.rescale(1D); - long expected = Double.doubleToRawLongBits(cold.getHeight(point[0], point[1], 27L)); + long expected = Double.doubleToRawLongBits(cold.getHeight(PackRuntime.standalone(null), point[0], point[1], 27L)); for (int repeat = 0; repeat < 4; repeat++) { - assertEquals(expected, Double.doubleToRawLongBits(warm.getHeight(point[0], point[1], 27L))); + assertEquals(expected, Double.doubleToRawLongBits(warm.getHeight(runtime, point[0], point[1], 27L))); } } } @@ -124,16 +126,16 @@ public class IrisGeneratorSurfaceDetailTest { return seed * 0.000001D; }).setSurfaceDetail(0.5D); - double first = generator.getHeight(0, 0, 27L); - assertEquals(Double.doubleToRawLongBits(first), Double.doubleToRawLongBits(generator.getHeight(0, 0, 27L))); + double first = generator.getHeight(runtime, 0, 0, 27L); + assertEquals(Double.doubleToRawLongBits(first), Double.doubleToRawLongBits(generator.getHeight(runtime, 0, 0, 27L))); assertEquals(1, samples.get()); - double second = generator.getHeight(0, 0, 28L); + double second = generator.getHeight(runtime, 0, 0, 28L); assertEquals(0.000001D, second - first, 1e-12D); - assertEquals(Double.doubleToRawLongBits(second), Double.doubleToRawLongBits(generator.getHeight(0, 0, 28L))); + assertEquals(Double.doubleToRawLongBits(second), Double.doubleToRawLongBits(generator.getHeight(runtime, 0, 0, 28L))); assertEquals(2, samples.get()); - assertEquals(Double.doubleToRawLongBits(first), Double.doubleToRawLongBits(generator.getHeight(0, 0, 27L))); + assertEquals(Double.doubleToRawLongBits(first), Double.doubleToRawLongBits(generator.getHeight(runtime, 0, 0, 27L))); assertEquals(3, samples.get()); } @@ -147,14 +149,14 @@ public class IrisGeneratorSurfaceDetailTest { return x * 0.00001D; }).setSurfaceDetail(0.5D); - assertEquals(0L, Double.doubleToRawLongBits(generator.getHeight(0, 0, 27L))); - assertEquals(0L, Double.doubleToRawLongBits(generator.getHeight(0, 0, 27L))); + assertEquals(0L, Double.doubleToRawLongBits(generator.getHeight(runtime, 0, 0, 27L))); + assertEquals(0L, Double.doubleToRawLongBits(generator.getHeight(runtime, 0, 0, 27L))); assertEquals(1, originSamples.get()); assertEquals(Double.doubleToRawLongBits(71754D * 0.00001D), - Double.doubleToRawLongBits(generator.getHeight(71754, 0, 27L))); - assertEquals(0L, Double.doubleToRawLongBits(generator.getHeight(0, 0, 27L))); + Double.doubleToRawLongBits(generator.getHeight(runtime, 71754, 0, 27L))); + assertEquals(0L, Double.doubleToRawLongBits(generator.getHeight(runtime, 0, 0, 27L))); assertEquals(2, originSamples.get()); - assertEquals(0L, Double.doubleToRawLongBits(generator.getHeight(0, 0, 27L))); + assertEquals(0L, Double.doubleToRawLongBits(generator.getHeight(runtime, 0, 0, 27L))); assertEquals(2, originSamples.get()); } @@ -168,7 +170,7 @@ public class IrisGeneratorSurfaceDetailTest { long[][] expected = new long[xs.length][seeds.length]; for (int coordinate = 0; coordinate < xs.length; coordinate++) { for (int seed = 0; seed < seeds.length; seed++) { - expected[coordinate][seed] = Double.doubleToRawLongBits(reference.getHeight(xs[coordinate], 0D, seeds[seed])); + expected[coordinate][seed] = Double.doubleToRawLongBits(reference.getHeight(runtime, xs[coordinate], 0D, seeds[seed])); } } ForkJoinPool pool = new ForkJoinPool(4); @@ -181,7 +183,7 @@ public class IrisGeneratorSurfaceDetailTest { int coordinate = (sample + offset) & 1; int seed = (sample / 2 + offset) & 1; assertEquals(expected[coordinate][seed], - Double.doubleToRawLongBits(generator.getHeight(xs[coordinate], 0D, seeds[seed]))); + Double.doubleToRawLongBits(generator.getHeight(runtime, xs[coordinate], 0D, seeds[seed]))); } })); } @@ -198,67 +200,32 @@ public class IrisGeneratorSurfaceDetailTest { public void cachedLatticeHeightsRemainIsolatedBySeed() { IrisGenerator generator = generator((seed, x, z) -> seed * 0.000001D); generator.setSurfaceDetail(0.5D); - double first = generator.getHeight(1, 1, 27L); - double second = generator.getHeight(1, 1, 28L); + double first = generator.getHeight(runtime, 1, 1, 27L); + double second = generator.getHeight(runtime, 1, 1, 28L); assertEquals(0.000001D, second - first, 1e-12D); - assertEquals(first, generator.getHeight(1, 1, 27L), 0D); + assertEquals(first, generator.getHeight(runtime, 1, 1, 27L), 0D); } @Test - public void cachedLatticeHeightsRemainIsolatedByEngine() { - Engine firstEngine = mock(Engine.class); - Engine secondEngine = mock(Engine.class); - AtomicReference activeEngine = new AtomicReference<>(firstEngine); - IrisData data = mock(IrisData.class); - when(data.getEngine()).thenAnswer(ignored -> activeEngine.get()); - IrisGenerator generator = new IrisGenerator().setSurfaceDetail(0.5D).setComposite(new KList<>( - new ContextNoise(loader -> loader.getEngine() == firstEngine ? 0.2D : 0.8D))); - generator.setLoader(data); - - assertEquals(0.2D, generator.getHeight(0, 0, 27L), 1e-12D); - assertEquals(0.2D, generator.getHeight(1, 1, 27L), 1e-12D); - activeEngine.set(secondEngine); - assertEquals(0.8D, generator.getHeight(0, 0, 27L), 1e-12D); - assertEquals(0.8D, generator.getHeight(1, 1, 27L), 1e-12D); - activeEngine.set(firstEngine); - assertEquals(0.2D, generator.getHeight(1, 1, 27L), 1e-12D); - } - - @Test - public void cachedLatticeHeightsRemainIsolatedByLoader() { - Engine engine = mock(Engine.class); + public void cachedLatticeHeightsBelongToTheirRuntime() { IrisData firstData = mock(IrisData.class); IrisData secondData = mock(IrisData.class); - when(firstData.getEngine()).thenReturn(engine); - when(secondData.getEngine()).thenReturn(engine); + PackRuntime first = PackRuntime.standalone(firstData); + PackRuntime second = PackRuntime.standalone(secondData); IrisGenerator generator = new IrisGenerator().setSurfaceDetail(0.5D).setComposite(new KList<>( - new ContextNoise(loader -> loader == firstData ? 0.2D : 0.8D))); - generator.setLoader(firstData); + new ContextNoise(scope -> scope.data() == firstData ? 0.2D : 0.8D))); - assertEquals(0.2D, generator.getHeight(0, 0, 27L), 1e-12D); - assertEquals(0.2D, generator.getHeight(1, 1, 27L), 1e-12D); - generator.setLoader(secondData); - assertEquals(0.8D, generator.getHeight(0, 0, 27L), 1e-12D); - assertEquals(0.8D, generator.getHeight(1, 1, 27L), 1e-12D); - generator.setLoader(firstData); - assertEquals(0.2D, generator.getHeight(1, 1, 27L), 1e-12D); - } - - @Test - public void rescalingClearsCachedLatticeHeights() { - IrisGenerator generator = generator((seed, x, z) -> x * 0.01D + z * 0.02D); - generator.setSurfaceDetail(0.5D); - assertEquals(0.06D, generator.getHeight(2, 2, 27L), 1e-12D); - - generator.rescale(2D); - - assertEquals(0.12D, generator.getHeight(2, 2, 27L), 1e-12D); + assertEquals(0.2D, generator.getHeight(first, 0, 0, 27L), 1e-12D); + assertEquals(0.2D, generator.getHeight(first, 1, 1, 27L), 1e-12D); + assertEquals(0.8D, generator.getHeight(second, 0, 0, 27L), 1e-12D); + assertEquals(0.8D, generator.getHeight(second, 1, 1, 27L), 1e-12D); + assertEquals(0.2D, generator.getHeight(first, 1, 1, 27L), 1e-12D); } @Test(expected = IllegalArgumentException.class) public void rejectsNonfiniteDetail() { - generator((seed, x, z) -> 0D).setSurfaceDetail(Double.NaN).getHeight(1, 1, 27L); + generator((seed, x, z) -> 0D).setSurfaceDetail(Double.NaN).getHeight(runtime, 1, 1, 27L); } private static IrisGenerator generator(Sampler sampler) { @@ -277,21 +244,21 @@ public class IrisGeneratorSurfaceDetailTest { } @Override - public double getNoise(long superSeed, double x, double z, IrisData data, Engine engine) { + public double getNoise(long superSeed, double x, double z, PackRuntime runtime) { return sampler.sample(superSeed, x, z); } } private static final class ContextNoise extends IrisNoiseGenerator { - private final ToDoubleFunction sampler; + private final ToDoubleFunction sampler; - private ContextNoise(ToDoubleFunction sampler) { + private ContextNoise(ToDoubleFunction sampler) { this.sampler = sampler; } @Override - public double getNoise(long superSeed, double x, double z, IrisData data, Engine engine) { - return sampler.applyAsDouble(data); + public double getNoise(long superSeed, double x, double z, PackRuntime runtime) { + return sampler.applyAsDouble(runtime); } } } diff --git a/core/src/test/java/art/arcane/iris/generation/noise/IrisNoiseGeneratorCacheTest.java b/core/src/test/java/art/arcane/iris/generation/noise/IrisNoiseGeneratorCacheTest.java index 8b9879462..ec3d522d9 100644 --- a/core/src/test/java/art/arcane/iris/generation/noise/IrisNoiseGeneratorCacheTest.java +++ b/core/src/test/java/art/arcane/iris/generation/noise/IrisNoiseGeneratorCacheTest.java @@ -1,9 +1,9 @@ package art.arcane.iris.generation.noise; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.generation.runtime.Engine; import art.arcane.volmlib.util.noise.CNG; -import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; import org.junit.Test; @@ -24,7 +24,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.times; -import static org.mockito.Mockito.never; public final class IrisNoiseGeneratorCacheTest { private static final long GENERATOR_SALT = 33_955_677L; @@ -35,17 +34,17 @@ public final class IrisNoiseGeneratorCacheTest { public void callerSeedsDoNotShareAFirstWinnerGenerator() { GeneratorFixture fixture = new GeneratorFixture(); - assertSame(fixture.firstGenerator, fixture.generator.getGenerator(11L, fixture.data, fixture.engine)); - assertSame(fixture.secondGenerator, fixture.generator.getGenerator(29L, fixture.data, fixture.engine)); - assertSame(fixture.firstGenerator, fixture.generator.getGenerator(11L, fixture.data, fixture.engine)); + assertSame(fixture.firstGenerator, fixture.generator.getGenerator(11L, fixture.runtime)); + assertSame(fixture.secondGenerator, fixture.generator.getGenerator(29L, fixture.runtime)); + assertSame(fixture.firstGenerator, fixture.generator.getGenerator(11L, fixture.runtime)); } @Test public void reverseInitializationOrderKeepsSeedAssignments() { GeneratorFixture fixture = new GeneratorFixture(); - assertSame(fixture.secondGenerator, fixture.generator.getGenerator(29L, fixture.data, fixture.engine)); - assertSame(fixture.firstGenerator, fixture.generator.getGenerator(11L, fixture.data, fixture.engine)); + assertSame(fixture.secondGenerator, fixture.generator.getGenerator(29L, fixture.runtime)); + assertSame(fixture.firstGenerator, fixture.generator.getGenerator(11L, fixture.runtime)); } @Test @@ -56,11 +55,11 @@ public final class IrisNoiseGeneratorCacheTest { try { Future first = executor.submit(() -> { assertTrue(start.await(5L, TimeUnit.SECONDS)); - return fixture.generator.getGenerator(11L, fixture.data, fixture.engine); + return fixture.generator.getGenerator(11L, fixture.runtime); }); Future second = executor.submit(() -> { assertTrue(start.await(5L, TimeUnit.SECONDS)); - return fixture.generator.getGenerator(29L, fixture.data, fixture.engine); + return fixture.generator.getGenerator(29L, fixture.runtime); }); start.countDown(); @@ -72,55 +71,34 @@ public final class IrisNoiseGeneratorCacheTest { } @Test - public void heightResolvesEngineOnceAcrossFracturesAndSurfaceCorners() { + public void eachRuntimeBuildsItsOwnGeneratorAndKeepsIt() { IrisData data = mock(IrisData.class); - Engine engine = mock(Engine.class); - when(data.getEngine()).thenReturn(engine); - IrisNoiseGenerator child = new IrisNoiseGenerator().setStyle(NoiseStyle.SIMPLEX.style()); - IrisNoiseGenerator layer = new IrisNoiseGenerator().setStyle(NoiseStyle.SIMPLEX.style()) - .setFracture(new KList<>(child)); - IrisGenerator generator = new IrisGenerator().setComposite(new KList<>(layer, child)) - .setSurfaceDetail(0.5D); - generator.setLoader(data); - - double first = generator.getHeight(13D, -21D, 71L); - verify(data, times(1)).getEngine(); - assertEquals(Double.doubleToRawLongBits(first), - Double.doubleToRawLongBits(generator.getHeight(13D, -21D, 71L))); - verify(data, times(2)).getEngine(); - } - - @Test - public void changedEngineUsesDistinctConstructionAndRestoresPreviousGenerator() { - IrisData data = mock(IrisData.class); - Engine firstEngine = mock(Engine.class); - Engine secondEngine = mock(Engine.class); + PackRuntime firstRuntime = PackRuntime.forEngine(mock(Engine.class), data); + PackRuntime secondRuntime = PackRuntime.forEngine(mock(Engine.class), data); IrisGeneratorStyle style = mock(IrisGeneratorStyle.class); CNG first = mock(CNG.class); CNG second = mock(CNG.class); IrisNoiseGenerator layer = new IrisNoiseGenerator().setStyle(style); - when(data.getEngine()).thenReturn(firstEngine, secondEngine, firstEngine); - when(style.createForLayer(any(RNG.class), same(data), eq(1), same(firstEngine))).thenReturn(first); - when(style.createForLayer(any(RNG.class), same(data), eq(1), same(secondEngine))).thenReturn(second); + when(style.createForLayer(any(RNG.class), same(firstRuntime), eq(1))).thenReturn(first); + when(style.createForLayer(any(RNG.class), same(secondRuntime), eq(1))).thenReturn(second); - assertSame(first, layer.getGenerator(11L, data, data.getEngine())); - assertSame(second, layer.getGenerator(11L, data, data.getEngine())); - assertSame(first, layer.getGenerator(11L, data, data.getEngine())); - verify(style, times(1)).createForLayer(any(RNG.class), same(data), eq(1), same(firstEngine)); - verify(style, times(1)).createForLayer(any(RNG.class), same(data), eq(1), same(secondEngine)); + assertSame(first, layer.getGenerator(11L, firstRuntime)); + assertSame(second, layer.getGenerator(11L, secondRuntime)); + assertSame(first, layer.getGenerator(11L, firstRuntime)); + verify(style, times(1)).createForLayer(any(RNG.class), same(firstRuntime), eq(1)); + verify(style, times(1)).createForLayer(any(RNG.class), same(secondRuntime), eq(1)); } @Test - public void disabledNoiseDoesNotResolveEngine() { - IrisData data = mock(IrisData.class); + public void disabledNoiseReturnsItsOffset() { IrisNoiseGenerator layer = new IrisNoiseGenerator(false).setOffsetY(0.37D); - assertEquals(0.37D, layer.getNoise(11L, 13D, -21D, data), 0D); - verify(data, never()).getEngine(); + assertEquals(0.37D, layer.getNoise(11L, 13D, -21D, PackRuntime.standalone(null)), 0D); } private static final class GeneratorFixture { private final IrisData data = mock(IrisData.class); private final Engine engine = mock(Engine.class); + private final PackRuntime runtime = PackRuntime.forEngine(engine, data); private final IrisGeneratorStyle style = mock(IrisGeneratorStyle.class); private final CNG firstGenerator = mock(CNG.class); private final CNG secondGenerator = mock(CNG.class); @@ -130,12 +108,11 @@ public final class IrisNoiseGeneratorCacheTest { .setOctaves(OCTAVES); private GeneratorFixture() { - when(data.getEngine()).thenReturn(engine); Map generators = Map.of( 11L + GENERATOR_SALT - CONFIGURED_SEED, firstGenerator, 29L + GENERATOR_SALT - CONFIGURED_SEED, secondGenerator ); - when(style.createForLayer(any(RNG.class), same(data), eq(OCTAVES), same(engine))).thenAnswer(invocation -> { + when(style.createForLayer(any(RNG.class), same(runtime), eq(OCTAVES))).thenAnswer(invocation -> { RNG rng = invocation.getArgument(0); return generators.get(rng.getSeed()); }); diff --git a/core/src/test/java/art/arcane/iris/generation/noise/IrisNoiseGeneratorFractureMirrorTest.java b/core/src/test/java/art/arcane/iris/generation/noise/IrisNoiseGeneratorFractureMirrorTest.java index 1f77d9f0e..41867f913 100644 --- a/core/src/test/java/art/arcane/iris/generation/noise/IrisNoiseGeneratorFractureMirrorTest.java +++ b/core/src/test/java/art/arcane/iris/generation/noise/IrisNoiseGeneratorFractureMirrorTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.noise; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.noise.NoiseGenerator; import org.junit.Test; @@ -7,6 +8,8 @@ import org.junit.Test; import static org.junit.Assert.assertTrue; public final class IrisNoiseGeneratorFractureMirrorTest { + private static final PackRuntime RUNTIME = PackRuntime.standalone(null); + private static final long SEED = 71L; private static final int GRID_SIZE = 40; private static final double GRID_STEP = 7.3D; @@ -31,7 +34,7 @@ public final class IrisNoiseGeneratorFractureMirrorTest { for (int j = i + 1; j < GRID_SIZE; j++) { double a = i * GRID_STEP; double b = j * GRID_STEP + 0.5D; - if (Math.abs(noise.getNoise(SEED, a, b, null) - noise.getNoise(SEED, b, a, null)) < MIRRORED) { + if (Math.abs(noise.getNoise(SEED, a, b, RUNTIME) - noise.getNoise(SEED, b, a, RUNTIME)) < MIRRORED) { mirroredSamples++; } } @@ -41,7 +44,7 @@ public final class IrisNoiseGeneratorFractureMirrorTest { private static IrisNoiseGenerator diagonalSymmetricRoot() { IrisNoiseGenerator root = new IrisNoiseGenerator().setStyle(NoiseStyle.SIMPLEX.style()).setSeed(5L); - root.getGenerator(SEED, null, null).setGenerator(new DiagonalSymmetricGenerator()); + root.getGenerator(SEED, RUNTIME).setGenerator(new DiagonalSymmetricGenerator()); return root; } diff --git a/core/src/test/java/art/arcane/iris/generation/noise/IrisNoiseGeneratorFractureTest.java b/core/src/test/java/art/arcane/iris/generation/noise/IrisNoiseGeneratorFractureTest.java index b1203c5b1..87bf94d93 100644 --- a/core/src/test/java/art/arcane/iris/generation/noise/IrisNoiseGeneratorFractureTest.java +++ b/core/src/test/java/art/arcane/iris/generation/noise/IrisNoiseGeneratorFractureTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.noise; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.pack.loading.IrisData; import art.arcane.volmlib.util.collection.KList; @@ -29,6 +30,8 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; public final class IrisNoiseGeneratorFractureTest { + private static final PackRuntime RUNTIME = PackRuntime.standalone(null); + @Test public void deepChainsMatchRecursiveSamplingBits() { Random coordinates = new Random(718311L); @@ -37,13 +40,13 @@ public final class IrisNoiseGeneratorFractureTest { for (int depth : new int[]{0, 1, 3, 4, 5, 8}) { IrisNoiseGenerator root = chain(depth, style).getFirst(); for (long seed : new long[]{0L, -4193L, Long.MIN_VALUE, Long.MAX_VALUE}) { - assertParity(root, seed, 0D, -0D, null, null); - assertParity(root, seed, -0D, 0D, null, null); - assertParity(root, seed, -30_000_000D, 29_999_999.75D, null, null); - assertParity(root, seed, Math.nextDown(-64D), Math.nextUp(64D), null, null); + assertParity(root, seed, 0D, -0D, RUNTIME); + assertParity(root, seed, -0D, 0D, RUNTIME); + assertParity(root, seed, -30_000_000D, 29_999_999.75D, RUNTIME); + assertParity(root, seed, Math.nextDown(-64D), Math.nextUp(64D), RUNTIME); for (int index = 0; index < 8; index++) { assertParity(root, seed, coordinates.nextDouble() * 4096D - 2048D, - coordinates.nextDouble() * 4096D - 2048D, null, null); + coordinates.nextDouble() * 4096D - 2048D, RUNTIME); } } } @@ -54,13 +57,13 @@ public final class IrisNoiseGeneratorFractureTest { public void fourFracturesReducePrimitiveSamplesFromThirtyOneToNine() { List chain = chain(4, NoiseStyle.SIMPLEX); List bases = spyBases(chain, 71L); - reference(chain.getFirst(), 71L, 13.25D, -21.75D, null, null); + reference(chain.getFirst(), 71L, 13.25D, -21.75D, RUNTIME); for (int index = 0; index < bases.size(); index++) { verify(bases.get(index), times(1 << index)).noise(anyDouble(), anyDouble()); clearInvocations(bases.get(index)); } - chain.getFirst().getNoise(71L, 13.25D, -21.75D, null); + chain.getFirst().getNoise(71L, 13.25D, -21.75D, RUNTIME); for (int index = 0; index < bases.size(); index++) { verify(bases.get(index), times(index == 0 ? 1 : 2)).noise(anyDouble(), anyDouble()); } @@ -70,7 +73,7 @@ public final class IrisNoiseGeneratorFractureTest { public void shallowChainsKeepTheirSamplingCounts() { List chain = chain(3, NoiseStyle.SIMPLEX); List bases = spyBases(chain, 71L); - chain.getFirst().getNoise(71L, 13.25D, -21.75D, null); + chain.getFirst().getNoise(71L, 13.25D, -21.75D, RUNTIME); for (int index = 0; index < bases.size(); index++) { verify(bases.get(index), times(1 << index)).noise(anyDouble(), anyDouble()); } @@ -80,18 +83,18 @@ public final class IrisNoiseGeneratorFractureTest { public void changedParametersAndFracturesRemainVisible() { List chain = chain(5, NoiseStyle.IRIS); IrisNoiseGenerator root = chain.getFirst(); - assertParity(root, 19L, 31D, -79D, null, null); + assertParity(root, 19L, 31D, -79D, RUNTIME); chain.get(3).setOffsetX(-319D).setOffsetZ(17D).setOffsetY(-0.7D) .setSeed(Long.MAX_VALUE).setOpacity(0.35D).setZoom(17D); - assertParity(root, 19L, 31D, -79D, null, null); + assertParity(root, 19L, 31D, -79D, RUNTIME); chain.get(4).setEnabled(false); - assertParity(root, 19L, 31D, -79D, null, null); + assertParity(root, 19L, 31D, -79D, RUNTIME); chain.get(4).setEnabled(true); chain.get(2).getFracture().add(new IrisNoiseGenerator().setStyle(NoiseStyle.PERLIN.style())); - assertParity(root, 19L, 31D, -79D, null, null); + assertParity(root, 19L, 31D, -79D, RUNTIME); chain.get(2).getFracture().removeLast(); chain.getLast().getFracture().add(new IrisNoiseGenerator().setStyle(NoiseStyle.SIMPLEX.style())); - assertParity(root, 19L, 31D, -79D, null, null); + assertParity(root, 19L, 31D, -79D, RUNTIME); } @Test @@ -99,11 +102,11 @@ public final class IrisNoiseGeneratorFractureTest { List chain = chain(4, NoiseStyle.SIMPLEX); long leafSeed = childSeed(chain, 23L, chain.size() - 1); StatefulNoise stateful = new StatefulNoise(); - chain.getLast().getGenerator(leafSeed, null, null).setGenerator(stateful); - double expected = reference(chain.getFirst(), 23L, 17D, -31D, null, null); + chain.getLast().getGenerator(leafSeed, RUNTIME).setGenerator(stateful); + double expected = reference(chain.getFirst(), 23L, 17D, -31D, RUNTIME); assertEquals(16, stateful.samples); stateful.samples = 0; - double actual = chain.getFirst().getNoise(23L, 17D, -31D, null); + double actual = chain.getFirst().getNoise(23L, 17D, -31D, RUNTIME); assertBits(expected, actual); assertEquals(16, stateful.samples); } @@ -113,11 +116,11 @@ public final class IrisNoiseGeneratorFractureTest { List chain = chain(4, NoiseStyle.SIMPLEX); List bases = spyBases(chain, 71L); chain.getLast().getStyle().setExpression("custom"); - chain.getFirst().getNoise(71L, 13.25D, -21.75D, null); + chain.getFirst().getNoise(71L, 13.25D, -21.75D, RUNTIME); verify(bases.getLast(), times(16)).noise(anyDouble(), anyDouble()); chain.getLast().getStyle().setExpression(null).setImageMap("map"); clearInvocations(bases.getLast()); - chain.getFirst().getNoise(71L, 13.25D, -21.75D, null); + chain.getFirst().getNoise(71L, 13.25D, -21.75D, RUNTIME); verify(bases.getLast(), times(16)).noise(anyDouble(), anyDouble()); } @@ -127,7 +130,7 @@ public final class IrisNoiseGeneratorFractureTest { List bases = spyBases(chain, 71L); chain.getLast().setStyle(new IrisGeneratorStyle(NoiseStyle.SIMPLEX) { }); - chain.getFirst().getNoise(71L, 13.25D, -21.75D, null); + chain.getFirst().getNoise(71L, 13.25D, -21.75D, RUNTIME); verify(bases.getLast(), times(16)).noise(anyDouble(), anyDouble()); } @@ -138,9 +141,9 @@ public final class IrisNoiseGeneratorFractureTest { doThrow(new IllegalStateException("sample failed")).doCallRealMethod() .when(bases.getLast()).noise(anyDouble(), anyDouble()); assertThrows(IllegalStateException.class, - () -> chain.getFirst().getNoise(71L, 13.25D, -21.75D, null)); + () -> chain.getFirst().getNoise(71L, 13.25D, -21.75D, RUNTIME)); clearInvocations(bases.getLast()); - chain.getFirst().getNoise(71L, 13.25D, -21.75D, null); + chain.getFirst().getNoise(71L, 13.25D, -21.75D, RUNTIME); verify(bases.getLast(), times(2)).noise(anyDouble(), anyDouble()); } @@ -148,24 +151,24 @@ public final class IrisNoiseGeneratorFractureTest { public void threadsAndEngineIdentitiesRemainIndependent() throws Exception { IrisNoiseGenerator root = chain(5, NoiseStyle.IRIS).getFirst(); IrisData data = mock(IrisData.class); - Engine firstEngine = mock(Engine.class); - Engine secondEngine = mock(Engine.class); + PackRuntime firstEngine = PackRuntime.forEngine(mock(Engine.class), data); + PackRuntime secondEngine = PackRuntime.forEngine(mock(Engine.class), data); CountDownLatch start = new CountDownLatch(1); ExecutorService executor = Executors.newFixedThreadPool(2); try { - Future first = executor.submit(() -> sampleConcurrently(root, data, firstEngine, 47L, start)); - Future second = executor.submit(() -> sampleConcurrently(root, data, secondEngine, -131L, start)); + Future first = executor.submit(() -> sampleConcurrently(root, firstEngine, 47L, start)); + Future second = executor.submit(() -> sampleConcurrently(root, secondEngine, -131L, start)); start.countDown(); first.get(15L, TimeUnit.SECONDS); second.get(15L, TimeUnit.SECONDS); } finally { executor.shutdownNow(); } - assertParity(root, 47L, 17D, 19D, data, secondEngine); - assertParity(root, 47L, 17D, 19D, data, firstEngine); + assertParity(root, 47L, 17D, 19D, secondEngine); + assertParity(root, 47L, 17D, 19D, firstEngine); } - private static void sampleConcurrently(IrisNoiseGenerator root, IrisData data, Engine engine, + private static void sampleConcurrently(IrisNoiseGenerator root, PackRuntime RUNTIME, long seed, CountDownLatch start) { try { assertTrue(start.await(5L, TimeUnit.SECONDS)); @@ -174,7 +177,7 @@ public final class IrisNoiseGeneratorFractureTest { throw new AssertionError(failure); } for (int index = 0; index < 64; index++) { - assertParity(root, seed, index * 13.75D, -index * 2.25D, data, engine); + assertParity(root, seed, index * 13.75D, -index * 2.25D, RUNTIME); } } @@ -198,7 +201,7 @@ public final class IrisNoiseGeneratorFractureTest { private static List spyBases(List nodes, long superSeed) { List bases = new ArrayList<>(nodes.size()); for (IrisNoiseGenerator node : nodes) { - CNG generator = node.getGenerator(superSeed, null, null); + CNG generator = node.getGenerator(superSeed, RUNTIME); NoiseGenerator base = spy(generator.getGenerator()); generator.setGenerator(base); bases.add(base); @@ -215,8 +218,8 @@ public final class IrisNoiseGeneratorFractureTest { } private static void assertParity(IrisNoiseGenerator node, long seed, double x, double z, - IrisData data, Engine engine) { - assertBits(reference(node, seed, x, z, data, engine), node.getNoise(seed, x, z, data, engine)); + PackRuntime RUNTIME) { + assertBits(reference(node, seed, x, z, RUNTIME), node.getNoise(seed, x, z, RUNTIME)); } private static void assertBits(double expected, double actual) { @@ -224,12 +227,12 @@ public final class IrisNoiseGeneratorFractureTest { } private static double reference(IrisNoiseGenerator node, long superSeed, double xv, double zv, - IrisData data, Engine engine) { - return reference(node, superSeed, xv, zv, data, engine, IrisNoiseGenerator.X_AXIS); + PackRuntime RUNTIME) { + return reference(node, superSeed, xv, zv, RUNTIME, IrisNoiseGenerator.X_AXIS); } private static double reference(IrisNoiseGenerator node, long superSeed, double xv, double zv, - IrisData data, Engine engine, int axis) { + PackRuntime RUNTIME, int axis) { if (!node.isEnabled()) { return node.getOffsetY(); } @@ -240,14 +243,14 @@ public final class IrisNoiseGeneratorFractureTest { if (child.isEnabled()) { double offset = child.getOpacity() / 2D; long childSeed = superSeed + node.getSeed() + salt; - x += reference(child, childSeed, xv, zv, data, engine, IrisNoiseGenerator.X_AXIS) - offset; - z += reference(child, childSeed, xv, zv, data, engine, IrisNoiseGenerator.Z_AXIS) - offset; + x += reference(child, childSeed, xv, zv, RUNTIME, IrisNoiseGenerator.X_AXIS) - offset; + z += reference(child, childSeed, xv, zv, RUNTIME, IrisNoiseGenerator.Z_AXIS) - offset; } salt += 819; } double sampleX = (x / node.getZoom()) + node.getOffsetX(); double sampleZ = (z / node.getZoom()) + node.getOffsetZ(); - CNG generator = node.getGenerator(superSeed, data, engine).reseededForAxis(axis); + CNG generator = node.getGenerator(superSeed, RUNTIME).reseededForAxis(axis); double result = generator.noiseFast2D(sampleX, sampleZ) * node.getOpacity(); result = node.isNegative() ? -result + node.getOpacity() : result; result = (node.getExponent() != 1D ? result < 0D ? -Math.pow(-result, node.getExponent()) diff --git a/core/src/test/java/art/arcane/iris/generation/noise/IrisNoiseGeneratorRemapTest.java b/core/src/test/java/art/arcane/iris/generation/noise/IrisNoiseGeneratorRemapTest.java index 2f2b6e7f4..807ead9a7 100644 --- a/core/src/test/java/art/arcane/iris/generation/noise/IrisNoiseGeneratorRemapTest.java +++ b/core/src/test/java/art/arcane/iris/generation/noise/IrisNoiseGeneratorRemapTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.noise; +import art.arcane.iris.generation.runtime.PackRuntime; import org.junit.Test; import static org.junit.Assert.assertEquals; @@ -13,7 +14,7 @@ public class IrisNoiseGeneratorRemapTest { .setStyle(NoiseStyle.FLAT.style()) .setOpacity(sample[0]) .setParametric(true); - assertEquals(sample[1], layer.getNoise(75L, 13D, -21D, null), 0.000000000001D); + assertEquals(sample[1], layer.getNoise(75L, 13D, -21D, PackRuntime.standalone(null)), 0.000000000001D); } } } diff --git a/core/src/test/java/art/arcane/iris/generation/noise/NoiseSeedCohesionTest.java b/core/src/test/java/art/arcane/iris/generation/noise/NoiseSeedCohesionTest.java index dd83f59e5..9be2435de 100644 --- a/core/src/test/java/art/arcane/iris/generation/noise/NoiseSeedCohesionTest.java +++ b/core/src/test/java/art/arcane/iris/generation/noise/NoiseSeedCohesionTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.noise; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.noise.CNG; import org.junit.Test; @@ -60,12 +61,12 @@ public class NoiseSeedCohesionTest { public void generatorCacheEvictionRetainsSamples() { for (NoiseStyle style : NoiseStyle.values()) { IrisGeneratorStyle configured = style.style(); - double[] expected = samples(configured.create(new RNG(SEEDS[0]), null), false); + double[] expected = samples(configured.create(new RNG(SEEDS[0]), PackRuntime.standalone(null)), false); for (long seed = 0; seed < 9; seed++) { - configured.create(new RNG(seed), null); + configured.create(new RNG(seed), PackRuntime.standalone(null)); } assertArrayEquals(style.name(), expected, - samples(configured.create(new RNG(SEEDS[0]), null), true), 0D); + samples(configured.create(new RNG(SEEDS[0]), PackRuntime.standalone(null)), true), 0D); } } diff --git a/core/src/test/java/art/arcane/iris/generation/noise/NoiseStyleContractTest.java b/core/src/test/java/art/arcane/iris/generation/noise/NoiseStyleContractTest.java index af19275dd..ef29a5c3e 100644 --- a/core/src/test/java/art/arcane/iris/generation/noise/NoiseStyleContractTest.java +++ b/core/src/test/java/art/arcane/iris/generation/noise/NoiseStyleContractTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.noise; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.pack.loading.IrisData; import art.arcane.volmlib.util.noise.CNG; import art.arcane.volmlib.util.noise.NoiseGenerator; @@ -71,8 +72,8 @@ public final class NoiseStyleContractTest { if (style == NoiseStyle.STATIC) { continue; } - CNG normal = style.style().createNoCache(new RNG(45231L), null); - CNG enlarged = style.style().zoomed(2D).createNoCache(new RNG(45231L), null); + CNG normal = style.style().createNoCache(new RNG(45231L), PackRuntime.standalone(null)); + CNG enlarged = style.style().zoomed(2D).createNoCache(new RNG(45231L), PackRuntime.standalone(null)); assertEquals(style.name(), normal.noise(13.25D, -17.75D), enlarged.noise(26.5D, -35.5D), 0.000000001D); assertEquals(style.name(), normal.noise(13.25D), enlarged.noise(26.5D), 0.000000001D); @@ -85,7 +86,7 @@ public final class NoiseStyleContractTest { public void defaultSettingsPreserveEveryPreset() { for (NoiseStyle style : NoiseStyle.values()) { CNG direct = style.create(new RNG(7253L)); - CNG configured = style.style().createNoCache(new RNG(7253L), null); + CNG configured = style.style().createNoCache(new RNG(7253L), PackRuntime.standalone(null)); for (int index = 0; index < 32; index++) { double x = index * 19.713D - 400D; double z = index * -31.579D + 100D; @@ -119,16 +120,16 @@ public final class NoiseStyleContractTest { NoiseStyle.IRIS.style().setCellularFrequency(0.7D).setCellularZoom(1.25D) }; for (IrisGeneratorStyle style : styles) { - CNG normal = style.createNoCache(new RNG(217L), null); - CNG enlarged = style.setZoom(2D).createNoCache(new RNG(217L), null); + CNG normal = style.createNoCache(new RNG(217L), PackRuntime.standalone(null)); + CNG enlarged = style.setZoom(2D).createNoCache(new RNG(217L), PackRuntime.standalone(null)); assertEquals(normal.noise(19.25D, -71.75D), enlarged.noise(38.5D, -143.5D), 0.000000001D); } } @Test public void configuredExponentCompoundsThePresetCurve() { - CNG base = NoiseStyle.VASCULAR_THIN.style().createNoCache(new RNG(8831L), null); - CNG squared = NoiseStyle.VASCULAR_THIN.style().setExponent(2D).createNoCache(new RNG(8831L), null); + CNG base = NoiseStyle.VASCULAR_THIN.style().createNoCache(new RNG(8831L), PackRuntime.standalone(null)); + CNG squared = NoiseStyle.VASCULAR_THIN.style().setExponent(2D).createNoCache(new RNG(8831L), PackRuntime.standalone(null)); double value = base.noise(29.5D, -33.25D); assertEquals(value * value, squared.noise(29.5D, -33.25D), 0.000000000001D); } @@ -158,11 +159,11 @@ public final class NoiseStyleContractTest { @Test public void layerOctavesPreserveAndMultiplyPresetDetail() { IrisGeneratorStyle style = NoiseStyle.QUADOCTAVE_SIMPLEX.style(); - CNG unchanged = style.createForLayer(new RNG(71L), null, 1); - CNG detailed = style.createForLayer(new RNG(71L), null, 2); + CNG unchanged = style.createForLayer(new RNG(71L), PackRuntime.standalone(null), 1); + CNG detailed = style.createForLayer(new RNG(71L), PackRuntime.standalone(null), 2); assertEquals(4, unchanged.getOct()); assertEquals(8, detailed.getOct()); - assertEquals(16, style.createForLayer(new RNG(71L), null, Integer.MAX_VALUE).getOct()); + assertEquals(16, style.createForLayer(new RNG(71L), PackRuntime.standalone(null), Integer.MAX_VALUE).getOct()); assertNotEquals(unchanged.noise(21D, -31D), detailed.noise(21D, -31D), 0D); } @@ -172,10 +173,10 @@ public final class NoiseStyleContractTest { IrisData data = mock(IrisData.class); when(data.getDataFolder()).thenReturn(dataFolder); IrisGeneratorStyle cached = NoiseStyle.BIOCTAVE_SIMPLEX.style().setCacheSize(32); - CNG first = cached.createForLayer(new RNG(921L), data, 3); - CNG reloaded = cached.createForLayer(new RNG(921L), data, 3); - CNG uncached = NoiseStyle.BIOCTAVE_SIMPLEX.style().createForLayer(new RNG(921L), data, 3); - CNG different = cached.createForLayer(new RNG(921L), data, 1); + CNG first = cached.createForLayer(new RNG(921L), PackRuntime.standalone(data), 3); + CNG reloaded = cached.createForLayer(new RNG(921L), PackRuntime.standalone(data), 3); + CNG uncached = NoiseStyle.BIOCTAVE_SIMPLEX.style().createForLayer(new RNG(921L), PackRuntime.standalone(data), 3); + CNG different = cached.createForLayer(new RNG(921L), PackRuntime.standalone(data), 1); assertEquals(6, first.getOct()); assertEquals(6, reloaded.getOct()); assertEquals(uncached.noise(4D, 7D), first.noise(4D, 7D), 0.000001D); @@ -190,12 +191,12 @@ public final class NoiseStyleContractTest { double[] invalid = {0D, -1D, Double.NaN, Double.POSITIVE_INFINITY, Double.MIN_VALUE}; for (double value : invalid) { assertThrows(IllegalArgumentException.class, - () -> NoiseStyle.SIMPLEX.style().setZoom(value).createNoCache(new RNG(1L), null)); + () -> NoiseStyle.SIMPLEX.style().setZoom(value).createNoCache(new RNG(1L), PackRuntime.standalone(null))); assertThrows(IllegalArgumentException.class, - () -> NoiseStyle.SIMPLEX.style().setExponent(value).createNoCache(new RNG(1L), null)); + () -> NoiseStyle.SIMPLEX.style().setExponent(value).createNoCache(new RNG(1L), PackRuntime.standalone(null))); assertThrows(IllegalArgumentException.class, () -> NoiseStyle.SIMPLEX.style().setCellularFrequency(1D).setCellularZoom(value) - .createNoCache(new RNG(1L), null)); + .createNoCache(new RNG(1L), PackRuntime.standalone(null))); } } } diff --git a/core/src/test/java/art/arcane/iris/generation/noise/PatternNoiseStyleTest.java b/core/src/test/java/art/arcane/iris/generation/noise/PatternNoiseStyleTest.java index 5705e32b4..8c7a0a8a3 100644 --- a/core/src/test/java/art/arcane/iris/generation/noise/PatternNoiseStyleTest.java +++ b/core/src/test/java/art/arcane/iris/generation/noise/PatternNoiseStyleTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.noise; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.noise.CNG; import org.junit.Test; @@ -18,7 +19,7 @@ public class PatternNoiseStyleTest { public void styleIntegrationUsesTheSameScaleInEveryDimension() { for (NoiseStyle style : STYLES) { CNG direct = style.create(new RNG(7331L)); - CNG zoomed = style.style().zoomed(2D).createNoCache(new RNG(7331L), null); + CNG zoomed = style.style().zoomed(2D).createNoCache(new RNG(7331L), PackRuntime.standalone(null)); for (int index = 0; index < 128; index++) { double x = index * 13.713D - 400D; double y = index * 1.119D - 70D; diff --git a/core/src/test/java/art/arcane/iris/generation/runtime/DimensionTerrain3DCompositionTest.java b/core/src/test/java/art/arcane/iris/generation/runtime/DimensionTerrain3DCompositionTest.java index 939236c19..1a8c98931 100644 --- a/core/src/test/java/art/arcane/iris/generation/runtime/DimensionTerrain3DCompositionTest.java +++ b/core/src/test/java/art/arcane/iris/generation/runtime/DimensionTerrain3DCompositionTest.java @@ -10,6 +10,7 @@ import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.terrain.IrisDimension; import art.arcane.iris.generation.terrain.IrisRegion; import art.arcane.iris.generation.biome.IrisBiomePaletteLayer; +import art.arcane.iris.generation.biome.PaletteLayerRuntime; import art.arcane.iris.generation.terrain.IrisSlopeClip; import art.arcane.iris.generation.image.IrisImageMapRuntime; import art.arcane.iris.generation.terrain.Terrain3DColumn; @@ -425,7 +426,7 @@ public class DimensionTerrain3DCompositionTest { when(layer.getSlopeCondition()).thenReturn(slope); when(layer.getHeightGenerator(any(), any())).thenReturn(height); when(height.fit(anyInt(), anyInt(), anyDouble(), anyDouble())).thenReturn(1); - when(layer.get(any(), anyInt(), anyDouble(), anyDouble(), anyDouble(), any())).thenReturn(block); + when(layer.get(any(), anyInt(), anyDouble(), anyDouble(), anyDouble(), any(PaletteLayerRuntime.class))).thenReturn(block); layers.add(layer); } return new IrisBiome().setLockLayers(locked).setLayers(layers); diff --git a/core/src/test/java/art/arcane/iris/generation/runtime/EngineBiomeColumnTest.java b/core/src/test/java/art/arcane/iris/generation/runtime/EngineBiomeColumnTest.java index 1bf48551d..a293b5dbf 100644 --- a/core/src/test/java/art/arcane/iris/generation/runtime/EngineBiomeColumnTest.java +++ b/core/src/test/java/art/arcane/iris/generation/runtime/EngineBiomeColumnTest.java @@ -143,6 +143,7 @@ public class EngineBiomeColumnTest { case "getData" -> data; case "getDimension" -> dimension; case "getWorld" -> world; + case "getPackRuntime" -> null; default -> InvocationHandler.invokeDefault(proxy, method, arguments); }); } diff --git a/core/src/test/java/art/arcane/iris/generation/runtime/EngineShutdownDrainTest.java b/core/src/test/java/art/arcane/iris/generation/runtime/EngineShutdownDrainTest.java index 6158663f4..67bec0ae5 100644 --- a/core/src/test/java/art/arcane/iris/generation/runtime/EngineShutdownDrainTest.java +++ b/core/src/test/java/art/arcane/iris/generation/runtime/EngineShutdownDrainTest.java @@ -1,5 +1,9 @@ package art.arcane.iris.generation.runtime; +import art.arcane.iris.structure.nativegen.NativeStructureVolumeIndex; +import art.arcane.iris.structure.placement.StructureReachability; +import art.arcane.iris.structure.placement.StructurePlacementScope; +import art.arcane.iris.structure.placement.IrisStructureLocator; import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.generation.runtime.EngineRuntimeBuilder.RuntimeAssembly; import art.arcane.iris.structure.nativegen.NativeStructureOwnershipStore; @@ -135,6 +139,25 @@ public class EngineShutdownDrainTest { } } + @Test + public void closedEngineRemovesItselfFromEveryStructureRegistry() throws Exception { + ShutdownFixture fixture = new ShutdownFixture(); + try (MockedStatic ownership = mockStatic(NativeStructureOwnershipStore.class); + MockedStatic locator = mockStatic(IrisStructureLocator.class); + MockedStatic reachability = mockStatic(StructureReachability.class); + MockedStatic scopes = mockStatic(StructurePlacementScope.class); + MockedStatic volumes = mockStatic(NativeStructureVolumeIndex.class)) { + fixture.shutdown.close(); + + assertTrue(fixture.engine.closed); + ownership.verify(() -> NativeStructureOwnershipStore.release(fixture.engine)); + locator.verify(() -> IrisStructureLocator.invalidate(fixture.engine)); + reachability.verify(() -> StructureReachability.invalidate(fixture.engine)); + scopes.verify(() -> StructurePlacementScope.invalidate(fixture.engine)); + volumes.verify(() -> NativeStructureVolumeIndex.uninstall(fixture.engine)); + } + } + @Test public void closingRuntimeAllowsItsBackgroundWorkersToOpenCapturedScopes() throws Exception { ShutdownFixture fixture = new ShutdownFixture(); @@ -887,7 +910,7 @@ public class EngineShutdownDrainTest { when(generation.runtimeKernel()).thenReturn(kernel); GenerationRuntime nextGeneration = generation(target, mantle); when(nextGeneration.complex()).thenReturn(replacement); - when(generation.withComplex(anyInt(), same(replacement), isNull(), isNull(), any())) + when(generation.withComplex(anyInt(), same(replacement), any(), isNull(), isNull(), any())) .thenReturn(nextGeneration); EngineRuntimeBuilder builder = spy(new EngineRuntimeBuilder(engine)); doReturn(new GenerationRuntime.BiomeMaxes(0D, 0D, 0D)).when(builder).computeBiomeMaxes(); diff --git a/core/src/test/java/art/arcane/iris/generation/runtime/HydrologyVegetationSourceTest.java b/core/src/test/java/art/arcane/iris/generation/runtime/HydrologyVegetationSourceTest.java index 6a3c075d2..91e902ce0 100644 --- a/core/src/test/java/art/arcane/iris/generation/runtime/HydrologyVegetationSourceTest.java +++ b/core/src/test/java/art/arcane/iris/generation/runtime/HydrologyVegetationSourceTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.runtime; +import art.arcane.iris.testsupport.MockPackData; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.block.IrisBlockData; import art.arcane.iris.generation.decoration.HydrologyVegetation; @@ -42,7 +43,7 @@ public class HydrologyVegetationSourceTest { private static final Set KNOWN = Set.of("minecraft:air", "minecraft:dirt", "minecraft:fern", "minecraft:sugar_cane", "minecraft:short_grass", "minecraft:dead_bush", "minecraft:poppy", "minecraft:dandelion"); - private final IrisData data = mock(IrisData.class); + private final IrisData data = MockPackData.create(); private PlantPlatform platform; @Before @@ -221,7 +222,7 @@ public class HydrologyVegetationSourceTest { return decorators; } }; - new HydrologyVegetation(3L, null).decorate(chunk, 8, 8, 8, 8, WaterRole.SHORE, water, data); + new HydrologyVegetation(3L, null).decorate(chunk, 8, 8, 8, 8, WaterRole.SHORE, water, data.standalonePackRuntime()); return ((PlantBlockState) chunk.get(8, 61, 8)).block(); } diff --git a/core/src/test/java/art/arcane/iris/generation/runtime/IrisCarveWallPaletteScopeTest.java b/core/src/test/java/art/arcane/iris/generation/runtime/IrisCarveWallPaletteScopeTest.java index 1f010a0da..d3c8b1daf 100644 --- a/core/src/test/java/art/arcane/iris/generation/runtime/IrisCarveWallPaletteScopeTest.java +++ b/core/src/test/java/art/arcane/iris/generation/runtime/IrisCarveWallPaletteScopeTest.java @@ -1,10 +1,12 @@ package art.arcane.iris.generation.runtime; +import art.arcane.iris.testsupport.MockPackData; import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.generation.mantle.EngineMantle; import art.arcane.iris.generation.stage.IrisCarveModifier; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.biome.IrisBiomePaletteLayer; +import art.arcane.iris.generation.biome.PaletteLayerRuntime; import art.arcane.iris.generation.terrain.IrisDimension; import art.arcane.iris.generation.terrain.IrisDimensionCarvingResolver; import art.arcane.iris.world.IrisWorld; @@ -171,7 +173,7 @@ public class IrisCarveWallPaletteScopeTest { private final MantleChunk chunk; private final GenerationRuntime active; private final GenerationRuntime detached; - private final IrisData assemblyData = mock(IrisData.class); + private final IrisData assemblyData = MockPackData.create(); private final IrisComplex assemblyComplex = mock(IrisComplex.class); private final EngineRuntimeBuilder.RuntimeAssembly assembly; private final AtomicInteger dataLookups = new AtomicInteger(); @@ -194,8 +196,8 @@ public class IrisCarveWallPaletteScopeTest { doReturn(1).when(chunk).sectionCount(); doReturn(true).when(chunk).exists(0); doReturn(section).when(chunk).get(0); - active = runtime(mock(IrisData.class), mock(IrisComplex.class), engineMantle); - detached = runtime(mock(IrisData.class), mock(IrisComplex.class), engineMantle); + active = runtime(MockPackData.create(), mock(IrisComplex.class), engineMantle); + detached = runtime(MockPackData.create(), mock(IrisComplex.class), engineMantle); field(engine, IrisEngine.class, "lifecycleLock", new Object()); field(engine, IrisEngine.class, "threadState", new EngineThreadState()); field(engine, IrisEngine.class, "detachedGenerationRuntimes", Collections.newSetFromMap(new IdentityHashMap<>())); @@ -219,17 +221,17 @@ public class IrisCarveWallPaletteScopeTest { doReturn(engine.getWorld()).when(assemblyTarget).getWorld(); doReturn(assemblyData).when(assemblyTarget).getData(); doReturn(mock(IrisDimension.class)).when(assemblyTarget).getDimension(); - assembly = new EngineRuntimeBuilder.RuntimeAssembly(19, assemblyTarget); + assembly = new EngineRuntimeBuilder.RuntimeAssembly(engine, 19, assemblyTarget); assembly.complex = assemblyComplex; assembly.mantle = engineMantle; IrisBiome biome = mock(IrisBiome.class); IrisBiomePaletteLayer palette = mock(IrisBiomePaletteLayer.class); doReturn(palette).when(biome).getWall(); doAnswer(call -> { - assertSame(expectedData, call.getArgument(4)); + assertSame(expectedData, call.getArgument(5).packRuntime().data()); paletteCalls.incrementAndGet(); return wall; - }).when(palette).get(any(RNG.class), anyDouble(), anyDouble(), anyDouble(), any(IrisData.class)); + }).when(palette).get(any(RNG.class), anyInt(), anyDouble(), anyDouble(), anyDouble(), any(PaletteLayerRuntime.class)); for (IrisComplex complex : new IrisComplex[]{activeComplex, detachedComplex, assemblyComplex}) { doReturn(ProceduralStream.of((x, z) -> biome, Interpolated.of(value -> 0D, value -> null))) .when(complex).getTrueBiomeStream(); diff --git a/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexChunkCornersTest.java b/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexChunkCornersTest.java index 090046995..bdf80cbb3 100644 --- a/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexChunkCornersTest.java +++ b/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexChunkCornersTest.java @@ -171,7 +171,7 @@ public class IrisComplexChunkCornersTest { Class cacheClass = Class.forName("art.arcane.iris.generation.runtime.IrisComplex$GridBoundsCache"); Constructor cacheConstructor = cacheClass.getDeclaredConstructor(); cacheConstructor.setAccessible(true); - setField(complex, "gridBoundsCache", ThreadLocal.withInitial(() -> newCache(cacheConstructor))); + setField(complex, "gridBoundsCache", new ThreadSlots<>(() -> newCache(cacheConstructor))); return complex; } @@ -257,7 +257,7 @@ public class IrisComplexChunkCornersTest { private boolean nested; @Override - public double getHeight(double x, double z, long seed) { + public double getHeight(PackRuntime runtime, double x, double z, long seed) { if (nested) { return Math.cos(x * 0.13D) * 0.5D; } @@ -281,7 +281,7 @@ public class IrisComplexChunkCornersTest { } @Override - public double getHeight(double x, double z, long seed) { + public double getHeight(PackRuntime runtime, double x, double z, long seed) { invocations++; return Math.sin(x * 0.37D + seed) * Math.cos(z * 0.21D) * amplitude; } diff --git a/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexConstantGeneratorBoundsTest.java b/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexConstantGeneratorBoundsTest.java index dfd7a10fe..09b6c6c30 100644 --- a/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexConstantGeneratorBoundsTest.java +++ b/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexConstantGeneratorBoundsTest.java @@ -32,7 +32,7 @@ public class IrisComplexConstantGeneratorBoundsTest { expected += M.lerp(low, high, noise); } expected /= size; - assertBits(expected, IrisComplex.averageGeneratorHeights(generators, low, high, 12D, -9D, 7331L)); + assertBits(expected, IrisComplex.averageGeneratorHeights(PackRuntime.standalone(null), generators, low, high, 12D, -9D, 7331L)); assertEquals(0, generator.calls); } } @@ -44,8 +44,8 @@ public class IrisComplexConstantGeneratorBoundsTest { public void inactiveInvalidNoiseMatchesExistingConstantFitContract() { for (double noise : new double[]{Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY}) { CountingGenerator generator = new CountingGenerator(noise); - assertBits(generator.fitDouble(0D, 0D, 7331L, 12D, -9D), - IrisComplex.averageGeneratorHeights(new IrisGenerator[]{generator}, 0D, 0D, 12D, -9D, 7331L)); + assertBits(generator.fitDouble(PackRuntime.standalone(null), 0D, 0D, 7331L, 12D, -9D), + IrisComplex.averageGeneratorHeights(PackRuntime.standalone(null), new IrisGenerator[]{generator}, 0D, 0D, 12D, -9D, 7331L)); assertEquals(0, generator.calls); assertTrue(Double.isNaN(M.lerp(0D, 0D, noise))); } @@ -58,7 +58,7 @@ public class IrisComplexConstantGeneratorBoundsTest { for (double noise : new double[]{0.3D, -2D, 3D}) { CountingGenerator generator = new CountingGenerator(noise); double expected = (0D + M.lerp(pair[0], pair[1], noise)) / 1; - assertBits(expected, IrisComplex.averageGeneratorHeights(new IrisGenerator[]{generator}, + assertBits(expected, IrisComplex.averageGeneratorHeights(PackRuntime.standalone(null), new IrisGenerator[]{generator}, pair[0], pair[1], 12D, -9D, 7331L)); assertEquals(1, generator.calls); } @@ -72,7 +72,7 @@ public class IrisComplexConstantGeneratorBoundsTest { CountingGenerator generator = new CountingGenerator(0.3D); generator.setLoadKey("diagnostic/terrain"); IllegalStateException failure = assertThrows(IllegalStateException.class, - () -> IrisComplex.averageGeneratorHeights(new IrisGenerator[]{generator}, + () -> IrisComplex.averageGeneratorHeights(PackRuntime.standalone(null), new IrisGenerator[]{generator}, bounds[0], bounds[1], 671D, 2437D, 7331L)); assertTrue(failure.getMessage().contains("671.0,2437.0")); assertTrue(failure.getMessage().contains("generator=diagnostic/terrain")); @@ -90,7 +90,7 @@ public class IrisComplexConstantGeneratorBoundsTest { invalidGenerator.setLoadKey("diagnostic/cliffs"); CountingGenerator unsampled = new CountingGenerator(0.5D); IllegalStateException failure = assertThrows(IllegalStateException.class, - () -> IrisComplex.averageGeneratorHeights(new IrisGenerator[]{valid, invalidGenerator, unsampled}, + () -> IrisComplex.averageGeneratorHeights(PackRuntime.standalone(null), new IrisGenerator[]{valid, invalidGenerator, unsampled}, 0D, 44D, 671D, 2437D, 7331L)); assertTrue(failure.getMessage().contains("671.0,2437.0")); assertTrue(failure.getMessage().contains("generator=diagnostic/cliffs")); @@ -115,7 +115,7 @@ public class IrisComplexConstantGeneratorBoundsTest { } @Override - public double getHeight(double x, double z, long seed) { + public double getHeight(PackRuntime runtime, double x, double z, long seed) { calls++; return value; } diff --git a/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexGeneratorOrderingTest.java b/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexGeneratorOrderingTest.java index df02aca76..ac7b85d19 100644 --- a/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexGeneratorOrderingTest.java +++ b/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexGeneratorOrderingTest.java @@ -60,7 +60,7 @@ public class IrisComplexGeneratorOrderingTest { ); double output = 0D; for (IrisComplex.GeneratorGroup group : groups) { - output += IrisComplex.averageGeneratorHeights( + output += IrisComplex.averageGeneratorHeights(PackRuntime.standalone(null), group.generators(), 0D, 1D, @@ -78,7 +78,7 @@ public class IrisComplexGeneratorOrderingTest { Map> generators = Map.of(); assertEquals(0, IrisComplex.freezeGeneratorGroups(generators).length); - assertEquals(0D, IrisComplex.averageGeneratorHeights( + assertEquals(0D, IrisComplex.averageGeneratorHeights(PackRuntime.standalone(null), new IrisGenerator[0], -1D, 1D, @@ -141,7 +141,7 @@ public class IrisComplexGeneratorOrderingTest { } @Override - public double getHeight(double x, double z, long seed) { + public double getHeight(PackRuntime runtime, double x, double z, long seed) { return height; } } diff --git a/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexGridBoundsCacheTest.java b/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexGridBoundsCacheTest.java index 3f4b7b36b..bc04030ba 100644 --- a/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexGridBoundsCacheTest.java +++ b/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexGridBoundsCacheTest.java @@ -247,7 +247,7 @@ public class IrisComplexGridBoundsCacheTest { Class cacheClass = Class.forName("art.arcane.iris.generation.runtime.IrisComplex$GridBoundsCache"); Constructor cacheConstructor = cacheClass.getDeclaredConstructor(); cacheConstructor.setAccessible(true); - ThreadLocal cache = ThreadLocal.withInitial(() -> newCache(cacheConstructor)); + ThreadSlots cache = new ThreadSlots<>(() -> newCache(cacheConstructor)); Field gridBoundsCache = IrisComplex.class.getDeclaredField("gridBoundsCache"); gridBoundsCache.setAccessible(true); gridBoundsCache.set(complex, cache); @@ -295,7 +295,7 @@ public class IrisComplexGridBoundsCacheTest { private static long invokeCornerBounds(IrisComplex complex, Method method, IrisInterpolator interpolator, int x, int z) throws Exception { Field gridBoundsCache = IrisComplex.class.getDeclaredField("gridBoundsCache"); gridBoundsCache.setAccessible(true); - ThreadLocal cache = (ThreadLocal) gridBoundsCache.get(complex); + ThreadSlots cache = (ThreadSlots) gridBoundsCache.get(complex); return (long) method.invoke(complex, cache.get(), null, interpolator, 0, new IrisGenerator[0], x, z); } @@ -392,7 +392,7 @@ public class IrisComplexGridBoundsCacheTest { } @Override - public double getHeight(double x, double z, long seed) { + public double getHeight(PackRuntime runtime, double x, double z, long seed) { invocations++; return value; } diff --git a/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexSelfSelectionTest.java b/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexSelfSelectionTest.java index b0e7aedd6..69dca5a9b 100644 --- a/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexSelfSelectionTest.java +++ b/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexSelfSelectionTest.java @@ -106,7 +106,7 @@ public class IrisComplexSelfSelectionTest { } @Override - public CNG getChildrenGenerator(long seed, double scale) { + public CNG getChildrenGenerator(PackRuntime runtime, long seed, double scale) { return noise; } } diff --git a/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexTransitionTest.java b/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexTransitionTest.java index b7ef9b9e8..c7e8eee3d 100644 --- a/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexTransitionTest.java +++ b/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexTransitionTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.runtime; +import art.arcane.iris.testsupport.MockPackData; import art.arcane.iris.generation.context.ChunkContext; import art.arcane.iris.world.history.TransitionDisplacementField; import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster; @@ -671,7 +672,7 @@ public class IrisComplexTransitionTest { private Hunk paint(int chunkX) { Engine engine = mock(Engine.class); - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); IrisBiome biome = mock(IrisBiome.class); IrisRegion region = new IrisRegion(); IrisDimension dimension = new IrisDimension().setBedrock(false).setHideOresForHiddenOre(true); @@ -679,9 +680,9 @@ public class IrisComplexTransitionTest { when(engine.getComplex()).thenReturn(complex); when(engine.getData()).thenReturn(data); when(engine.getSeedManager()).thenReturn(mock(SeedManager.class)); - when(biome.generateLayers(eq(dimension), anyDouble(), anyDouble(), any(RNG.class), anyInt(), anyInt(), eq(data), same(complex))) + when(biome.generateLayers(eq(dimension), anyDouble(), anyDouble(), any(RNG.class), anyInt(), anyInt(), MockPackData.runtimeOf(data), same(complex))) .thenAnswer(invocation -> new KList<>(List.of(stone))); - when(biome.generateSeaLayers(anyDouble(), anyDouble(), any(RNG.class), anyInt(), eq(data))) + when(biome.generateSeaLayers(anyDouble(), anyDouble(), any(RNG.class), anyInt(), MockPackData.runtimeOf(data))) .thenAnswer(invocation -> new KList<>(Collections.nCopies(seaLayers, ice))); int[] grounds = grounds(chunkX); ChunkContext context = mock(ChunkContext.class); diff --git a/core/src/test/java/art/arcane/iris/generation/runtime/IrisEngineGenerationCacheWarmTest.java b/core/src/test/java/art/arcane/iris/generation/runtime/IrisEngineGenerationCacheWarmTest.java index 5c600b41f..7344ca485 100644 --- a/core/src/test/java/art/arcane/iris/generation/runtime/IrisEngineGenerationCacheWarmTest.java +++ b/core/src/test/java/art/arcane/iris/generation/runtime/IrisEngineGenerationCacheWarmTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.runtime; +import art.arcane.iris.testsupport.MockPackData; import art.arcane.iris.generation.runtime.EngineBackgroundTasks.BackgroundTaskDrain; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.decoration.IrisOreGenerator; @@ -75,7 +76,7 @@ public class IrisEngineGenerationCacheWarmTest { Fixture fixture = fixture(); AtomicReference> queued = new AtomicReference<>(); IllegalStateException expected = new IllegalStateException("cache warm failed"); - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); IrisOreGenerator ore = mock(IrisOreGenerator.class); IrisBiome biome = new IrisBiome(); biome.setLoadKey("failing-ore"); @@ -83,7 +84,7 @@ public class IrisEngineGenerationCacheWarmTest { when(fixture.engine().getData()).thenReturn(data); when(fixture.engine().getSeedManager()).thenReturn(mock(SeedManager.class)); when(fixture.engine().getAllBiomes()).thenReturn(new KList<>(biome)); - doThrow(expected).when(ore).warm(any(RNG.class), same(data)); + doThrow(expected).when(ore).warm(any(RNG.class), MockPackData.runtimeOf(data)); try (MockedStatic scheduling = scheduler(queued); MockedStatic logging = mockStatic(IrisLogging.class)) { fixture.engine().prepareGenerationCaches(IrisEngine.InitializationMode.WORLD_CREATION, System.nanoTime()); diff --git a/core/src/test/java/art/arcane/iris/generation/runtime/IrisEngineGenerationRuntimeScopeTest.java b/core/src/test/java/art/arcane/iris/generation/runtime/IrisEngineGenerationRuntimeScopeTest.java index 934ca72d4..4172390af 100644 --- a/core/src/test/java/art/arcane/iris/generation/runtime/IrisEngineGenerationRuntimeScopeTest.java +++ b/core/src/test/java/art/arcane/iris/generation/runtime/IrisEngineGenerationRuntimeScopeTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.runtime; +import art.arcane.iris.testsupport.MockPackData; import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.generation.hydrology.config.IrisHydrology; import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime; @@ -55,6 +56,7 @@ import java.util.function.IntConsumer; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import static org.mockito.ArgumentMatchers.eq; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; @@ -197,8 +199,8 @@ public class IrisEngineGenerationRuntimeScopeTest { when(childBiome.getRarity()).thenReturn(1); when(root.getRealBiome(fixture.data)).thenReturn(parentBiome); when(child.getRealBiome(fixture.data)).thenReturn(childBiome); - when(root.getChildrenGenerator(fixture.runtime.seedManager().getCarve() ^ 0x9E3779B97F4A7C15L, - fixture.data)).thenReturn(generator); + when(root.getChildrenGenerator(eq(fixture.runtime.seedManager().getCarve() ^ 0x9E3779B97F4A7C15L), + MockPackData.runtimeOf(fixture.data))).thenReturn(generator); when(fixture.dimension.getCarving()).thenReturn(new KList<>(root)); when(fixture.dimension.getCarvingEntryIndex()).thenReturn(Map.of("child", child)); expected[index] = childBiome; @@ -816,6 +818,7 @@ public class IrisEngineGenerationRuntimeScopeTest { RuntimeFixture active = runtime(1, 1D, 1D, 1D); IrisEngine engine = engine(active.runtime, mock(EngineEffects.class), mock(EngineWorldManager.class)); EngineRuntimeBuilder.RuntimeAssembly assembly = new EngineRuntimeBuilder.RuntimeAssembly( + engine, 2, active.target, Path.of("build", "test-mantles", "assembly")); @@ -1073,6 +1076,7 @@ public class IrisEngineGenerationRuntimeScopeTest { mock(SeedManager.class), null, complex, + PackRuntime.standalone(data), upperContext, dimensionStackContext, mode, diff --git a/core/src/test/java/art/arcane/iris/generation/runtime/IrisEngineStreamTypeTest.java b/core/src/test/java/art/arcane/iris/generation/runtime/IrisEngineStreamTypeTest.java index 88bbaae7c..186ec0884 100644 --- a/core/src/test/java/art/arcane/iris/generation/runtime/IrisEngineStreamTypeTest.java +++ b/core/src/test/java/art/arcane/iris/generation/runtime/IrisEngineStreamTypeTest.java @@ -92,7 +92,7 @@ public class IrisEngineStreamTypeTest { assertUnknownStream("NOT_A_STREAM", () -> data.getExpressionLoader().load("inline")); assertUnknownStream("NOT_A_STREAM", () -> data.getExpressionLoader().load("snippet")); assertUnknownStream("water_head", () -> data.getExpressionLoader().load("lowercase")); - assertUnknownStream("NOT_A_STREAM", () -> new IrisGeneratorStyle().setExpression("inline").create(new RNG(7L), data)); + assertUnknownStream("NOT_A_STREAM", () -> new IrisGeneratorStyle().setExpression("inline").create(new RNG(7L), PackRuntime.standalone(data))); IrisExpression known = data.getExpressionLoader().load("known"); assertSame(IrisEngineStreamType.WATER_HEAD, known.getVariables().get(0).getEngineStreamValue()); diff --git a/core/src/test/java/art/arcane/iris/generation/runtime/RuntimeTableTest.java b/core/src/test/java/art/arcane/iris/generation/runtime/RuntimeTableTest.java new file mode 100644 index 000000000..e7ccd91f1 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/generation/runtime/RuntimeTableTest.java @@ -0,0 +1,59 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.generation.runtime; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; + +public class RuntimeTableTest { + @Test + public void buildsOncePerPackObject() { + AtomicInteger builds = new AtomicInteger(); + RuntimeTable, Object> table = new RuntimeTable<>(config -> { + builds.incrementAndGet(); + return new Object(); + }); + List config = List.of("a"); + + assertSame(table.get(config), table.get(config)); + assertEquals(1, builds.get()); + } + + @Test + public void equalPackObjectsGetTheirOwnRuntime() { + RuntimeTable, Object> table = new RuntimeTable<>(config -> new Object()); + + assertNotSame(table.get(List.of("a")), table.get(new ArrayList<>(List.of("a")))); + } + + @Test + public void builderMayResolveOtherEntriesOfTheSameTable() { + RuntimeTable[] holder = new RuntimeTable[1]; + holder[0] = new RuntimeTable<>(depth -> depth == 0 ? 0 : holder[0].get(depth - 1) + 1); + + assertEquals(Integer.valueOf(3), holder[0].get(3)); + } +} diff --git a/core/src/test/java/art/arcane/iris/generation/runtime/ThreadSlotsTest.java b/core/src/test/java/art/arcane/iris/generation/runtime/ThreadSlotsTest.java new file mode 100644 index 000000000..ef808301a --- /dev/null +++ b/core/src/test/java/art/arcane/iris/generation/runtime/ThreadSlotsTest.java @@ -0,0 +1,128 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.generation.runtime; + +import static org.junit.Assert.assertNull; +import java.util.concurrent.CountDownLatch; +import java.util.List; +import java.util.ArrayList; +import org.junit.Test; + +import java.lang.reflect.Field; +import java.util.concurrent.atomic.AtomicReferenceArray; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; + +public class ThreadSlotsTest { + private static final int THREAD_CHURN = 2_000; + + @Test + public void sameThreadGetsItsOwnValueBack() { + ThreadSlots slots = new ThreadSlots<>(Object::new); + + assertSame(slots.get(), slots.get()); + } + + @Test + public void otherThreadsGetTheirOwnValues() throws Exception { + ThreadSlots slots = new ThreadSlots<>(Object::new); + Object callerValue = slots.get(); + AtomicReference workerValue = new AtomicReference<>(); + + Thread worker = new Thread(() -> workerValue.set(slots.get())); + worker.start(); + worker.join(); + + assertNotSame(callerValue, workerValue.get()); + assertSame(callerValue, slots.get()); + } + + @Test + public void workerChurnReusesSlotsOfDeadThreads() throws Exception { + AtomicInteger created = new AtomicInteger(); + ThreadSlots slots = new ThreadSlots<>(() -> { + created.incrementAndGet(); + return new Object(); + }); + + for (int index = 0; index < THREAD_CHURN; index++) { + Thread worker = new Thread(slots::get); + worker.start(); + worker.join(); + } + + assertEquals(THREAD_CHURN, created.get()); + assertEquals("The table must stay at its fixed size", 256, slotCount(slots)); + } + + @Test + public void bindingsStayUnsetUntilBoundAndClearOnRemove() { + ThreadSlots bindings = ThreadSlots.bindings(); + Object value = new Object(); + + assertNull(bindings.get()); + bindings.set(value); + assertSame(value, bindings.get()); + bindings.remove(); + assertNull(bindings.get()); + } + + @Test + public void liveThreadsBeyondTheProbedSlotsKeepTheirValues() throws Exception { + ThreadSlots slots = new ThreadSlots<>(Object::new); + int threads = 300; + CountDownLatch filled = new CountDownLatch(threads); + CountDownLatch release = new CountDownLatch(1); + AtomicInteger lost = new AtomicInteger(); + List workers = new ArrayList<>(); + for (int index = 0; index < threads; index++) { + Thread worker = new Thread(() -> { + Object first = slots.get(); + filled.countDown(); + try { + release.await(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + } + if (slots.get() != first) { + lost.incrementAndGet(); + } + }); + workers.add(worker); + worker.start(); + } + filled.await(); + release.countDown(); + for (Thread worker : workers) { + worker.join(); + } + + assertEquals(0, lost.get()); + } + + private static int slotCount(ThreadSlots slots) throws ReflectiveOperationException { + Field field = ThreadSlots.class.getDeclaredField("owners"); + field.setAccessible(true); + return ((AtomicReferenceArray) field.get(slots)).length(); + } +} diff --git a/core/src/test/java/art/arcane/iris/generation/stage/IrisCarveModifierLayerMemoTest.java b/core/src/test/java/art/arcane/iris/generation/stage/IrisCarveModifierLayerMemoTest.java index 11c52fe98..043b6c86c 100644 --- a/core/src/test/java/art/arcane/iris/generation/stage/IrisCarveModifierLayerMemoTest.java +++ b/core/src/test/java/art/arcane/iris/generation/stage/IrisCarveModifierLayerMemoTest.java @@ -1,5 +1,7 @@ package art.arcane.iris.generation.stage; +import art.arcane.iris.generation.runtime.PackRuntime; +import art.arcane.iris.testsupport.MockPackData; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.biome.IrisBiomePaletteLayer; import art.arcane.iris.generation.biome.IrisSurfaceLayerFallback; @@ -33,7 +35,7 @@ public class IrisCarveModifierLayerMemoTest { @Test public void heightFreeFloorLayersIgnoreTheZoneFloor() { - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); IrisComplex complex = mock(IrisComplex.class); when(complex.hasTerrain3D()).thenReturn(true); when(complex.terrainSurfaceSlope(anyInt(), anyInt(), anyInt())).thenAnswer(call -> (double) (int) call.getArgument(1)); @@ -44,9 +46,9 @@ public class IrisCarveModifierLayerMemoTest { IrisDimension dimension = new IrisDimension().setSurfaceLayerFallback(IrisSurfaceLayerFallback.TOP_LAYER); assertTrue(IrisCarveModifier.hasHeightFreeFloorLayers(biome)); - KList reference = biome.generateLayers(dimension, 14D, -9D, rng, 3, 0, data, complex); + KList reference = biome.generateLayers(dimension, 14D, -9D, rng, 3, 0, data.standalonePackRuntime(), complex); for (int floor = -64; floor < 320; floor += 7) { - assertEquals(reference, biome.generateLayers(dimension, 14D, -9D, rng, 3, floor, data, complex)); + assertEquals(reference, biome.generateLayers(dimension, 14D, -9D, rng, 3, floor, data.standalonePackRuntime(), complex)); } biome.setLockLayers(true); @@ -82,9 +84,9 @@ public class IrisCarveModifierLayerMemoTest { when(layer.getMinHeight()).thenReturn(thickness); when(layer.getMaxHeight()).thenReturn(thickness); when(layer.getSlopeCondition()).thenReturn(slope); - when(layer.getHeightGenerator(any(RNG.class), same(data))).thenReturn(height); + when(layer.getHeightGenerator(any(RNG.class), MockPackData.runtimeOf(data))).thenReturn(height); when(height.fit(anyInt(), anyInt(), anyDouble(), anyDouble())).thenReturn(thickness); - when(layer.get(any(RNG.class), anyInt(), anyDouble(), anyDouble(), anyDouble(), same(data))) + when(layer.get(any(RNG.class), anyInt(), anyDouble(), anyDouble(), anyDouble(), MockPackData.paletteLayerRuntimeOf(data))) .thenAnswer(call -> block((int) call.getArgument(1))); return layer; } diff --git a/core/src/test/java/art/arcane/iris/generation/stage/IrisCarveModifierSubterrainMaskTest.java b/core/src/test/java/art/arcane/iris/generation/stage/IrisCarveModifierSubterrainMaskTest.java index ac9945e76..b90cc9874 100644 --- a/core/src/test/java/art/arcane/iris/generation/stage/IrisCarveModifierSubterrainMaskTest.java +++ b/core/src/test/java/art/arcane/iris/generation/stage/IrisCarveModifierSubterrainMaskTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.stage; +import art.arcane.iris.testsupport.MockPackData; import art.arcane.iris.generation.block.B; import art.arcane.iris.generation.hydrology.cave.HydrologyCaveAction; import art.arcane.iris.generation.hydrology.cave.HydrologyCaveCell; @@ -157,7 +158,8 @@ public class IrisCarveModifierSubterrainMaskTest { when(engine.getWorld()).thenReturn(IrisWorld.builder().minHeight(MINIMUM_Y).maxHeight(64).build()); when(engine.getComplex()).thenReturn(complex); when(engine.getDimension()).thenReturn(new IrisDimension()); - when(engine.getData()).thenReturn(mock(IrisData.class)); + IrisData data = MockPackData.create(); + when(engine.getData()).thenReturn(data); when(complex.getSubterrainPlanner()).thenReturn(planner); when(complex.getHydrologyRuntime()).thenReturn(hydrology); IrisCarveModifier modifier = mock(IrisCarveModifier.class, CALLS_REAL_METHODS); diff --git a/core/src/test/java/art/arcane/iris/generation/stage/IrisDepositModifierContextTest.java b/core/src/test/java/art/arcane/iris/generation/stage/IrisDepositModifierContextTest.java index 850b8b54d..f45884d9c 100644 --- a/core/src/test/java/art/arcane/iris/generation/stage/IrisDepositModifierContextTest.java +++ b/core/src/test/java/art/arcane/iris/generation/stage/IrisDepositModifierContextTest.java @@ -82,7 +82,7 @@ public class IrisDepositModifierContextTest { public void workerPreparationFailurePropagatesAfterAllScopesClose() throws Exception { try (Fixture fixture = new Fixture(mock(IrisEngine.class, RETURNS_DEEP_STUBS), true)) { GenerationClosedException failure = new GenerationClosedException("worker clump preparation failed"); - doThrow(failure).when(fixture.dimensionDeposit).getClump(any(), any(), any()); + doThrow(failure).when(fixture.dimensionDeposit).getClump(any(), any()); assertSame(failure, assertThrows(GenerationClosedException.class, () -> fixture.modifier.modify(32, -48, Hunk.newArrayHunk(16, 16, 16), true, fixture.context))); verify(fixture.chunk).release(); @@ -94,7 +94,7 @@ public class IrisDepositModifierContextTest { @Test public void contentFailureInOneClumpSkipsItAndTheChunkContinues() throws Exception { try (Fixture fixture = new Fixture(mock(IrisEngine.class, RETURNS_DEEP_STUBS), true)) { - doThrow(new IllegalArgumentException("bad clump")).when(fixture.dimensionDeposit).getClump(any(), any(), any()); + doThrow(new IllegalArgumentException("bad clump")).when(fixture.dimensionDeposit).getClump(any(), any()); fixture.modifier.modify(32, -48, Hunk.newArrayHunk(16, 16, 16), true, fixture.context); verify(fixture.chunk).release(); assertNull(IrisContext.get()); @@ -127,7 +127,7 @@ public class IrisDepositModifierContextTest { RejectedExecutionException secondWorker = new RejectedExecutionException("second worker failure"); when(fixture.dimensionDeposit.getMinPerChunk()).thenReturn(200); when(fixture.dimensionDeposit.getMaxPerChunk()).thenReturn(200); - doThrow(firstWorker, secondWorker).when(fixture.dimensionDeposit).getClump(any(), any(), any()); + doThrow(firstWorker, secondWorker).when(fixture.dimensionDeposit).getClump(any(), any()); assertSame(firstWorker, assertThrows(GenerationClosedException.class, () -> fixture.modifier.modify(32, -48, Hunk.newArrayHunk(16, 16, 16), true, fixture.context))); assertEquals(1, firstWorker.getSuppressed().length); @@ -154,7 +154,7 @@ public class IrisDepositModifierContextTest { verify(generator, times(4)).getPerClumpSpawnChance(); verify(rng, times(1)).i(0, 5); - verify(generator, never()).getClump(any(), any(), any()); + verify(generator, never()).getClump(any(), any()); } private static final class Fixture implements AutoCloseable { @@ -222,7 +222,7 @@ public class IrisDepositModifierContextTest { assertEquals(71L, IrisContext.require().getGenerationSessionId()); completed.incrementAndGet(); return clump; - }).when(generator).getClump(any(), any(), any()); + }).when(generator).getClump(any(), any()); } when(dimensionDeposit.getMinPerChunk()).thenReturn(9); when(dimensionDeposit.getMaxPerChunk()).thenReturn(9); diff --git a/core/src/test/java/art/arcane/iris/generation/stage/IrisDepositModifierOrderingTest.java b/core/src/test/java/art/arcane/iris/generation/stage/IrisDepositModifierOrderingTest.java index a067bd3be..09ddf6902 100644 --- a/core/src/test/java/art/arcane/iris/generation/stage/IrisDepositModifierOrderingTest.java +++ b/core/src/test/java/art/arcane/iris/generation/stage/IrisDepositModifierOrderingTest.java @@ -359,7 +359,7 @@ public class IrisDepositModifierOrderingTest { clump.getBlocks().put(new IrisBlockVector(x, 0, z), replacement); } } - when(generator.getClump(any(), any(), any())).thenAnswer(invocation -> { + when(generator.getClump(any(), any())).thenAnswer(invocation -> { if (reverse && name.equals("dimension")) { assertTrue(regionReady.await(10, TimeUnit.SECONDS)); } else if (reverse && name.equals("region")) { diff --git a/core/src/test/java/art/arcane/iris/generation/stage/IrisDepositModifierParityTest.java b/core/src/test/java/art/arcane/iris/generation/stage/IrisDepositModifierParityTest.java index 7fd6f7c06..d56d3050a 100644 --- a/core/src/test/java/art/arcane/iris/generation/stage/IrisDepositModifierParityTest.java +++ b/core/src/test/java/art/arcane/iris/generation/stage/IrisDepositModifierParityTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.stage; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.testsupport.KeyedBlockState; import art.arcane.iris.pack.loading.IrisData; @@ -277,6 +278,8 @@ public class IrisDepositModifierParityTest { when(engine.getData()).thenReturn(data); when(engine.getDimensionStackContext()).thenReturn(null); } + PackRuntime runtime = PackRuntime.forEngine(engine, engine.getData()); + when(engine.getPackRuntime()).thenReturn(runtime); when(engine.getCaveBiome(anyInt(), anyInt(), anyInt(), any())).thenAnswer(invocation -> { caveBiomeLookups.incrementAndGet(); int x = invocation.getArgument(0); @@ -564,9 +567,9 @@ public class IrisDepositModifierParityTest { } @Override - public IrisObject getClump(Engine engine, RNG rng, IrisData data) { + public IrisObject getClump(PackRuntime runtime, RNG rng) { clumps.incrementAndGet(); - return super.getClump(engine, rng, data); + return super.getClump(runtime, rng); } @Override diff --git a/core/src/test/java/art/arcane/iris/generation/stage/IrisDepositModifierPoolGuardTest.java b/core/src/test/java/art/arcane/iris/generation/stage/IrisDepositModifierPoolGuardTest.java index 577e34018..cd43c4023 100644 --- a/core/src/test/java/art/arcane/iris/generation/stage/IrisDepositModifierPoolGuardTest.java +++ b/core/src/test/java/art/arcane/iris/generation/stage/IrisDepositModifierPoolGuardTest.java @@ -147,7 +147,7 @@ public class IrisDepositModifierPoolGuardTest { clump.getBlocks().put(new IrisBlockVector(x, 0, z), gravel); } } - when(generator.getClump(any(), any(), any())).thenReturn(clump); + when(generator.getClump(any(), any())).thenReturn(clump); return generator; } } diff --git a/core/src/test/java/art/arcane/iris/generation/stage/IrisTerrainNormalActuatorBankCutTest.java b/core/src/test/java/art/arcane/iris/generation/stage/IrisTerrainNormalActuatorBankCutTest.java index 51463d685..10dcfe395 100644 --- a/core/src/test/java/art/arcane/iris/generation/stage/IrisTerrainNormalActuatorBankCutTest.java +++ b/core/src/test/java/art/arcane/iris/generation/stage/IrisTerrainNormalActuatorBankCutTest.java @@ -1,5 +1,7 @@ package art.arcane.iris.generation.stage; +import art.arcane.iris.generation.runtime.PackRuntime; +import art.arcane.iris.testsupport.MockPackData; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.context.ChunkContext; import art.arcane.iris.generation.context.ChunkedDataCache; @@ -25,6 +27,7 @@ import org.junit.Test; import java.util.List; +import static org.mockito.ArgumentMatchers.same; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.mockito.ArgumentMatchers.any; @@ -92,7 +95,7 @@ public class IrisTerrainNormalActuatorBankCutTest { private final IrisComplex complex = mock(IrisComplex.class); private Fixture(WaterRole role) { - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); IrisBiome biome = mock(IrisBiome.class); IrisRegion region = new IrisRegion(); IrisDimension dimension = new IrisDimension() @@ -129,9 +132,9 @@ public class IrisTerrainNormalActuatorBankCutTest { when(context.getFluid()).thenReturn(new ChunkedDataCache<>( ProceduralStream.of((x, z) -> null, Interpolated.of(value -> 0D, value -> null)), 11, -4, false)); when(biome.generateLayers(eq(dimension), anyDouble(), anyDouble(), any(RNG.class), - anyInt(), anyInt(), eq(data), eq(complex))).thenReturn(new KList<>(List.of(grass, dirt))); + anyInt(), anyInt(), MockPackData.runtimeOf(data), eq(complex))).thenReturn(new KList<>(List.of(grass, dirt))); when(biome.generateCeilingLayers(eq(dimension), anyDouble(), anyDouble(), any(RNG.class), - anyInt(), anyInt(), eq(data), eq(complex))).thenReturn(new KList<>()); + anyInt(), anyInt(), MockPackData.runtimeOf(data), eq(complex))).thenReturn(new KList<>()); } private Hunk actuate() { diff --git a/core/src/test/java/art/arcane/iris/generation/stage/IrisTerrainNormalActuatorColumnParityTest.java b/core/src/test/java/art/arcane/iris/generation/stage/IrisTerrainNormalActuatorColumnParityTest.java index 0ba482ba3..1603b8614 100644 --- a/core/src/test/java/art/arcane/iris/generation/stage/IrisTerrainNormalActuatorColumnParityTest.java +++ b/core/src/test/java/art/arcane/iris/generation/stage/IrisTerrainNormalActuatorColumnParityTest.java @@ -1,5 +1,7 @@ package art.arcane.iris.generation.stage; +import art.arcane.iris.generation.runtime.PackRuntime; +import art.arcane.iris.testsupport.MockPackData; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.block.B; import art.arcane.iris.generation.block.IrisBlockData; @@ -41,6 +43,7 @@ import java.util.List; import java.util.Map; import java.util.Random; +import static org.mockito.ArgumentMatchers.same; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -110,7 +113,7 @@ public class IrisTerrainNormalActuatorColumnParityTest { private final Engine engine = mock(Engine.class); private final ChunkContext context = mock(ChunkContext.class); private final IrisComplex complex = mock(IrisComplex.class); - private final IrisData data = mock(IrisData.class); + private final IrisData data = MockPackData.create(); private final IrisBiome biome = mock(IrisBiome.class); private final IrisRegion region = new IrisRegion(); private final IrisDimension dimension; @@ -203,11 +206,11 @@ public class IrisTerrainNormalActuatorColumnParityTest { when(context.getFluid()).thenReturn(new ChunkedDataCache<>( ProceduralStream.of((x, z) -> fluid, Interpolated.of(value -> 0D, value -> fluid)), X, Z, false)); when(biome.generateLayers(eq(dimension), anyDouble(), anyDouble(), any(RNG.class), - anyInt(), anyInt(), eq(data), eq(complex))).thenAnswer(invocation -> layers(gravityLayers ? "sand" : "layer", layerCount)); - when(biome.generateSeaLayers(anyDouble(), anyDouble(), any(RNG.class), anyInt(), eq(data))) + anyInt(), anyInt(), MockPackData.runtimeOf(data), eq(complex))).thenAnswer(invocation -> layers(gravityLayers ? "sand" : "layer", layerCount)); + when(biome.generateSeaLayers(anyDouble(), anyDouble(), any(RNG.class), anyInt(), MockPackData.runtimeOf(data))) .thenAnswer(invocation -> layers("sea", seaCount)); when(biome.generateCeilingLayers(eq(dimension), anyDouble(), anyDouble(), any(RNG.class), - anyInt(), anyInt(), eq(data), eq(complex))).thenAnswer(invocation -> layers("ceiling", ceilingCount)); + anyInt(), anyInt(), MockPackData.runtimeOf(data), eq(complex))).thenAnswer(invocation -> layers("ceiling", ceilingCount)); when(biome.getSurfaceOreBands()).thenReturn(IrisOreBands.of(biomeSurface)); when(biome.getUndergroundOreBands()).thenReturn(IrisOreBands.of(biomeUnderground)); description = "he=" + he + " fluid=" + surfaceFluid + " bedrock=" + bedrock + " mapped=" + (mapped != null) @@ -306,7 +309,7 @@ public class IrisTerrainNormalActuatorColumnParityTest { if (i > he && i <= hf) { int fdepth = hf - i; if (seaFloor && fblocks == null) { - fblocks = biome.generateSeaLayers(realX, realZ, rng, hf - he, data); + fblocks = biome.generateSeaLayers(realX, realZ, rng, hf - he, data.standalonePackRuntime()); } h.setRaw(xf, i, zf, HydrologyFluidLayerSelector.select(fblocks, fdepth, columnFluid, !seaFloor || openUnderFall)); continue; @@ -319,11 +322,11 @@ public class IrisTerrainNormalActuatorColumnParityTest { } if (blocks == null) { blocks = biome.generateLayers(dimension, realX, realZ, rng, - layerSurfaceY, layerSurfaceY, data, complex); + layerSurfaceY, layerSurfaceY, data.standalonePackRuntime(), complex); } if (layerCeilingY > 0 && depth >= 2 && i - layerCeilingY < 2) { if (ceilingBlocks == null) { - ceilingBlocks = biome.generateCeilingLayers(dimension, realX, realZ, rng, 2, layerCeilingY, data, complex); + ceilingBlocks = biome.generateCeilingLayers(dimension, realX, realZ, rng, 2, layerCeilingY, data.standalonePackRuntime(), complex); } int ceilingDepth = i - layerCeilingY; h.setRaw(xf, i, zf, ceilingBlocks.hasIndex(ceilingDepth) ? ceilingBlocks.get(ceilingDepth) : rock); @@ -356,7 +359,7 @@ public class IrisTerrainNormalActuatorColumnParityTest { private NativeBlockState scan(KList ores, int x, int y, int z) { for (IrisOreGenerator ore : ores) { - NativeBlockState state = ore.generate(x, y, z, rng, data); + NativeBlockState state = ore.generate(x, y, z, rng, PackRuntime.standalone(data)); if (state != null) { return state; } @@ -376,7 +379,7 @@ public class IrisTerrainNormalActuatorColumnParityTest { IrisMaterialPalette palette = mock(IrisMaterialPalette.class); NativeBlockState block = state(name); palettes.put(name, block); - when(palette.get(any(RNG.class), anyDouble(), anyDouble(), anyDouble(), eq(data))).thenReturn(block); + when(palette.get(any(RNG.class), anyDouble(), anyDouble(), anyDouble(), MockPackData.runtimeOf(data))).thenReturn(block); return palette; } diff --git a/core/src/test/java/art/arcane/iris/generation/stage/IrisTerrainNormalActuatorHydrologyTest.java b/core/src/test/java/art/arcane/iris/generation/stage/IrisTerrainNormalActuatorHydrologyTest.java index 19f597406..a73e5e177 100644 --- a/core/src/test/java/art/arcane/iris/generation/stage/IrisTerrainNormalActuatorHydrologyTest.java +++ b/core/src/test/java/art/arcane/iris/generation/stage/IrisTerrainNormalActuatorHydrologyTest.java @@ -1,5 +1,7 @@ package art.arcane.iris.generation.stage; +import art.arcane.iris.generation.runtime.PackRuntime; +import art.arcane.iris.testsupport.MockPackData; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.context.ChunkContext; import art.arcane.iris.generation.context.ChunkedDataCache; @@ -29,6 +31,7 @@ import org.junit.Before; import java.util.ArrayList; import java.util.List; +import static org.mockito.ArgumentMatchers.same; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; @@ -182,7 +185,7 @@ public class IrisTerrainNormalActuatorHydrologyTest { for (int y = GROUND + 1; y < HEAD; y++) { assertSame("the mouth holds the sea fluid at y " + y, mouth.sea, estuary.get(0, y, 0)); } - verify(mouth.biome).generateSeaLayers(anyDouble(), anyDouble(), any(RNG.class), eq(HEAD - GROUND), eq(mouth.data)); + verify(mouth.biome).generateSeaLayers(anyDouble(), anyDouble(), any(RNG.class), eq(HEAD - GROUND), MockPackData.runtimeOf(mouth.data)); Painter frozenMouth = new Painter(WaterRole.MOUTH, HEAD); when(frozenMouth.complex.resolveWaterFluid(11, -4)).thenReturn(frozenMouth.sea); @@ -402,7 +405,7 @@ public class IrisTerrainNormalActuatorHydrologyTest { private static final class Painter { private final Engine engine = mock(Engine.class); private final IrisComplex complex = mock(IrisComplex.class); - private final IrisData data = mock(IrisData.class); + private final IrisData data = MockPackData.create(); private final IrisBiome biome = mock(IrisBiome.class); private final IrisRegion region = new IrisRegion(); private final ChunkContext context = mock(ChunkContext.class); @@ -439,7 +442,7 @@ public class IrisTerrainNormalActuatorHydrologyTest { ProceduralStream.of((x, z) -> rock, Interpolated.of(value -> 0D, value -> rock)), 11, -4, false)); when(context.getFluid()).thenReturn(new ChunkedDataCache<>( ProceduralStream.of((x, z) -> sea, Interpolated.of(value -> 0D, value -> sea)), 11, -4, false)); - when(biome.generateSeaLayers(anyDouble(), anyDouble(), any(RNG.class), anyInt(), eq(data))) + when(biome.generateSeaLayers(anyDouble(), anyDouble(), any(RNG.class), anyInt(), MockPackData.runtimeOf(data))) .thenAnswer(invocation -> new KList<>(List.of(ice))); layers(grass, dirt); } @@ -453,7 +456,7 @@ public class IrisTerrainNormalActuatorHydrologyTest { } private void thickSeaLayers() { - when(biome.generateSeaLayers(anyDouble(), anyDouble(), any(RNG.class), anyInt(), eq(data))).thenAnswer(invocation -> { + when(biome.generateSeaLayers(anyDouble(), anyDouble(), any(RNG.class), anyInt(), MockPackData.runtimeOf(data))).thenAnswer(invocation -> { KList layers = new KList<>(); for (int layer = 0; layer < (int) invocation.getArgument(3); layer++) { layers.add(ice); @@ -475,12 +478,12 @@ public class IrisTerrainNormalActuatorHydrologyTest { when(complex.terrainColumn(11, -4)).thenReturn(carved); when(complex.naturalTerrainColumn(11, -4)).thenReturn(natural); when(biome.generateCeilingLayers(eq(dimension), anyDouble(), anyDouble(), any(RNG.class), - anyInt(), anyInt(), eq(data), eq(complex))).thenReturn(new KList<>()); + anyInt(), anyInt(), MockPackData.runtimeOf(data), eq(complex))).thenReturn(new KList<>()); } private void layers(NativeBlockState top, NativeBlockState second) { when(biome.generateLayers(eq(dimension), anyDouble(), anyDouble(), any(RNG.class), - anyInt(), anyInt(), eq(data), eq(complex))).thenAnswer(invocation -> new KList<>(List.of(top, second))); + anyInt(), anyInt(), MockPackData.runtimeOf(data), eq(complex))).thenAnswer(invocation -> new KList<>(List.of(top, second))); } private IrisHydrologyMaterials materials(boolean palettes) { @@ -494,7 +497,7 @@ public class IrisTerrainNormalActuatorHydrologyTest { private IrisMaterialPalette palette(NativeBlockState block) { IrisMaterialPalette palette = mock(IrisMaterialPalette.class); - when(palette.get(any(RNG.class), anyDouble(), anyDouble(), anyDouble(), eq(data))).thenReturn(block); + when(palette.get(any(RNG.class), anyDouble(), anyDouble(), anyDouble(), MockPackData.runtimeOf(data))).thenReturn(block); return palette; } diff --git a/core/src/test/java/art/arcane/iris/generation/subterrain/SubterrainSurfaceMaterialsTest.java b/core/src/test/java/art/arcane/iris/generation/subterrain/SubterrainSurfaceMaterialsTest.java index 3416fd953..61c4de7d7 100644 --- a/core/src/test/java/art/arcane/iris/generation/subterrain/SubterrainSurfaceMaterialsTest.java +++ b/core/src/test/java/art/arcane/iris/generation/subterrain/SubterrainSurfaceMaterialsTest.java @@ -1,5 +1,7 @@ package art.arcane.iris.generation.subterrain; +import art.arcane.iris.generation.runtime.PackRuntime; +import art.arcane.iris.testsupport.MockPackData; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.biome.IrisBiomePaletteLayer; import art.arcane.iris.generation.decoration.IrisDecorationPart; @@ -37,6 +39,7 @@ import java.util.EnumMap; import java.util.List; import java.util.Map; +import static org.mockito.ArgumentMatchers.same; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; @@ -235,7 +238,7 @@ public class SubterrainSurfaceMaterialsTest { private final NativeBlockState wall = solid("minecraft:andesite"); private final IrisDimension dimension = new IrisDimension(); private final IrisComplex complex = mock(IrisComplex.class); - private final IrisData data = mock(IrisData.class); + private final IrisData data = MockPackData.create(); private final IrisBiome biome = mock(IrisBiome.class); private final RNG random = new RNG(44339L); private final SubterrainPlanner planner; @@ -261,8 +264,8 @@ public class SubterrainSurfaceMaterialsTest { when(biome.getDecoratorBucket(IrisDecorationPart.NONE)).thenReturn(new IrisDecorator[0]); IrisBiomePaletteLayer wallPalette = mock(IrisBiomePaletteLayer.class); when(biome.getWall()).thenReturn(wallPalette); - when(wallPalette.get(eq(random), anyDouble(), anyDouble(), anyDouble(), eq(data))).thenReturn(wall); - when(biome.generateCeilingLayers(eq(dimension), anyDouble(), anyDouble(), eq(random), eq(1), anyInt(), eq(data), eq(complex))) + when(wallPalette.get(eq(random), anyDouble(), anyDouble(), anyDouble(), MockPackData.runtimeOf(data))).thenReturn(wall); + when(biome.generateCeilingLayers(eq(dimension), anyDouble(), anyDouble(), eq(random), eq(1), anyInt(), MockPackData.runtimeOf(data), eq(complex))) .thenReturn(new KList<>(ceiling)); floorPalette(floor); NativeBlockState air = mock(NativeBlockState.class); @@ -335,12 +338,12 @@ public class SubterrainSurfaceMaterialsTest { } private void floorPalette(NativeBlockState state) { - when(biome.generateLayers(eq(dimension), anyDouble(), anyDouble(), eq(random), eq(1), anyInt(), eq(data), eq(complex))) + when(biome.generateLayers(eq(dimension), anyDouble(), anyDouble(), eq(random), eq(1), anyInt(), MockPackData.runtimeOf(data), eq(complex))) .thenReturn(state == null ? new KList<>() : new KList<>(state)); } private SubterrainSurfaceMaterials materials(List candidates) { - return new SubterrainSurfaceMaterials(planner, candidates, dimension, complex, data, random, -64); + return new SubterrainSurfaceMaterials(planner, candidates, dimension, complex, data.standalonePackRuntime(), random, -64); } private SubterrainCell cell(SubterrainPosition position) { diff --git a/core/src/test/java/art/arcane/iris/generation/terrain/ContinentGeneratorTest.java b/core/src/test/java/art/arcane/iris/generation/terrain/ContinentGeneratorTest.java index de74d930d..994d7476c 100644 --- a/core/src/test/java/art/arcane/iris/generation/terrain/ContinentGeneratorTest.java +++ b/core/src/test/java/art/arcane/iris/generation/terrain/ContinentGeneratorTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.terrain; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.NoiseStyle; import art.arcane.iris.pack.loading.IrisData; @@ -91,11 +92,11 @@ public class ContinentGeneratorTest { } private double[] sampleSharedStyleGenerator(IrisGeneratorStyle style) { - return sampleSharedGenerator(style, ContinentGenerator.deriveContinentSeed(new RNG(WORLD_SEED)), packData); + return sampleSharedGenerator(style, ContinentGenerator.deriveContinentSeed(new RNG(WORLD_SEED)), PackRuntime.of(packData.getEngine(), packData)); } private double[] sampleContinentMap(IrisDimension dimension, double[][] blocks) { - return sampleAtBlocks(ContinentGenerator.create(dimension, new RNG(WORLD_SEED), packData), blocks); + return sampleAtBlocks(ContinentGenerator.create(dimension, new RNG(WORLD_SEED), PackRuntime.of(packData.getEngine(), packData)), blocks); } private static double[][] shrinkByContinentZoom(double[][] blocks) { diff --git a/core/src/test/java/art/arcane/iris/generation/terrain/IrisDimensionCarvingEntryTest.java b/core/src/test/java/art/arcane/iris/generation/terrain/IrisDimensionCarvingEntryTest.java index 0cd2b7977..54875831a 100644 --- a/core/src/test/java/art/arcane/iris/generation/terrain/IrisDimensionCarvingEntryTest.java +++ b/core/src/test/java/art/arcane/iris/generation/terrain/IrisDimensionCarvingEntryTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.terrain; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.NoiseStyle; import art.arcane.iris.pack.loading.IrisData; @@ -25,7 +26,7 @@ public class IrisDimensionCarvingEntryTest { } private double[] sampleSharedChildStyleGeneratorAfterChildrenGeneratorBuilt() { - carvingEntry.getChildrenGenerator(WORLD_SEED, packData); + carvingEntry.getChildrenGenerator(WORLD_SEED, PackRuntime.of(packData.getEngine(), packData)); return sampleSharedChildStyleGenerator(carvingEntry.getChildStyle()); } @@ -34,7 +35,7 @@ public class IrisDimensionCarvingEntryTest { } private double[] sampleSharedChildStyleGenerator(IrisGeneratorStyle childStyle) { - return sampleSharedGenerator(childStyle, deriveSharedChildStyleSeed(), packData); + return sampleSharedGenerator(childStyle, deriveSharedChildStyleSeed(), PackRuntime.of(packData.getEngine(), packData)); } private RNG deriveSharedChildStyleSeed() { diff --git a/core/src/test/java/art/arcane/iris/generation/terrain/IrisDimensionCarvingResolverParityTest.java b/core/src/test/java/art/arcane/iris/generation/terrain/IrisDimensionCarvingResolverParityTest.java index 28bff4309..c71faac5b 100644 --- a/core/src/test/java/art/arcane/iris/generation/terrain/IrisDimensionCarvingResolverParityTest.java +++ b/core/src/test/java/art/arcane/iris/generation/terrain/IrisDimensionCarvingResolverParityTest.java @@ -1,5 +1,7 @@ package art.arcane.iris.generation.terrain; +import art.arcane.iris.generation.runtime.PackRuntime; +import art.arcane.iris.testsupport.MockPackData; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.pack.value.IrisRange; @@ -115,7 +117,7 @@ public class IrisDimensionCarvingResolverParityTest { dimension.getCarvingEntryIndex().put("root-low", parent); CNG generator = mock(CNG.class); doReturn(0.5D, 0D).when(generator).noiseFast2D(-17D, 23D); - doReturn(generator).when(parent).getChildrenGenerator(anyLong(), any(IrisData.class)); + doReturn(generator).when(parent).getChildrenGenerator(anyLong(), any(PackRuntime.class)); IrisDimensionCarvingResolver.Snapshot snapshot = IrisDimensionCarvingResolver.snapshot(fixture.engine); assertSame(fixture.engine.getData().getBiomeLoader().load("root-low"), snapshot.resolveBiome(-17, 40, 23)); @@ -139,7 +141,7 @@ public class IrisDimensionCarvingResolverParityTest { parent.setChildRecursionDepth(1); CNG generator = mock(CNG.class); doReturn(0.5D).when(generator).noiseFast2D(-17D, 23D); - doReturn(generator).when(parent).getChildrenGenerator(anyLong(), any(IrisData.class)); + doReturn(generator).when(parent).getChildrenGenerator(anyLong(), any(PackRuntime.class)); IrisDimensionCarvingEntry selected = IrisDimensionCarvingResolver.resolveFromRoot( engine, parent, -17, -1500, 23, new IrisDimensionCarvingResolver.State()); @@ -159,7 +161,7 @@ public class IrisDimensionCarvingResolverParityTest { child.setWorldYRange(new IrisRange(-20, 20)); CNG generator = mock(CNG.class); doReturn(0.5D).when(generator).noiseFast2D(anyDouble(), anyDouble()); - doReturn(generator).when(parent).getChildrenGenerator(anyLong(), any(IrisData.class)); + doReturn(generator).when(parent).getChildrenGenerator(anyLong(), any(PackRuntime.class)); IrisDimensionCarvingResolver.State state = new IrisDimensionCarvingResolver.State(); assertSame(child, IrisDimensionCarvingResolver.resolveFromRoot(fixture.engine, parent, 7, 0, 9, state)); assertSame(parent, IrisDimensionCarvingResolver.resolveFromRoot(fixture.engine, parent, 7, 30, 9, state)); @@ -175,7 +177,7 @@ public class IrisDimensionCarvingResolverParityTest { parent.setChildren(new KList<>(children)); CNG generator = mock(CNG.class); doReturn(0.5D).when(generator).noiseFast2D(anyDouble(), anyDouble()); - doReturn(generator).when(parent).getChildrenGenerator(anyLong(), any(IrisData.class)); + doReturn(generator).when(parent).getChildrenGenerator(anyLong(), any(PackRuntime.class)); IrisDimensionCarvingResolver.State state = new IrisDimensionCarvingResolver.State(); for (int worldY = -80; worldY < 140; worldY += 13) { @@ -199,7 +201,7 @@ public class IrisDimensionCarvingResolverParityTest { parent.setChildRecursionDepth(1); CNG generator = mock(CNG.class); doReturn(0.5D).when(generator).noiseFast2D(anyDouble(), anyDouble()); - doReturn(generator).when(parent).getChildrenGenerator(anyLong(), any(IrisData.class)); + doReturn(generator).when(parent).getChildrenGenerator(anyLong(), any(PackRuntime.class)); IrisDimensionCarvingEntry child = fixture.engine.getDimension().getCarvingEntryIndex().get("child-a"); IrisDimensionCarvingResolver.State state = new IrisDimensionCarvingResolver.State(); @@ -227,7 +229,7 @@ public class IrisDimensionCarvingResolverParityTest { } CNG generator = mock(CNG.class); doReturn(0.5D, 0D).when(generator).noiseFast2D(-17D, 23D); - doReturn(generator).when(parent).getChildrenGenerator(anyLong(), any(IrisData.class)); + doReturn(generator).when(parent).getChildrenGenerator(anyLong(), any(PackRuntime.class)); IrisDimensionCarvingEntry child = fixture.engine.getDimension().getCarvingEntryIndex().get("child-a"); IrisDimensionCarvingResolver.State state = new IrisDimensionCarvingResolver.State(); @@ -244,7 +246,7 @@ public class IrisDimensionCarvingResolverParityTest { parent.setChildRecursionDepth(1); CNG generator = mock(CNG.class); doReturn(0.5D).when(generator).noiseFast2D(anyDouble(), anyDouble()); - doReturn(generator).when(parent).getChildrenGenerator(anyLong(), any(IrisData.class)); + doReturn(generator).when(parent).getChildrenGenerator(anyLong(), any(PackRuntime.class)); IrisDimensionCarvingResolver.State state = new IrisDimensionCarvingResolver.State(); IrisDimensionCarvingEntry firstChild = fixture.engine.getDimension().getCarvingEntryIndex().get("child-a"); IrisDimensionCarvingEntry replacementChild = replacement.engine.getDimension().getCarvingEntryIndex().get("child-a"); @@ -395,7 +397,7 @@ public class IrisDimensionCarvingResolverParityTest { Fixture fixture = createFixture(); Engine engine = fixture.engine; IrisData firstData = engine.getData(); - IrisData replacementData = mock(IrisData.class); + IrisData replacementData = MockPackData.create(); IrisDimensionCarvingEntry entry = mock(IrisDimensionCarvingEntry.class); IrisBiome firstBiome = new IrisBiome(); IrisBiome replacementBiome = new IrisBiome(); @@ -430,7 +432,7 @@ public class IrisDimensionCarvingResolverParityTest { Fixture fixture = createFixture(); IrisData firstData = fixture.engine.getData(); IrisDimension dimension = fixture.engine.getDimension(); - IrisData replacementData = mock(IrisData.class); + IrisData replacementData = MockPackData.create(); IrisDimensionCarvingEntry entry = mock(IrisDimensionCarvingEntry.class); IrisBiome firstBiome = new IrisBiome(); IrisBiome replacementBiome = new IrisBiome(); @@ -470,12 +472,12 @@ public class IrisDimensionCarvingResolverParityTest { } @Test(timeout = 20_000L) - public void longLivedWorkerDoesNotRetainPopulatedThreadLocalStateOrEngine() throws Exception { + public void longLivedWorkerDoesNotRetainPopulatedResolverStateOrEngine() throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); CountDownLatch blockerStarted = new CountDownLatch(1); CountDownLatch releaseBlocker = new CountDownLatch(1); try { - LifetimeReferences references = executor.submit(this::populateThreadLocalLifetimeReferences).get(); + LifetimeReferences references = executor.submit(this::populateResolverStateLifetimeReferences).get(); Future blocker = executor.submit(() -> { blockerStarted.countDown(); releaseBlocker.await(); @@ -494,31 +496,22 @@ public class IrisDimensionCarvingResolverParityTest { } } - private LifetimeReferences populateThreadLocalLifetimeReferences() throws Exception { + private LifetimeReferences populateResolverStateLifetimeReferences() throws Exception { RetainedFixture fixture = createRetainedFixture(); assertNotNull(IrisDimensionCarvingResolver.resolveRootEntry(fixture.engine(), 80)); - Field threadStateField = IrisDimensionCarvingResolver.class.getDeclaredField("THREAD_STATE"); - threadStateField.setAccessible(true); - ThreadLocal threadState = (ThreadLocal) threadStateField.get(null); - Object value = threadState.get(); - assertTrue(value instanceof WeakReference); - @SuppressWarnings("unchecked") - WeakReference state = - (WeakReference) value; - IrisDimensionCarvingResolver.State populatedState = state.get(); - assertNotNull(populatedState); + IrisDimensionCarvingResolver.State populatedState = fixture.engine().getPackRuntime().carvingResolverState(); Field biomeCacheField = IrisDimensionCarvingResolver.State.class.getDeclaredField("biomeCache"); biomeCacheField.setAccessible(true); assertFalse(((Map) biomeCacheField.get(populatedState)).isEmpty()); return new LifetimeReferences( - state, + new WeakReference<>(populatedState), new WeakReference<>(fixture.engine())); } private static void awaitCollection(LifetimeReferences references) { AtomicInteger attempt = new AtomicInteger(); - Await.reached("the thread-local State and Engine to be collected", Duration.ofSeconds(5L), () -> { + Await.reached("the resolver State and Engine to be collected", Duration.ofSeconds(5L), () -> { System.gc(); if (references.state().get() == null && references.engine().get() == null) { @@ -528,7 +521,7 @@ public class IrisDimensionCarvingResolverParityTest { pressure[0] = (byte) attempt.incrementAndGet(); return false; }); - assertTrue("Thread-local State was retained", references.state().get() == null); + assertTrue("Resolver State was retained", references.state().get() == null); assertTrue("Engine was retained", references.engine().get() == null); } @@ -547,7 +540,7 @@ public class IrisDimensionCarvingResolverParityTest { } private RetainedFixture createRetainedFixture() { - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); IrisBiome biome = new IrisBiome(); biome.setLoader(data); @@ -564,17 +557,20 @@ public class IrisDimensionCarvingResolverParityTest { IrisDimension dimension = new IrisDimension(); dimension.setCarving(carvingEntries); + AtomicReference runtime = new AtomicReference<>(); Engine engine = (Engine) Proxy.newProxyInstance( Engine.class.getClassLoader(), new Class[]{Engine.class}, (proxy, method, arguments) -> switch (method.getName()) { case "getDimension" -> dimension; case "getData" -> data; + case "getPackRuntime" -> runtime.get(); case "hashCode" -> System.identityHashCode(proxy); case "equals" -> proxy == arguments[0]; case "toString" -> "carving-retention-test-engine"; default -> throw new UnsupportedOperationException(method.toString()); }); + runtime.set(PackRuntime.forEngine(engine, data)); return new RetainedFixture(engine, entry); } @@ -602,7 +598,7 @@ public class IrisDimensionCarvingResolverParityTest { doReturn(childBBiome).when(biomeLoader).load("child-b"); doReturn(childCBiome).when(biomeLoader).load("child-c"); - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); doReturn(biomeLoader).when(data).getBiomeLoader(); IrisDimensionCarvingEntry rootLow = buildEntry("root-low", "root-low", new IrisRange(-64, 120), 4, List.of("child-a", "child-b")); @@ -678,7 +674,7 @@ public class IrisDimensionCarvingResolverParityTest { doReturn(childFBiome).when(biomeLoader).load("child-f"); doReturn(childGBiome).when(biomeLoader).load("child-g"); - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); doReturn(biomeLoader).when(data).getBiomeLoader(); IrisDimensionCarvingEntry rootLow = buildEntry("root-low", "root-low", new IrisRange(-64, 120), 7, List.of("child-a", "child-d", "child-e")); @@ -872,7 +868,7 @@ public class IrisDimensionCarvingResolverParityTest { } long seed = engine.getSeedManager().getCarve() ^ CHILD_SEED_SALT; - CNG childGenerator = parent.getChildrenGenerator(seed, engine.getData()); + CNG childGenerator = parent.getChildrenGenerator(seed, PackRuntime.of(engine)); LegacyCarvingChoice selected = childGenerator.fitRarity(options, worldX, worldZ); if (selected == null || selected.entry == null) { return parent; diff --git a/core/src/test/java/art/arcane/iris/generation/terrain/IrisMaterialPaletteGeneratorCacheTest.java b/core/src/test/java/art/arcane/iris/generation/terrain/IrisMaterialPaletteGeneratorCacheTest.java index 4263289d8..c84ac1632 100644 --- a/core/src/test/java/art/arcane/iris/generation/terrain/IrisMaterialPaletteGeneratorCacheTest.java +++ b/core/src/test/java/art/arcane/iris/generation/terrain/IrisMaterialPaletteGeneratorCacheTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.generation.terrain; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.pack.loading.IrisData; @@ -29,17 +30,17 @@ public final class IrisMaterialPaletteGeneratorCacheTest { public void callerSeedsDoNotShareAFirstWinnerGenerator() { GeneratorFixture fixture = new GeneratorFixture(); - assertSame(fixture.firstGenerator, fixture.palette.getLayerGenerator(new RNG(11L), fixture.data)); - assertSame(fixture.secondGenerator, fixture.palette.getLayerGenerator(new RNG(29L), fixture.data)); - assertSame(fixture.firstGenerator, fixture.palette.getLayerGenerator(new RNG(11L), fixture.data)); + assertSame(fixture.firstGenerator, fixture.palette.getLayerGenerator(new RNG(11L), fixture.runtime)); + assertSame(fixture.secondGenerator, fixture.palette.getLayerGenerator(new RNG(29L), fixture.runtime)); + assertSame(fixture.firstGenerator, fixture.palette.getLayerGenerator(new RNG(11L), fixture.runtime)); } @Test public void reverseInitializationOrderKeepsSeedAssignments() { GeneratorFixture fixture = new GeneratorFixture(); - assertSame(fixture.secondGenerator, fixture.palette.getLayerGenerator(new RNG(29L), fixture.data)); - assertSame(fixture.firstGenerator, fixture.palette.getLayerGenerator(new RNG(11L), fixture.data)); + assertSame(fixture.secondGenerator, fixture.palette.getLayerGenerator(new RNG(29L), fixture.runtime)); + assertSame(fixture.firstGenerator, fixture.palette.getLayerGenerator(new RNG(11L), fixture.runtime)); } @Test @@ -50,11 +51,11 @@ public final class IrisMaterialPaletteGeneratorCacheTest { try { Future first = executor.submit(() -> { assertTrue(start.await(5L, TimeUnit.SECONDS)); - return fixture.palette.getLayerGenerator(new RNG(11L), fixture.data); + return fixture.palette.getLayerGenerator(new RNG(11L), fixture.runtime); }); Future second = executor.submit(() -> { assertTrue(start.await(5L, TimeUnit.SECONDS)); - return fixture.palette.getLayerGenerator(new RNG(29L), fixture.data); + return fixture.palette.getLayerGenerator(new RNG(29L), fixture.runtime); }); start.countDown(); @@ -67,19 +68,18 @@ public final class IrisMaterialPaletteGeneratorCacheTest { private static final class GeneratorFixture { private final IrisData data = mock(IrisData.class); - private final Engine engine = mock(Engine.class); + private final PackRuntime runtime = PackRuntime.forEngine(mock(Engine.class), data); private final IrisGeneratorStyle style = mock(IrisGeneratorStyle.class); private final CNG firstGenerator = mock(CNG.class); private final CNG secondGenerator = mock(CNG.class); private final IrisMaterialPalette palette = new IrisMaterialPalette().qclear().setStyle(style); private GeneratorFixture() { - when(data.getEngine()).thenReturn(engine); Map generators = Map.of( 11L + GENERATOR_SALT, firstGenerator, 29L + GENERATOR_SALT, secondGenerator ); - when(style.create(any(RNG.class), same(data), same(engine))).thenAnswer(invocation -> { + when(style.createNoCache(any(RNG.class), any())).thenAnswer(invocation -> { RNG rng = invocation.getArgument(0); return generators.get(rng.getSeed()); }); diff --git a/core/src/test/java/art/arcane/iris/generation/terrain/TerrainFieldSeedCohesionTest.java b/core/src/test/java/art/arcane/iris/generation/terrain/TerrainFieldSeedCohesionTest.java index 93d88a9e3..c13633aed 100644 --- a/core/src/test/java/art/arcane/iris/generation/terrain/TerrainFieldSeedCohesionTest.java +++ b/core/src/test/java/art/arcane/iris/generation/terrain/TerrainFieldSeedCohesionTest.java @@ -1,5 +1,7 @@ package art.arcane.iris.generation.terrain; +import art.arcane.iris.generation.noise.GeneratorRuntime; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.noise.IrisGenerator; import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.noise.CNG; @@ -11,29 +13,14 @@ import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; public class TerrainFieldSeedCohesionTest { - @Test - public void coordinateFracturesSeparateSeedAndSignature() { - IrisDimension shared = new IrisDimension(); - for (long seed : new long[]{91L, 17L, 91L}) { - for (int signature : new int[]{73, 211}) { - CNG expected = new IrisDimension().getCoordFracture(new RNG(seed), signature); - CNG actual = shared.getCoordFracture(new RNG(seed), signature); - for (int index = 0; index < 8; index++) { - assertEquals(expected.noise(index * 128D - 600D, index * -251D + 300D), - actual.noise(index * 128D - 600D, index * -251D + 300D), 0D); - } - } - } - } - @Test public void cellGeneratorsRetainSeedAssignments() { - IrisGenerator generator = new IrisGenerator(); - CellGenerator first = generator.getCellGenerator(17L); - CellGenerator second = generator.getCellGenerator(91L); + GeneratorRuntime generator = PackRuntime.standalone(null).generator(new IrisGenerator()); + CellGenerator first = generator.cellGenerator(17L); + CellGenerator second = generator.cellGenerator(91L); assertNotSame(first, second); - assertSame(first, generator.getCellGenerator(17L)); - CellGenerator expected = new IrisGenerator().getCellGenerator(91L); + assertSame(first, generator.cellGenerator(17L)); + CellGenerator expected = PackRuntime.standalone(null).generator(new IrisGenerator()).cellGenerator(91L); assertEquals(expected.getDistance(17D, -81D), second.getDistance(17D, -81D), 0D); } } diff --git a/core/src/test/java/art/arcane/iris/pack/datapack/export/compile/biome/IrisSelectionReference.java b/core/src/test/java/art/arcane/iris/pack/datapack/export/compile/biome/IrisSelectionReference.java index c17a1818f..19ceb1686 100644 --- a/core/src/test/java/art/arcane/iris/pack/datapack/export/compile/biome/IrisSelectionReference.java +++ b/core/src/test/java/art/arcane/iris/pack/datapack/export/compile/biome/IrisSelectionReference.java @@ -1,5 +1,6 @@ package art.arcane.iris.pack.datapack.export.compile.biome; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.stream.RarityStream; import art.arcane.iris.generation.terrain.ContinentGenerator; @@ -40,15 +41,15 @@ final class IrisSelectionReference { loaded.add(region); } } - regions = new RarityStream<>(dimension.getRegionStyle().create(rng.nextParallelRNG(883), data).stream().zoom(dimension.getRegionZoom()), loaded); - continent = ContinentGenerator.create(dimension, rng, data); + regions = new RarityStream<>(dimension.getRegionStyle().create(rng.nextParallelRNG(883), PackRuntime.standalone(data)).stream().zoom(dimension.getRegionZoom()), loaded); + continent = ContinentGenerator.create(dimension, rng, PackRuntime.standalone(data)); for (IrisRegion region : loaded) { Map> streams = new EnumMap<>(InferredType.class); - streams.put(InferredType.LAND, new RarityStream<>(dimension.getLandBiomeStyle().create(rng.nextParallelRNG(InferredType.LAND.ordinal()), data).stream() + streams.put(InferredType.LAND, new RarityStream<>(dimension.getLandBiomeStyle().create(rng.nextParallelRNG(InferredType.LAND.ordinal()), PackRuntime.standalone(data)).stream() .zoom(dimension.getBiomeZoom()).zoom(dimension.getLandZoom()).zoom(region.getLandBiomeZoom()), pool(region.getLandBiomes()))); - streams.put(InferredType.SEA, new RarityStream<>(dimension.getSeaBiomeStyle().create(rng.nextParallelRNG(InferredType.SEA.ordinal()), data).stream() + streams.put(InferredType.SEA, new RarityStream<>(dimension.getSeaBiomeStyle().create(rng.nextParallelRNG(InferredType.SEA.ordinal()), PackRuntime.standalone(data)).stream() .zoom(dimension.getBiomeZoom()).zoom(dimension.getSeaZoom()).zoom(region.getSeaBiomeZoom()), pool(region.getSeaBiomes()))); - streams.put(InferredType.SHORE, new RarityStream<>(dimension.getShoreBiomeStyle().create(rng.nextParallelRNG(InferredType.SHORE.ordinal()), data).stream() + streams.put(InferredType.SHORE, new RarityStream<>(dimension.getShoreBiomeStyle().create(rng.nextParallelRNG(InferredType.SHORE.ordinal()), PackRuntime.standalone(data)).stream() .zoom(dimension.getBiomeZoom()).zoom(region.getShoreBiomeZoom()), pool(region.getShoreBiomes()))); picks.put(region, streams); } @@ -85,7 +86,7 @@ final class IrisSelectionReference { long maximum = selection.size() - 1L; IrisBiome selected = maximum <= 0L ? selection.get(0L) - : selection.get(biome.getChildrenGenerator(childStyleSeed, biome.getChildShrinkFactor()).fit2D(0, (int) maximum, x, z)); + : selection.get(biome.getChildrenGenerator(data.standalonePackRuntime(), childStyleSeed, biome.getChildShrinkFactor()).fit2D(0, (int) maximum, x, z)); if (selected.getLoadKey().equals(biome.getLoadKey())) { return biome; } diff --git a/core/src/test/java/art/arcane/iris/pack/datapack/export/compile/decoration/DecorationStageTest.java b/core/src/test/java/art/arcane/iris/pack/datapack/export/compile/decoration/DecorationStageTest.java index 640a81189..79a9c6309 100644 --- a/core/src/test/java/art/arcane/iris/pack/datapack/export/compile/decoration/DecorationStageTest.java +++ b/core/src/test/java/art/arcane/iris/pack/datapack/export/compile/decoration/DecorationStageTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.pack.datapack.export.compile.decoration; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.pack.datapack.DataVersion; import art.arcane.iris.pack.datapack.export.ExportTestPacks; @@ -461,7 +462,7 @@ public class DecorationStageTest { private static GatePattern irisPattern(String styleJson, double chance) { IrisGeneratorStyle style = new Gson().fromJson(styleJson, IrisGeneratorStyle.class); - CNG generator = style.create(new RNG(4242L), null); + CNG generator = style.create(new RNG(4242L), PackRuntime.standalone(null)); double zoom = style.getZoom(); return pattern((x, z) -> generator.fitDouble(0.0, 1.0, x / zoom, z / zoom) <= chance); } diff --git a/core/src/test/java/art/arcane/iris/pack/datapack/export/compile/noise/NoiseStyleCompilerTest.java b/core/src/test/java/art/arcane/iris/pack/datapack/export/compile/noise/NoiseStyleCompilerTest.java index d01bab761..e5551d69b 100644 --- a/core/src/test/java/art/arcane/iris/pack/datapack/export/compile/noise/NoiseStyleCompilerTest.java +++ b/core/src/test/java/art/arcane/iris/pack/datapack/export/compile/noise/NoiseStyleCompilerTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.pack.datapack.export.compile.noise; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.noise.IrisGenerator; import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.IrisNoiseGenerator; @@ -245,7 +246,7 @@ public final class NoiseStyleCompilerTest { NoiseRegistry registry = new NoiseRegistry("iris_export"); Field field = SMOOTH.compileLayer(layer, SEED, registry, CAPABILITIES); for (int x = -20; x <= 20; x += 10) { - assertEquals(layer.getNoise(SUPER_SEED, x, -x, null), sample(field, registry, x, -x), tolerance); + assertEquals(layer.getNoise(SUPER_SEED, x, -x, PackRuntime.standalone(null)), sample(field, registry, x, -x), tolerance); } } @@ -253,7 +254,7 @@ public final class NoiseStyleCompilerTest { NoiseRegistry registry = new NoiseRegistry("iris_export"); Field field = SMOOTH.compileComposite(generator, SEED, registry, CAPABILITIES); for (int x = -30; x <= 30; x += 15) { - assertEquals(generator.getHeight(x, 2 * x, SUPER_SEED), sample(field, registry, x, 2 * x), FLOAT_TOLERANCE); + assertEquals(generator.getHeight(PackRuntime.standalone(null), x, 2 * x, SUPER_SEED), sample(field, registry, x, 2 * x), FLOAT_TOLERANCE); } } diff --git a/core/src/test/java/art/arcane/iris/pack/datapack/export/compile/noise/SmoothNoiseFidelityTest.java b/core/src/test/java/art/arcane/iris/pack/datapack/export/compile/noise/SmoothNoiseFidelityTest.java index e9e4f1dbd..728c8507d 100644 --- a/core/src/test/java/art/arcane/iris/pack/datapack/export/compile/noise/SmoothNoiseFidelityTest.java +++ b/core/src/test/java/art/arcane/iris/pack/datapack/export/compile/noise/SmoothNoiseFidelityTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.pack.datapack.export.compile.noise; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.IrisNoiseGenerator; import art.arcane.iris.generation.noise.NoiseStyle; @@ -60,7 +61,7 @@ public final class SmoothNoiseFidelityTest { IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.SIMPLEX); NoiseRegistry registry = new NoiseRegistry(NAMESPACE); Field field = COMPILER.compile(style, SALT, registry, CAPABILITIES); - CNG iris = style.createNoCache(new RNG(IRIS_SEED), null); + CNG iris = style.createNoCache(new RNG(IRIS_SEED), PackRuntime.standalone(null)); double[] irisValues = grid((x, z) -> iris.noise(x, z), 0, 0, SIZE, STRIDE); double[] lowered = new double[0]; for (int window = 0; window < 4; window++) { @@ -76,7 +77,7 @@ public final class SmoothNoiseFidelityTest { IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.QUADOCTAVE_FRACTAL_FBM_SIMPLEX).zoomed(0.5); NoiseRegistry registry = new NoiseRegistry(NAMESPACE); Field field = COMPILER.compile(style, SALT, registry, CAPABILITIES); - CNG iris = style.createNoCache(new RNG(IRIS_SEED), null); + CNG iris = style.createNoCache(new RNG(IRIS_SEED), PackRuntime.standalone(null)); double[] irisSpectrum = new double[SIZE / 2]; double[] loweredSpectrum = new double[SIZE / 2]; for (int window = 0; window < WINDOWS.length; window++) { @@ -115,7 +116,7 @@ public final class SmoothNoiseFidelityTest { IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.NOWHERE).zoomed(0.5); NoiseRegistry registry = new NoiseRegistry(NAMESPACE); Field field = COMPILER.compile(style, SALT, registry, CAPABILITIES); - CNG iris = style.createNoCache(new RNG(IRIS_SEED), null); + CNG iris = style.createNoCache(new RNG(IRIS_SEED), PackRuntime.standalone(null)); long irisFragments = 0L; long loweredFragments = 0L; for (int window = 0; window < WINDOWS.length; window++) { diff --git a/core/src/test/java/art/arcane/iris/pack/datapack/export/compile/terrain/VolumetricCompilerTest.java b/core/src/test/java/art/arcane/iris/pack/datapack/export/compile/terrain/VolumetricCompilerTest.java index 796b92bb3..fd878c22c 100644 --- a/core/src/test/java/art/arcane/iris/pack/datapack/export/compile/terrain/VolumetricCompilerTest.java +++ b/core/src/test/java/art/arcane/iris/pack/datapack/export/compile/terrain/VolumetricCompilerTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.pack.datapack.export.compile.terrain; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.NoiseStyle; import art.arcane.iris.generation.terrain.IrisDimension; @@ -101,7 +102,7 @@ public class VolumetricCompilerTest { try { NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE); Compiled compiled = compile(data, registry, NoiseStyleCompiler.create(new ArrayList<>()), TerrainTestSupport.twoBiomeCodes(registry, 0.0)); - CNG iris = new IrisGeneratorStyle(NoiseStyle.SIMPLEX).createNoCache(new RNG(MARGINAL_SEED), data); + CNG iris = new IrisGeneratorStyle(NoiseStyle.SIMPLEX).createNoCache(new RNG(MARGINAL_SEED), PackRuntime.standalone(data)); SplittableRandom random = new SplittableRandom(MARGINAL_SEED); double[] exported = new double[MARGINAL_SAMPLES]; double[] expected = new double[MARGINAL_SAMPLES]; @@ -129,7 +130,7 @@ public class VolumetricCompilerTest { try { NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE); Compiled compiled = compile(data, registry, NoiseStyleCompiler.create(new ArrayList<>()), TerrainTestSupport.twoBiomeCodes(registry, 0.0)); - CNG iris = new IrisGeneratorStyle(NoiseStyle.SIMPLEX).createNoCache(new RNG(MARGINAL_SEED), data); + CNG iris = new IrisGeneratorStyle(NoiseStyle.SIMPLEX).createNoCache(new RNG(MARGINAL_SEED), PackRuntime.standalone(data)); SplittableRandom random = new SplittableRandom(MARGINAL_SEED); int exported = 0; int expected = 0; diff --git a/core/src/test/java/art/arcane/iris/pack/loading/IrisDataCloseLoadedUnderTest.java b/core/src/test/java/art/arcane/iris/pack/loading/IrisDataCloseLoadedUnderTest.java new file mode 100644 index 000000000..682768c80 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/pack/loading/IrisDataCloseLoadedUnderTest.java @@ -0,0 +1,48 @@ +package art.arcane.iris.pack.loading; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +public class IrisDataCloseLoadedUnderTest { + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Test + public void closesOnlyLoadersInsideTheWorldFolder() throws IOException { + Path dimensions = temporaryFolder.newFolder("dimensions").toPath(); + Path world = dimensions.resolve("studio"); + Path epochPack = createPack(world.resolve("iris/generation/epochs/a/pack")); + Path prefixSiblingPack = createPack(dimensions.resolve("studio-other/iris/pack")); + Path sourcePack = createPack(temporaryFolder.newFolder("packs").toPath().resolve("source")); + IrisData epochData = IrisData.get(epochPack.toFile()); + IrisData prefixSiblingData = IrisData.get(prefixSiblingPack.toFile()); + IrisData sourceData = IrisData.get(sourcePack.toFile()); + + try { + IrisData.closeLoadedUnder(world.toFile()); + + assertTrue(IrisData.getLoaded(epochPack.toFile()).isEmpty()); + assertTrue(epochData.isClosed()); + assertSame(prefixSiblingData, IrisData.getLoaded(prefixSiblingPack.toFile()).orElse(null)); + assertSame(sourceData, IrisData.getLoaded(sourcePack.toFile()).orElse(null)); + } finally { + IrisData.getLoaded(epochPack.toFile()).ifPresent(IrisData::close); + IrisData.getLoaded(prefixSiblingPack.toFile()).ifPresent(IrisData::close); + IrisData.getLoaded(sourcePack.toFile()).ifPresent(IrisData::close); + } + } + + private static Path createPack(Path pack) throws IOException { + Files.createDirectories(pack.resolve("dimensions")); + Files.writeString(pack.resolve("dimensions/" + pack.getFileName() + ".json"), "{}"); + return pack; + } +} diff --git a/core/src/test/java/art/arcane/iris/pack/value/IrisMathNoiseHotPathParityTest.java b/core/src/test/java/art/arcane/iris/pack/value/IrisMathNoiseHotPathParityTest.java index 0ba33fb6a..8e9a90900 100644 --- a/core/src/test/java/art/arcane/iris/pack/value/IrisMathNoiseHotPathParityTest.java +++ b/core/src/test/java/art/arcane/iris/pack/value/IrisMathNoiseHotPathParityTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.pack.value; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.noise.IrisGenerator; import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.IrisNoiseGenerator; @@ -38,17 +39,17 @@ public class IrisMathNoiseHotPathParityTest { .setStyle(NoiseStyle.PERLIN_IRIS.style()) .setExponent(1.15D); - assertEquals(0.4646529061250786D, noiseGenerator.getNoise(9988L, 31.25D, -17.5D, null), 0D); + assertEquals(0.4646529061250786D, noiseGenerator.getNoise(9988L, 31.25D, -17.5D, PackRuntime.standalone(null)), 0D); IrisGeneratorStyle style = NoiseStyle.IRIS_DOUBLE.style(); - assertEquals(0.6855680984398492D, style.createNoCache(new RNG(112233L), null).noiseFast2D(42.5D, -19.75D), 0D); + assertEquals(0.6855680984398492D, style.createNoCache(new RNG(112233L), PackRuntime.standalone(null)).noiseFast2D(42.5D, -19.75D), 0D); IrisGenerator generator = new IrisGenerator() .setZoom(9.5D) .setOpacity(0.91D) .setComposite(new KList().qadd(noiseGenerator)); - assertEquals(0.5023367573389593D, generator.getHeight(63.0D, -27.0D, 445566L), 0D); + assertEquals(0.5023367573389593D, generator.getHeight(PackRuntime.standalone(null), 63.0D, -27.0D, 445566L), 0D); } @Test diff --git a/core/src/test/java/art/arcane/iris/purity/PackRuntimeStateGateTest.java b/core/src/test/java/art/arcane/iris/purity/PackRuntimeStateGateTest.java new file mode 100644 index 000000000..8ce6e824b --- /dev/null +++ b/core/src/test/java/art/arcane/iris/purity/PackRuntimeStateGateTest.java @@ -0,0 +1,507 @@ +package art.arcane.iris.purity; + +import art.arcane.iris.pack.schema.annotation.Snippet; +import org.junit.Test; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Stream; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +/** + * Pack objects are read-only configuration once loaded. Everything derived for an engine (seeded noise, samplers, + * per-chunk memos) lives in runtime objects the engine owns, so a closed engine can never be pinned by a pack object + * that outlives it. This gate is the ledger of every non-serialized field on a pack type: each one must be listed as + * {@link Kind#CONFIG} (derived from the pack's own content only) or still be pending migration. + */ +public class PackRuntimeStateGateTest { + private static final String IRIS_PACKAGE = "art/arcane/iris"; + private static final String REGISTRANT = "art/arcane/iris/pack/loading/IrisRegistrant"; + private static final String SNIPPET_DESCRIPTOR = "Lart/arcane/iris/pack/schema/annotation/Snippet;"; + private static final List GSON_SKIPPED_TYPES = List.of( + "Lart/arcane/volmlib/util/cache/AtomicCache;", + "Lart/arcane/volmlib/util/scheduling/ChronoLatch;"); + private static final List ADDITIONAL_PACK_TYPES = List.of( + "art.arcane.iris.generation.block.TileData", + "art.arcane.iris.generation.block.LegacyTileData", + "art.arcane.iris.world.loot.IrisVanillaLootTable"); + private static final List ENGINE_TYPES = List.of( + "Lart/arcane/iris/generation/runtime/Engine;", + "Lart/arcane/iris/generation/runtime/IrisEngine;", + "Lart/arcane/iris/generation/runtime/IrisComplex;"); + private static final String THREAD_LOCAL = "Ljava/lang/ThreadLocal;"; + private static final List ENGINE_LIFETIME_TYPES = List.of( + "Lart/arcane/iris/generation/runtime/Engine;", + "Lart/arcane/iris/generation/runtime/IrisEngine;", + "Lart/arcane/iris/generation/runtime/IrisComplex;", + "Lart/arcane/iris/pack/loading/IrisData;", + "Lart/arcane/iris/generation/runtime/ThreadSlots;", + "Lart/arcane/iris/world/IrisWorld;", + "Lart/arcane/volmlib/nativelib/terrain/NativeWorld;", + "Lorg/bukkit/World;"); + private static final Pattern REFERENCED_TYPE = Pattern.compile("L(art/arcane/iris/[A-Za-z0-9_/$]+)[;<]"); + + enum Kind { + CONFIG, + RUNTIME, + THREAD, + SCRATCH, + STATIC, + UNRELATED + } + + private record Entry(String owner, String field, Kind kind, String reason) { + private String key() { + return owner + "#" + field; + } + } + + private static Entry config(String owner, String field, String reason) { + return new Entry(owner, field, Kind.CONFIG, reason); + } + + private static final List CONFIG_FIELDS = List.of( + config("art.arcane.iris.generation.biome.IrisBiome", "biomeScatterResolved", "platform biome resolved from the biome's own key"), + config("art.arcane.iris.generation.biome.IrisBiome", "biomeSkyScatterResolved", "platform biome resolved from the biome's own key"), + config("art.arcane.iris.generation.biome.IrisBiome", "cacheColor", "preview color computed from the biome's own content"), + config("art.arcane.iris.generation.biome.IrisBiome", "cacheColorDecoratorLoad", "preview color computed from the biome's own content"), + config("art.arcane.iris.generation.biome.IrisBiome", "cacheColorDepositLoad", "preview color computed from the biome's own content"), + config("art.arcane.iris.generation.biome.IrisBiome", "cacheColorLayerLoad", "preview color computed from the biome's own content"), + config("art.arcane.iris.generation.biome.IrisBiome", "cacheColorObjectDensity", "preview color computed from the biome's own content"), + config("art.arcane.iris.generation.biome.IrisBiome", "carveObjectsCache", "filters the biome's own object placements"), + config("art.arcane.iris.generation.biome.IrisBiome", "decoratorBuckets", "groups the biome's own decorators by part"), + config("art.arcane.iris.generation.biome.IrisBiome", "derivativeResolved", "platform biome resolved from the biome's own key"), + config("art.arcane.iris.generation.biome.IrisBiome", "genCache", "generator links indexed by key from the biome's own list"), + config("art.arcane.iris.generation.biome.IrisBiome", "inferredType", "biome context inferred while loading the pack's regions"), + config("art.arcane.iris.generation.biome.IrisBiome", "inferredVariants", "biome context inferred while loading the pack's regions"), + config("art.arcane.iris.generation.biome.IrisBiome", "maxHeight", "sums the biome's own generator link and object heights"), + config("art.arcane.iris.generation.biome.IrisBiome", "maxWithObjectHeight", "sums the biome's own generator link and object heights"), + config("art.arcane.iris.generation.biome.IrisBiome", "realCarveBiome", "biome references resolved through the pack's IrisData"), + config("art.arcane.iris.generation.biome.IrisBiome", "realChildren", "biome references resolved through the pack's IrisData"), + config("art.arcane.iris.generation.biome.IrisBiome", "surfaceObjectsCache", "filters the biome's own object placements"), + config("art.arcane.iris.generation.biome.IrisBiome", "surfaceOreBandsCache", "filters and bands the biome's own ore list"), + config("art.arcane.iris.generation.biome.IrisBiome", "surfaceOreCache", "filters and bands the biome's own ore list"), + config("art.arcane.iris.generation.biome.IrisBiome", "surfaceOreReplaceableBlockData", "parsed block keys from the biome's own list"), + config("art.arcane.iris.generation.biome.IrisBiome", "undergroundOreBandsCache", "filters and bands the biome's own ore list"), + config("art.arcane.iris.generation.biome.IrisBiome", "undergroundOreCache", "filters and bands the biome's own ore list"), + config("art.arcane.iris.generation.biome.IrisBiome", "vanillaDerivativeResolved", "platform biome resolved from the biome's own key"), + config("art.arcane.iris.generation.biome.IrisBiomeCustomParticle", "particleResolved", "platform particle resolved from its own key"), + config("art.arcane.iris.generation.biome.IrisBiomeCustomSpawn", "typeResolved", "platform entity type resolved from its own key"), + config("art.arcane.iris.generation.biome.IrisBiomeGeneratorLink", "gen", "generator resolved through the pack's IrisData"), + config("art.arcane.iris.generation.biome.IrisBiomePaletteLayer", "blockData", "block states parsed from the layer's own palette"), + config("art.arcane.iris.generation.biome.IrisFloatingChildBiomes", "resolvedBiome", "child biome resolved through the pack's IrisData"), + config("art.arcane.iris.generation.biome.IrisFloatingChildBiomes", "shrinkScaleCache", "object scale built from the child's own shrink factor"), + config("art.arcane.iris.generation.block.IrisBlockData", "blockdata", "block state parsed from its own key through the pack's IrisData"), + config("art.arcane.iris.generation.block.IrisBlockData", "realProperties", "block state parsed from its own key through the pack's IrisData"), + config("art.arcane.iris.generation.block.VectorMap", "orderedSnapshot", "ordered view of the map's own entries"), + config("art.arcane.iris.generation.decoration.IrisDecorator", "blacklistArray", "block states parsed from the decorator's own palettes"), + config("art.arcane.iris.generation.decoration.IrisDecorator", "blockData", "block states parsed from the decorator's own palettes"), + config("art.arcane.iris.generation.decoration.IrisDecorator", "blockDataArray", "block states parsed from the decorator's own palettes"), + config("art.arcane.iris.generation.decoration.IrisDecorator", "blockDataTops", "block states parsed from the decorator's own palettes"), + config("art.arcane.iris.generation.decoration.IrisDecorator", "blockDataTopsArray", "block states parsed from the decorator's own palettes"), + config("art.arcane.iris.generation.decoration.IrisDecorator", "whitelistArray", "block states parsed from the decorator's own palettes"), + config("art.arcane.iris.generation.decoration.IrisDepositGenerator", "blockData", "block states parsed from the deposit's own palette"), + config("art.arcane.iris.generation.decoration.IrisDepositGenerator", "ore", "block states parsed from the deposit's own palette"), + config("art.arcane.iris.generation.decoration.IrisDepositGenerator", "replaceableBlockData", "block states parsed from the deposit's own palette"), + config("art.arcane.iris.generation.decoration.IrisDepositGenerator", "surfaceReplaceableBlockData", "block states parsed from the deposit's own palette"), + config("art.arcane.iris.generation.decoration.IrisDepositVariant", "resolved", "block states parsed from the variant's own palette"), + config("art.arcane.iris.generation.decoration.coral.IrisCoral", "variantCache", "variants baked from the decorator's own seed and shape settings"), + config("art.arcane.iris.generation.decoration.crystal.IrisCrystal", "variantCache", "variants baked from the decorator's own seed and shape settings"), + config("art.arcane.iris.generation.decoration.formation.IrisFormation", "variantCache", "variants baked from the decorator's own seed and shape settings"), + config("art.arcane.iris.generation.decoration.fungus.IrisFungus", "variantCache", "variants baked from the decorator's own seed and shape settings"), + config("art.arcane.iris.generation.decoration.ruin.IrisRuin", "variantCache", "variants baked from the decorator's own seed and shape settings"), + config("art.arcane.iris.generation.decoration.tree.IrisProceduralTree", "variantCache", "variants baked from the decorator's own seed and shape settings"), + config("art.arcane.iris.generation.terrain.IrisDimension", "carvingEntryIndex", "carving entries indexed from the dimension's own list"), + config("art.arcane.iris.generation.terrain.IrisDimension", "cosr", "trigonometry of the dimension's own angle"), + config("art.arcane.iris.generation.terrain.IrisDimension", "rad", "trigonometry of the dimension's own angle"), + config("art.arcane.iris.generation.terrain.IrisDimension", "sinr", "trigonometry of the dimension's own angle"), + config("art.arcane.iris.generation.terrain.IrisDimension", "staticObjectLayer", "static object layer compiled from the dimension's own placements"), + config("art.arcane.iris.generation.terrain.IrisDimension", "surfaceOreBandsCache", "filters and bands the dimension's own ore list"), + config("art.arcane.iris.generation.terrain.IrisDimension", "surfaceOreCache", "filters and bands the dimension's own ore list"), + config("art.arcane.iris.generation.terrain.IrisDimension", "undergroundOreBandsCache", "filters and bands the dimension's own ore list"), + config("art.arcane.iris.generation.terrain.IrisDimension", "undergroundOreCache", "filters and bands the dimension's own ore list"), + config("art.arcane.iris.generation.terrain.IrisDimension", "undergroundSpawnTables", "spawner references resolved through the pack's IrisData"), + config("art.arcane.iris.generation.terrain.IrisDimensionCarvingEntry", "realBiome", "carving biome resolved through the pack's IrisData"), + config("art.arcane.iris.generation.terrain.IrisMaterialPalette", "blockData", "block states parsed from the palette's own entries"), + config("art.arcane.iris.generation.terrain.IrisMaterialPalette", "fallback", "constant default stone entry of the palette"), + config("art.arcane.iris.generation.terrain.IrisRegion", "cacheColor", "preview color computed from the region's own content"), + config("art.arcane.iris.generation.terrain.IrisRegion", "cacheRidge", "biome keys collected from the region's own lists"), + config("art.arcane.iris.generation.terrain.IrisRegion", "cacheSpot", "biome keys collected from the region's own lists"), + config("art.arcane.iris.generation.terrain.IrisRegion", "carveObjectsCache", "filters the region's own object placements"), + config("art.arcane.iris.generation.terrain.IrisRegion", "realCaveBiomes", "biome pools resolved through the pack's IrisData"), + config("art.arcane.iris.generation.terrain.IrisRegion", "realLandBiomes", "biome pools resolved through the pack's IrisData"), + config("art.arcane.iris.generation.terrain.IrisRegion", "realSeaBiomes", "biome pools resolved through the pack's IrisData"), + config("art.arcane.iris.generation.terrain.IrisRegion", "realShoreBiomes", "biome pools resolved through the pack's IrisData"), + config("art.arcane.iris.generation.terrain.IrisRegion", "shoreHeightGenerator", "noise seeded only from the region's own name and biome settings"), + config("art.arcane.iris.generation.terrain.IrisRegion", "surfaceObjectsCache", "filters the region's own object placements"), + config("art.arcane.iris.generation.terrain.IrisRegion", "surfaceOreBandsCache", "filters and bands the region's own ore list"), + config("art.arcane.iris.generation.terrain.IrisRegion", "surfaceOreCache", "filters and bands the region's own ore list"), + config("art.arcane.iris.generation.terrain.IrisRegion", "undergroundOreBandsCache", "filters and bands the region's own ore list"), + config("art.arcane.iris.generation.terrain.IrisRegion", "undergroundOreCache", "filters and bands the region's own ore list"), + config("art.arcane.iris.pack.loading.IrisRegistrant", "compat", "compatibility status of the object's own content"), + config("art.arcane.iris.pack.loading.IrisRegistrant", "loadFile", "the key and file this object was loaded from"), + config("art.arcane.iris.pack.loading.IrisRegistrant", "loadKey", "the key and file this object was loaded from"), + config("art.arcane.iris.pack.loading.IrisRegistrant", "loader", "the IrisData that loaded this object"), + config("art.arcane.iris.pack.value.IrisColor", "color", "color parsed from its own hex or channels"), + config("art.arcane.iris.structure.object.IrisAxisRotationClamp", "forceLock", "lock flag derived from the clamp's own settings"), + config("art.arcane.iris.structure.object.IrisObject", "aabb", "geometry derived from the object's own blocks"), + config("art.arcane.iris.structure.object.IrisObject", "center", "geometry derived from the object's own blocks"), + config("art.arcane.iris.structure.object.IrisObject", "floatingFootprint", "geometry derived from the object's own blocks"), + config("art.arcane.iris.structure.object.IrisObject", "placementBakes", "rotated block layouts keyed only by rotation and translation"), + config("art.arcane.iris.structure.object.IrisObject", "placementLayout", "rotated block layouts keyed only by rotation and translation"), + config("art.arcane.iris.structure.object.IrisObject", "readLock", "guards the object's own block data"), + config("art.arcane.iris.structure.object.IrisObject", "shrinkOffset", "geometry derived from the object's own blocks"), + config("art.arcane.iris.structure.object.IrisObject", "smartBoreVariant", "shape variant derived from the object's own blocks"), + config("art.arcane.iris.structure.object.IrisObject", "smartBored", "shape variant derived from the object's own blocks"), + config("art.arcane.iris.structure.object.IrisObject", "surfaceSupportOffsets", "geometry derived from the object's own blocks"), + config("art.arcane.iris.structure.object.IrisObject", "treeGrounding", "grounding offsets of a tree object's own trunk"), + config("art.arcane.iris.structure.object.IrisObject", "writeLock", "guards the object's own block data"), + config("art.arcane.iris.structure.object.IrisObjectLoot", "filterCache", "block states parsed from its own filter list"), + config("art.arcane.iris.structure.object.IrisObjectMarker", "findData", "block states parsed from its own marker list"), + config("art.arcane.iris.structure.object.IrisObjectPlacement", "cache", "loot tables resolved through the pack's IrisData"), + config("art.arcane.iris.structure.object.IrisObjectPlacement", "compatCache", "compatibility of the placement's own object keys"), + config("art.arcane.iris.structure.object.IrisObjectPlacement", "compatPlaceCache", "compatibility of the placement's own object keys"), + config("art.arcane.iris.structure.object.IrisObjectReplace", "findData", "block states parsed from its own lists"), + config("art.arcane.iris.structure.object.IrisObjectReplace", "replaceData", "block states parsed from its own lists"), + config("art.arcane.iris.structure.object.IrisObjectRotation", "stateRotations", "rotated block states keyed by state and rotation step"), + config("art.arcane.iris.structure.object.IrisObjectVanillaLoot", "filterCache", "block states parsed from its own filter list"), + config("art.arcane.iris.world.entity.IrisEffect", "particleEffectResolved", "platform types resolved from the effect's own keys"), + config("art.arcane.iris.world.entity.IrisEffect", "pt", "platform types resolved from the effect's own keys"), + config("art.arcane.iris.world.entity.IrisEffect", "soundResolved", "platform types resolved from the effect's own keys"), + config("art.arcane.iris.world.entity.IrisEntitySpawn", "ent", "entity resolved through the pack's IrisData"), + config("art.arcane.iris.world.entity.IrisPotionEffect", "pt", "potion type resolved from its own key"), + config("art.arcane.iris.world.loot.IrisBlockDrops", "data", "block data parsed from its own list"), + config("art.arcane.iris.world.loot.IrisLoot", "dyeColorResolved", "dye color parsed from its own key"), + config("art.arcane.iris.world.loot.IrisLootReference", "tt", "loot tables resolved through the pack's IrisData"), + config("art.arcane.iris.world.loot.IrisVanillaLootTable", "resolvedKey", "namespaced key parsed from its own string") + ); + + @Test + public void everyNonSerializedPackFieldIsInTheLedger() throws Exception { + Map ledger = ledger(); + PackTypes types = PackTypes.scan(); + List unlisted = new ArrayList<>(); + for (String type : types.packTypes()) { + for (ClassFileFacts.DeclaredField field : types.facts(type).fields()) { + if (!isNonSerializedState(field)) { + continue; + } + String key = type + "#" + field.name(); + if (!ledger.containsKey(key)) { + unlisted.add(key + " : " + (field.signature() == null ? field.descriptor() : field.signature())); + } + } + } + assertTrue("Non-serialized pack fields missing from the ledger. Derived engine state belongs in a runtime " + + "object the engine owns; list only content-derived values as CONFIG:" + join(unlisted), unlisted.isEmpty()); + } + + @Test + public void everyThreadLocalAndEngineHoldingStaticIsInTheLedger() throws Exception { + PackTypes types = PackTypes.scan(); + Map ledger = holderLedger(); + List unlisted = new ArrayList<>(); + for (Map.Entry type : types.all().entrySet()) { + for (ClassFileFacts.DeclaredField field : type.getValue().fields()) { + if (!isThreadLocal(field) && !(field.isStatic() && holdsEngineLifetimeState(field))) { + continue; + } + String key = type.getKey() + "#" + field.name(); + if (!ledger.containsKey(key)) { + unlisted.add(key + " : " + (field.signature() == null ? field.descriptor() : field.signature())); + } + } + } + assertTrue("Thread-locals and static holders missing from the ledger:" + join(unlisted), unlisted.isEmpty()); + } + + @Test + public void everyLedgerEntryStillExists() throws Exception { + PackTypes types = PackTypes.scan(); + List stale = new ArrayList<>(); + for (List list : List.of(CONFIG_FIELDS, SETTLED_HOLDERS, ENGINE_PARAMETERS)) { + for (Entry entry : list) { + if (!types.declares(entry.owner(), entry.field())) { + stale.add(entry.key()); + } + } + } + assertTrue("Ledger entries for fields that no longer exist; remove them:" + join(stale), stale.isEmpty()); + } + + @Test + public void configAllowlistHoldsOnlyConfigEntries() { + for (Entry entry : CONFIG_FIELDS) { + assertTrue(entry.key() + " is not CONFIG", entry.kind() == Kind.CONFIG); + assertTrue(entry.key() + " needs a reason", !entry.reason().isBlank()); + } + } + + @Test + public void packTypesHoldNoEngineReference() throws Exception { + PackTypes types = PackTypes.scan(); + Set exempt = keys(ENGINE_PARAMETERS); + List failures = new ArrayList<>(); + for (String type : types.packTypesWithNested()) { + for (ClassFileFacts.DeclaredField field : types.facts(type).fields()) { + if (exempt.contains(type + "#" + field.name())) { + continue; + } + for (String engineType : ENGINE_TYPES) { + if (mentions(field, engineType)) { + failures.add(type + "#" + field.name() + " : " + engineType); + } + } + } + } + if (!failures.isEmpty()) { + fail("Pack types must not hold an engine; move the derived value into an engine-owned runtime object:" + + join(failures)); + } + } + + @Test + public void scanFindsThePackTypes() throws Exception { + PackTypes types = PackTypes.scan(); + assertTrue("expected the scan to find the biome type", types.packTypes().contains("art.arcane.iris.generation.biome.IrisBiome")); + assertTrue("expected the scan to follow field types to nested config", types.packTypes().contains("art.arcane.iris.generation.noise.IrisGeneratorStyle")); + assertTrue("expected more than 100 pack types, found " + types.packTypes().size(), types.packTypes().size() > 100); + } + + private static boolean isThreadLocal(ClassFileFacts.DeclaredField field) { + return field.descriptor().equals(THREAD_LOCAL); + } + + private static boolean holdsEngineLifetimeState(ClassFileFacts.DeclaredField field) { + for (String type : ENGINE_LIFETIME_TYPES) { + if (mentions(field, type)) { + return true; + } + } + return false; + } + + private static boolean isNonSerializedState(ClassFileFacts.DeclaredField field) { + if (field.isStatic()) { + return false; + } + return field.isTransient() || GSON_SKIPPED_TYPES.contains(field.descriptor()); + } + + private static boolean mentions(ClassFileFacts.DeclaredField field, String descriptor) { + String bare = descriptor.substring(0, descriptor.length() - 1); + return field.descriptor().contains(descriptor) + || (field.signature() != null && (field.signature().contains(descriptor) || field.signature().contains(bare + "<"))); + } + + private static final List ENGINE_PARAMETERS = List.of( + holder("art.arcane.iris.generation.runtime.IrisEngineStreamType", "getter", Kind.CONFIG, + "a function that takes the engine as its argument, stores none"), + holder("art.arcane.iris.generation.runtime.IrisEngineValueType", "getter", Kind.CONFIG, + "a function that takes the engine as its argument, stores none"), + holder("art.arcane.iris.generation.terrain.IrisDimensionModeType", "factory", Kind.CONFIG, + "a function that takes the engine as its argument, stores none"), + holder("art.arcane.iris.world.entity.IrisEntity$BukkitOps$1", "val$gen", Kind.UNRELATED, + "loot table adapter attached to a spawned entity, never stored on the pack object") + ); + + private static final List SETTLED_HOLDERS = List.of( + holder("art.arcane.iris.generation.biome.FloatingIslandSample", "LAST_DENSITY", Kind.SCRATCH, "the last cluster diagnostic doubles, no engine or pack reference"), + holder("art.arcane.iris.generation.biome.FloatingIslandSample", "LAST_REJECT", Kind.SCRATCH, "the last reject code, no engine or pack reference"), + holder("art.arcane.iris.generation.noise.ExpressionRuntime", "EVALUATION_SCRATCH", Kind.SCRATCH, "per-depth double argument arrays, no engine or pack reference"), + holder("art.arcane.iris.generation.bake.ChunkBakeCache", "SPARSE", Kind.SCRATCH, "a per-thread sparse-bake depth counter, no engine or pack reference"), + holder("art.arcane.iris.generation.context.IrisContext", "OVERFLOW", Kind.SCRATCH, "a scoped context binding removed when the thread's outermost scope closes"), + holder("art.arcane.iris.generation.decoration.DecoratorCore", "SCRATCH_OPTS", Kind.SCRATCH, "placement flags; the mantle reference is cleared when each placement returns"), + holder("art.arcane.iris.generation.decoration.IrisDepositGenerator", "FOOTPRINT_CELLS", Kind.SCRATCH, "primitive footprint cell buffers, no engine or pack reference"), + holder("art.arcane.iris.generation.mantle.CarveOrphanSweep", "SCRATCH", Kind.SCRATCH, "primitive sweep buffers, no engine or pack reference"), + holder("art.arcane.iris.generation.mantle.CaveLatticeBatch", "CURRENT", Kind.SCRATCH, "primitive noise and lattice buffers, no engine or pack reference"), + holder("art.arcane.iris.generation.mantle.MantleCarvingComponent", "BLEND_SCRATCH", Kind.SCRATCH, "profile, biome and region slots cleared by release when each chunk returns"), + holder("art.arcane.iris.generation.noise.IrisNoiseGenerator", "FRACTURE_SAMPLES", Kind.SCRATCH, "fracture node and generator slots cleared when each sample returns"), + holder("art.arcane.iris.generation.runtime.IrisComplex", "BATCH_SCRATCH", Kind.SCRATCH, "primitive noise batch buffers, no engine or pack reference"), + holder("art.arcane.iris.generation.runtime.PaintedColumnRuns", "SCRATCH", Kind.SCRATCH, "primitive run buffers, no engine or pack reference"), + holder("art.arcane.iris.generation.stage.IrisCarveModifier", "SCRATCH", Kind.SCRATCH, "carve masks, cavern and biome memos released when each chunk is carved"), + holder("art.arcane.iris.generation.stream.ProvisionalSampling", "TRACKERS", Kind.SCRATCH, "a per-thread provisional revision counter, no engine or pack reference"), + holder("art.arcane.iris.generation.terrain.Terrain3DFragmentFilter", "TRAVERSALS", Kind.SCRATCH, "traversal buffers whose column slots are cleared after each classification"), + holder("art.arcane.iris.structure.object.IrisSurfaceSupport", "STENCIL", Kind.SCRATCH, "primitive stencil buffers, no engine or pack reference"), + holder("art.arcane.iris.world.history.NativeTerrainReceipt", "DEFLATERS", Kind.SCRATCH, "a reusable zlib deflater, no engine or pack reference"), + holder("art.arcane.iris.world.history.SavedBiomeStore", "DEFLATERS", Kind.SCRATCH, "a reusable zlib deflater, no engine or pack reference"), + holder("art.arcane.iris.world.storage.matter.IrisMatterContext", "DATA", Kind.SCRATCH, "a scoped pack data binding removed when the thread's outermost scope closes"), + holder("art.arcane.iris.world.tree.TreeSVC", "REENTRANT", Kind.SCRATCH, "a reentrancy flag, no engine or pack reference"), + holder("art.arcane.iris.structure.nativegen.NativeStructureOwnershipStore", "STATES", Kind.STATIC, "live-engine registry; a closed engine releases its store in the shutdown sequence (EngineShutdownDrainTest)"), + holder("art.arcane.iris.structure.nativegen.NativeStructureVolumeIndex", "INDEXES", Kind.STATIC, "live-engine registry; a closed engine uninstalls its index in the shutdown sequence (EngineShutdownDrainTest)"), + holder("art.arcane.iris.structure.placement.IrisStructureLocator", "INDEX_CACHE", Kind.STATIC, "live-engine registry; a closed engine invalidates its index in the shutdown sequence (EngineShutdownDrainTest)"), + holder("art.arcane.iris.structure.placement.IrisStructureLocator", "LOCATABLE_INDEX_CACHE", Kind.STATIC, "live-engine registry; a closed engine invalidates its index in the shutdown sequence (EngineShutdownDrainTest)"), + holder("art.arcane.iris.structure.placement.StructurePlacementScope", "SCOPE_INDEXES", Kind.STATIC, "live-engine registry; a closed engine invalidates its index in the shutdown sequence (EngineShutdownDrainTest)"), + holder("art.arcane.iris.structure.placement.StructureReachability", "REACHABLE_CACHE", Kind.STATIC, "live-engine registry; a closed engine invalidates its keys in the shutdown sequence (EngineShutdownDrainTest)"), + holder("art.arcane.iris.generation.runtime.EngineTickRegistry", "TICK_ENGINES", Kind.STATIC, "live-engine registry; every engine unregisters itself when it closes (EngineReleaseProbeTest)"), + holder("art.arcane.iris.pack.loading.IrisData", "ENGINE_HOLDERS", Kind.STATIC, "pack data with live engines; an engine unregisters from its pack data when it closes (EngineReleaseProbeTest)"), + holder("art.arcane.iris.pack.loading.IrisData", "dataLoaders", Kind.STATIC, "pack data by folder; pack data drops each engine that closes (EngineReleaseProbeTest)"), + holder("art.arcane.iris.studio.object.ObjectStudioActivation", "SOURCES", Kind.STATIC, "studio object source packs, removed when the studio pack deactivates; pack data holds no closed engine"), + holder("art.arcane.iris.generation.runtime.EnginePanic$Diagnostics", "current", Kind.UNRELATED, "panic diagnostics strings for crash reports"), + holder("art.arcane.iris.pack.IrisPackBenchmarking", "instance", Kind.UNRELATED, "benchmark command session") + ); + + private static Entry holder(String owner, String field, Kind kind, String reason) { + return new Entry(owner, field, kind, reason); + } + + private static Set keys(List entries) { + Set keys = new TreeSet<>(); + for (Entry entry : entries) { + keys.add(entry.key()); + } + return keys; + } + + private static Map holderLedger() { + Map entries = new LinkedHashMap<>(); + for (Entry entry : SETTLED_HOLDERS) { + if (entries.put(entry.key(), entry) != null) { + fail("Duplicate holder ledger entry " + entry.key()); + } + } + return entries; + } + + private static Map ledger() { + Map entries = new LinkedHashMap<>(); + for (Entry entry : CONFIG_FIELDS) { + if (entries.put(entry.key(), entry) != null) { + fail("Duplicate ledger entry " + entry.key()); + } + } + return entries; + } + + private static String join(List lines) { + StringBuilder out = new StringBuilder(); + for (String line : lines) { + out.append("\n ").append(line); + } + return out.toString(); + } + + private record PackTypes(Map all, Set packTypes) { + private static PackTypes scan() throws Exception { + Map all = new TreeMap<>(); + ClassLoader loader = PackRuntimeStateGateTest.class.getClassLoader(); + for (String name : classNamesUnder(IRIS_PACKAGE)) { + byte[] bytes = BukkitHidingClassLoader.readClassBytes(loader, name); + if (bytes != null) { + all.put(name, ClassFileFacts.read(bytes)); + } + } + Set roots = new TreeSet<>(ADDITIONAL_PACK_TYPES); + for (Map.Entry entry : all.entrySet()) { + if (entry.getValue().hasClassAnnotation(SNIPPET_DESCRIPTOR) || extendsRegistrant(entry.getValue(), all)) { + roots.add(entry.getKey()); + } + } + Set packTypes = new TreeSet<>(); + List queue = new ArrayList<>(roots); + while (!queue.isEmpty()) { + String type = queue.removeLast(); + ClassFileFacts facts = all.get(type); + if (facts == null || !packTypes.add(type)) { + continue; + } + if (facts.superName() != null) { + queue.add(facts.superName().replace('/', '.')); + } + for (ClassFileFacts.DeclaredField field : facts.fields()) { + if (field.isStatic() || field.isTransient() || GSON_SKIPPED_TYPES.contains(field.descriptor())) { + continue; + } + queue.addAll(referencedTypes(field)); + } + } + return new PackTypes(all, packTypes); + } + + private ClassFileFacts facts(String type) { + return all.get(type); + } + + private boolean declares(String type, String fieldName) { + ClassFileFacts facts = all.get(type); + if (facts == null) { + return false; + } + for (ClassFileFacts.DeclaredField field : facts.fields()) { + if (field.name().equals(fieldName)) { + return true; + } + } + return false; + } + + private Set packTypesWithNested() { + Set types = new TreeSet<>(packTypes); + for (String candidate : all.keySet()) { + int nested = candidate.indexOf('$'); + if (nested > 0 && packTypes.contains(candidate.substring(0, nested))) { + types.add(candidate); + } + } + return types; + } + + private static boolean extendsRegistrant(ClassFileFacts facts, Map all) { + ClassFileFacts current = facts; + while (current != null && current.superName() != null) { + if (current.superName().equals(REGISTRANT)) { + return true; + } + current = all.get(current.superName().replace('/', '.')); + } + return false; + } + + private static List referencedTypes(ClassFileFacts.DeclaredField field) { + List types = new ArrayList<>(); + collect(field.descriptor(), types); + if (field.signature() != null) { + collect(field.signature(), types); + } + return types; + } + + private static void collect(String text, List sink) { + Matcher matcher = REFERENCED_TYPE.matcher(text); + while (matcher.find()) { + sink.add(matcher.group(1).replace('/', '.')); + } + } + + private static List classNamesUnder(String packageInternalName) throws Exception { + URL location = Snippet.class.getProtectionDomain().getCodeSource().getLocation(); + Path root = Paths.get(location.toURI()); + List names = new ArrayList<>(); + if (!Files.isDirectory(root)) { + throw new IOException("Pack type scan expects a class directory, found " + root); + } + try (Stream walk = Files.walk(root.resolve(packageInternalName))) { + walk.filter(path -> path.toString().endsWith(".class")).forEach(path -> { + String relative = root.relativize(path).toString().replace(File.separatorChar, '/'); + names.add(relative.substring(0, relative.length() - ".class".length()).replace('/', '.')); + }); + } + return names; + } + } +} diff --git a/core/src/test/java/art/arcane/iris/structure/nativegen/NativeStructureOwnershipStoreTest.java b/core/src/test/java/art/arcane/iris/structure/nativegen/NativeStructureOwnershipStoreTest.java index 094c31c08..47a00c4db 100644 --- a/core/src/test/java/art/arcane/iris/structure/nativegen/NativeStructureOwnershipStoreTest.java +++ b/core/src/test/java/art/arcane/iris/structure/nativegen/NativeStructureOwnershipStoreTest.java @@ -1,5 +1,8 @@ package art.arcane.iris.structure.nativegen; +import com.github.benmanes.caffeine.cache.Cache; +import java.lang.reflect.Field; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.IrisEngine; @@ -221,6 +224,23 @@ public class NativeStructureOwnershipStoreTest { record.structureKey(), record.originChunkX(), record.originChunkZ())); } + @Test + public void releasedStoreOfAClosedEngineCannotReopen() throws Exception { + Engine engine = engine(); + NativeStructureOwnershipStore.close(engine); + when(engine.isClosed()).thenReturn(true); + + NativeStructureOwnershipStore.release(engine); + + Field states = NativeStructureOwnershipStore.class.getDeclaredField("STATES"); + states.setAccessible(true); + @SuppressWarnings("unchecked") + Cache stores = (Cache) states.get(null); + assertNull(stores.getIfPresent(engine)); + assertThrows(IllegalStateException.class, () -> + NativeStructureOwnershipStore.findPersisted(engine, "test:after_release", 0, 0)); + } + @Test public void explicitCloseCreatesAndRetainsAClosedOwnershipState() { Engine engine = engine(); diff --git a/core/src/test/java/art/arcane/iris/structure/object/HeightmapObjectPlacerTest.java b/core/src/test/java/art/arcane/iris/structure/object/HeightmapObjectPlacerTest.java index 7583ca118..714c6908d 100644 --- a/core/src/test/java/art/arcane/iris/structure/object/HeightmapObjectPlacerTest.java +++ b/core/src/test/java/art/arcane/iris/structure/object/HeightmapObjectPlacerTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.structure.object; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.runtime.Engine; import art.arcane.volmlib.util.math.RNG; import org.junit.Test; @@ -15,11 +16,11 @@ public class HeightmapObjectPlacerTest { Engine engine = mock(Engine.class); IObjectPlacer ownedDelegate = mock(IObjectPlacer.class); when(ownedDelegate.getEngine()).thenReturn(engine); - HeightmapObjectPlacer owned = new HeightmapObjectPlacer(mock(RNG.class), 1, 2, 3, new IrisObjectPlacement(), ownedDelegate); + HeightmapObjectPlacer owned = new HeightmapObjectPlacer(mock(RNG.class), 1, 2, 3, new IrisObjectPlacement(), ownedDelegate, PackRuntime.standalone(null)); assertSame(engine, owned.getEngine()); IObjectPlacer unownedDelegate = mock(IObjectPlacer.class); - HeightmapObjectPlacer unowned = new HeightmapObjectPlacer(mock(RNG.class), 1, 2, 3, new IrisObjectPlacement(), unownedDelegate); + HeightmapObjectPlacer unowned = new HeightmapObjectPlacer(mock(RNG.class), 1, 2, 3, new IrisObjectPlacement(), unownedDelegate, PackRuntime.standalone(null)); assertNull(unowned.getEngine()); } } diff --git a/core/src/test/java/art/arcane/iris/structure/object/IrisObjectPlacementLifecycleRegressionTest.java b/core/src/test/java/art/arcane/iris/structure/object/IrisObjectPlacementLifecycleRegressionTest.java index 5635ccbde..ad65c554f 100644 --- a/core/src/test/java/art/arcane/iris/structure/object/IrisObjectPlacementLifecycleRegressionTest.java +++ b/core/src/test/java/art/arcane/iris/structure/object/IrisObjectPlacementLifecycleRegressionTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.structure.object; +import art.arcane.iris.testsupport.MockPackData; import art.arcane.iris.generation.terrain.IrisSlopeClip; import art.arcane.iris.generation.noise.IrisNoiseGenerator; @@ -74,7 +75,7 @@ public class IrisObjectPlacementLifecycleRegressionTest { engine = mock(Engine.class); when(engine.getHeight()).thenReturn(256); - data = mock(IrisData.class); + data = MockPackData.create(); when(data.getEngine()).thenReturn(engine); solid = state("minecraft:stone", true); schematicAir = state("minecraft:air", false); diff --git a/core/src/test/java/art/arcane/iris/structure/object/IrisObjectPlacementRunnerRegressionTest.java b/core/src/test/java/art/arcane/iris/structure/object/IrisObjectPlacementRunnerRegressionTest.java index 4d9488a66..ee60d304e 100644 --- a/core/src/test/java/art/arcane/iris/structure/object/IrisObjectPlacementRunnerRegressionTest.java +++ b/core/src/test/java/art/arcane/iris/structure/object/IrisObjectPlacementRunnerRegressionTest.java @@ -1,5 +1,7 @@ package art.arcane.iris.structure.object; +import art.arcane.iris.testsupport.MockPackData; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.block.TileData; import art.arcane.iris.generation.geometry.IrisBlockVector; import art.arcane.iris.generation.decoration.IrisStiltSettings; @@ -85,7 +87,7 @@ public class IrisObjectPlacementRunnerRegressionTest { engine = mock(Engine.class); when(engine.getHeight()).thenReturn(256); - data = mock(IrisData.class); + data = MockPackData.create(); when(data.getEngine()).thenReturn(engine); solid = state("minecraft:stone", true); schematicAir = state("minecraft:air", false); @@ -262,7 +264,7 @@ public class IrisObjectPlacementRunnerRegressionTest { IrisObjectReplace edit = mock(IrisObjectReplace.class); when(edit.getChance()).thenReturn(0.45F); when(edit.getFind(data)).thenReturn(new KList<>(solid)); - when(edit.getReplace(any(RNG.class), anyDouble(), anyDouble(), anyDouble(), any(IrisData.class))) + when(edit.getReplace(any(RNG.class), anyDouble(), anyDouble(), anyDouble(), any(PackRuntime.class))) .thenReturn(replacement); IrisMaterialPalette palette = mock(IrisMaterialPalette.class); when(palette.getTile(any(RNG.class), anyDouble(), anyDouble(), anyDouble(), any(IrisData.class))) @@ -351,7 +353,7 @@ public class IrisObjectPlacementRunnerRegressionTest { IrisMaterialPalette palette = mock(IrisMaterialPalette.class); when(edit.getChance()).thenReturn(1F); when(edit.getFind(data)).thenReturn(new KList<>(chest)); - when(edit.getReplace(any(RNG.class), anyDouble(), anyDouble(), anyDouble(), any(IrisData.class))) + when(edit.getReplace(any(RNG.class), anyDouble(), anyDouble(), anyDouble(), any(PackRuntime.class))) .thenReturn(solid); when(edit.getReplace()).thenReturn(palette); when(palette.getTile(any(RNG.class), anyDouble(), anyDouble(), anyDouble(), any(IrisData.class))) @@ -534,7 +536,7 @@ public class IrisObjectPlacementRunnerRegressionTest { NativeBlockState calcite = state("minecraft:calcite", true); NativeBlockState cobblestone = state("minecraft:cobblestone", true); IrisMaterialPalette palette = mock(IrisMaterialPalette.class); - when(palette.get(any(RNG.class), anyDouble(), anyDouble(), anyDouble(), any(IrisData.class))) + when(palette.get(any(RNG.class), anyDouble(), anyDouble(), anyDouble(), any(PackRuntime.class))) .thenReturn(cobblestone); IrisObject object = lineObject(3); object.setUnsigned(2, 0, 0, calcite); @@ -561,7 +563,7 @@ public class IrisObjectPlacementRunnerRegressionTest { object.setUnsigned(0, 0, 0, ice); object.setUnsigned(2, 0, 0, cluster); IrisMaterialPalette palette = mock(IrisMaterialPalette.class); - when(palette.get(any(RNG.class), anyDouble(), anyDouble(), anyDouble(), any(IrisData.class))) + when(palette.get(any(RNG.class), anyDouble(), anyDouble(), anyDouble(), any(PackRuntime.class))) .thenReturn(solid); RecordingPlacer placer = new RecordingPlacer(null); IrisObjectPlacement placement = placement().setMode(ObjectPlaceMode.CENTER_STILT) @@ -582,10 +584,10 @@ public class IrisObjectPlacementRunnerRegressionTest { NativeBlockState packedIce = state("minecraft:packed_ice", true); IrisMaterialPalette body = mock(IrisMaterialPalette.class); when(body.getPalette()).thenReturn(new KList<>(new IrisBlockData("minecraft:ice"))); - when(body.get(any(RNG.class), anyDouble(), anyDouble(), anyDouble(), any(IrisData.class))) + when(body.get(any(RNG.class), anyDouble(), anyDouble(), anyDouble(), any(PackRuntime.class))) .thenReturn(ice); IrisMaterialPalette roots = mock(IrisMaterialPalette.class); - when(roots.get(any(RNG.class), anyDouble(), anyDouble(), anyDouble(), any(IrisData.class))) + when(roots.get(any(RNG.class), anyDouble(), anyDouble(), anyDouble(), any(PackRuntime.class))) .thenReturn(packedIce); IrisFormation formation = new IrisFormation().setForm(IrisFormationForm.OVERHANG) .setHeightMin(16).setHeightMax(25).setBaseWidthMin(5).setBaseWidthMax(8) @@ -726,7 +728,7 @@ public class IrisObjectPlacementRunnerRegressionTest { when(barrel.isStorage()).thenReturn(true); for (NativeBlockState replacement : List.of(calcite, barrel)) { IrisMaterialPalette palette = mock(IrisMaterialPalette.class); - when(palette.get(any(RNG.class), anyDouble(), anyDouble(), anyDouble(), any(IrisData.class))) + when(palette.get(any(RNG.class), anyDouble(), anyDouble(), anyDouble(), any(PackRuntime.class))) .thenReturn(replacement); RecordingPlacer placer = new RecordingPlacer(null); IrisObjectPlacement placement = placement().setMode(ObjectPlaceMode.CENTER_STILT) @@ -750,7 +752,7 @@ public class IrisObjectPlacementRunnerRegressionTest { IrisMaterialPalette palette = mock(IrisMaterialPalette.class); when(edit.getChance()).thenReturn(1F); when(edit.getFind(data)).thenReturn(new KList<>(solid)); - when(edit.getReplace(any(RNG.class), anyDouble(), anyDouble(), anyDouble(), any(IrisData.class))) + when(edit.getReplace(any(RNG.class), anyDouble(), anyDouble(), anyDouble(), any(PackRuntime.class))) .thenReturn(replacement); when(edit.getReplace()).thenReturn(palette); when(palette.getTile(any(RNG.class), anyDouble(), anyDouble(), anyDouble(), any(IrisData.class))) diff --git a/core/src/test/java/art/arcane/iris/structure/object/IrisObjectPlacementSurfaceWarpCacheTest.java b/core/src/test/java/art/arcane/iris/structure/object/IrisObjectPlacementSurfaceWarpCacheTest.java index 1d35b0dd4..759255254 100644 --- a/core/src/test/java/art/arcane/iris/structure/object/IrisObjectPlacementSurfaceWarpCacheTest.java +++ b/core/src/test/java/art/arcane/iris/structure/object/IrisObjectPlacementSurfaceWarpCacheTest.java @@ -1,5 +1,7 @@ package art.arcane.iris.structure.object; +import art.arcane.iris.generation.runtime.PackRuntime; +import art.arcane.iris.testsupport.MockPackData; import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.NoiseStyle; @@ -10,8 +12,6 @@ import art.arcane.volmlib.util.noise.CNG; import art.arcane.volmlib.util.math.RNG; import org.junit.Test; -import java.util.concurrent.atomic.AtomicReference; - import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.mock; @@ -20,29 +20,26 @@ import static org.mockito.Mockito.when; public class IrisObjectPlacementSurfaceWarpCacheTest { @Test public void surfaceWarpSeparatesEngineSeeds() { - Engine first = engine(100L); - Engine second = engine(200L); - AtomicReference active = new AtomicReference<>(first); - IrisData data = mock(IrisData.class); - when(data.getEngine()).thenAnswer(ignored -> active.get()); + IrisData data = MockPackData.create(); + PackRuntime first = PackRuntime.forEngine(engine(100L), data); + PackRuntime second = PackRuntime.forEngine(engine(200L), data); IrisObjectPlacement placement = placement(); - CNG firstWarp = placement.getSurfaceWarp(new RNG(1L), data); - assertSame(firstWarp, placement.getSurfaceWarp(new RNG(999L), data)); - active.set(second); + CNG firstWarp = placement.getSurfaceWarp(new RNG(1L), first); + assertSame(firstWarp, placement.getSurfaceWarp(new RNG(999L), first)); - assertNotSame(firstWarp, placement.getSurfaceWarp(new RNG(1L), data)); + assertNotSame(firstWarp, placement.getSurfaceWarp(new RNG(1L), second)); } @Test public void standaloneSurfaceWarpUsesSuppliedSeed() { - IrisData data = mock(IrisData.class); + PackRuntime runtime = PackRuntime.standalone(MockPackData.create()); IrisObjectPlacement placement = placement(); - CNG first = placement.getSurfaceWarp(new RNG(1L), data); + CNG first = placement.getSurfaceWarp(new RNG(1L), runtime); - assertSame(first, placement.getSurfaceWarp(new RNG(1L), data)); - assertNotSame(first, placement.getSurfaceWarp(new RNG(2L), data)); + assertSame(first, placement.getSurfaceWarp(new RNG(1L), runtime)); + assertNotSame(first, placement.getSurfaceWarp(new RNG(2L), runtime)); } private IrisObjectPlacement placement() { diff --git a/core/src/test/java/art/arcane/iris/structure/object/ObjectPlacementGoldenTest.java b/core/src/test/java/art/arcane/iris/structure/object/ObjectPlacementGoldenTest.java index 0562e30be..38419e35a 100644 --- a/core/src/test/java/art/arcane/iris/structure/object/ObjectPlacementGoldenTest.java +++ b/core/src/test/java/art/arcane/iris/structure/object/ObjectPlacementGoldenTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.structure.object; +import art.arcane.iris.testsupport.MockPackData; import art.arcane.iris.generation.hydrology.raster.WaterRole; import art.arcane.iris.generation.block.BlockDataMergeSupport; import art.arcane.iris.generation.block.IrisBlockData; @@ -125,10 +126,10 @@ public class ObjectPlacementGoldenTest { when(engine.getDimension()).thenReturn(dimension); ContentGate gate = mock(ContentGate.class, withSettings().stubOnly()); when(gate.ready()).thenReturn(false); - data = mock(IrisData.class, withSettings().stubOnly()); + data = MockPackData.stubOnly(); when(data.getEngine()).thenReturn(engine); when(data.getContentGate()).thenReturn(gate); - objectData = mock(IrisData.class, withSettings().stubOnly()); + objectData = MockPackData.stubOnly(); when(objectData.getContentGate()).thenReturn(gate); } diff --git a/core/src/test/java/art/arcane/iris/structure/placement/IrisStructureLocatorContractTest.java b/core/src/test/java/art/arcane/iris/structure/placement/IrisStructureLocatorContractTest.java index 3efea3aa1..6d77abf95 100644 --- a/core/src/test/java/art/arcane/iris/structure/placement/IrisStructureLocatorContractTest.java +++ b/core/src/test/java/art/arcane/iris/structure/placement/IrisStructureLocatorContractTest.java @@ -18,6 +18,7 @@ package art.arcane.iris.structure.placement; +import art.arcane.iris.testsupport.MockPackData; import art.arcane.volmlib.util.structure.StructureTerrainMode; import art.arcane.volmlib.util.structure.StructureCarveShape; @@ -114,7 +115,7 @@ public class IrisStructureLocatorContractTest { @Test public void locatableIndexIncludesAliasesAndSeparatesEditableFromNativePlacements() { - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); IrisStructure structure = new IrisStructure(); structure.setLoadKey("test:city"); structure.setVanillaSource("source:city"); @@ -156,7 +157,7 @@ public class IrisStructureLocatorContractTest { @Test public void nativeStructureReplacementSuppressesOnlyItsRegisteredSource() { - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); Engine engine = mock(Engine.class); IrisDimension dimension = mock(IrisDimension.class); IrisStructurePlacement placement = new IrisStructurePlacement() @@ -185,7 +186,7 @@ public class IrisStructureLocatorContractTest { @Test public void vanillaSourceRequiresExplicitDimensionSuppression() { - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); IrisStructure structure = new IrisStructure(); structure.setLoadKey("test:city"); structure.setVanillaSource("minecraft:ancient_city"); @@ -214,7 +215,7 @@ public class IrisStructureLocatorContractTest { @Test public void regionReplacementFailsInsteadOfFallingBackToNative() { - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); IrisStructure structure = new IrisStructure(); structure.setLoadKey("test:city"); structure.setVanillaSource("minecraft:ancient_city"); @@ -242,7 +243,7 @@ public class IrisStructureLocatorContractTest { @Test public void geometryFailureFailsInsteadOfFallingBackToNative() { - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); IrisStructure structure = new IrisStructure() .setStartPool("test:start") .setMaxDepth(1) @@ -304,7 +305,7 @@ public class IrisStructureLocatorContractTest { @Test public void missingVanillaSourceFailsInsteadOfFallingBackToNative() { - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); IrisStructure structure = new IrisStructure(); structure.setLoadKey("test:city"); when(data.load(IrisStructure.class, "test:city", false)).thenReturn(structure); @@ -327,7 +328,7 @@ public class IrisStructureLocatorContractTest { @Test public void missingNonReplacementStructureFailsInsteadOfBeingSkipped() { - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); IrisStructurePlacement placement = new IrisStructurePlacement(); placement.getStructures().add("test:missing"); IrisDimension dimension = mock(IrisDimension.class); @@ -752,7 +753,7 @@ public class IrisStructureLocatorContractTest { @Test public void placementIndexIsScopedAndInvalidatedPerEngine() { - IrisData sharedData = mock(IrisData.class); + IrisData sharedData = MockPackData.create(); Engine firstEngine = emptyEngine(sharedData); Engine secondEngine = emptyEngine(sharedData); Set firstIndex = IrisStructureLocator.placedKeys(firstEngine); @@ -1089,7 +1090,7 @@ public class IrisStructureLocatorContractTest { private Engine densityEngine(double density, boolean underground, int worldMin, int worldHeight, int placementMin, int placementMax) { - IrisData data = mock(IrisData.class); + IrisData data = MockPackData.create(); IrisStructure structure = new IrisStructure(); structure.setLoadKey("test:density"); when(data.load(IrisStructure.class, "test:density", false)).thenReturn(structure); diff --git a/core/src/test/java/art/arcane/iris/structure/placement/IrisStructureStrataTest.java b/core/src/test/java/art/arcane/iris/structure/placement/IrisStructureStrataTest.java index 89f6e420a..61b05d244 100644 --- a/core/src/test/java/art/arcane/iris/structure/placement/IrisStructureStrataTest.java +++ b/core/src/test/java/art/arcane/iris/structure/placement/IrisStructureStrataTest.java @@ -1,7 +1,13 @@ package art.arcane.iris.structure.placement; +import art.arcane.iris.generation.runtime.PackRuntime; +import art.arcane.iris.testsupport.MockPackData; import art.arcane.iris.generation.biome.IrisBiome; +import art.arcane.iris.generation.block.IrisBlockData; import art.arcane.iris.generation.decoration.IrisOreBands; +import art.arcane.iris.generation.decoration.IrisOreGenerator; +import art.arcane.iris.generation.terrain.IrisMaterialPalette; +import art.arcane.iris.pack.value.IrisRange; import art.arcane.iris.generation.image.IrisImageMapRuntime; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.IrisComplex; @@ -23,6 +29,7 @@ import org.junit.Test; import java.util.List; +import static org.mockito.ArgumentMatchers.same; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.mockito.ArgumentMatchers.any; @@ -46,7 +53,7 @@ public class IrisStructureStrataTest { private final IrisComplex complex = mock(IrisComplex.class); private final IrisBiome biome = mock(IrisBiome.class); private final IrisImageMapRuntime imageMap = mock(IrisImageMapRuntime.class); - private final IrisData data = mock(IrisData.class); + private final IrisData data = MockPackData.create(); private final IrisDimension dimension = new IrisDimension().setBedrock(true).setHideOresForHiddenOre(true); @Before @@ -62,7 +69,7 @@ public class IrisStructureStrataTest { when(complex.getRockStream()).thenReturn(ProceduralStream.of((x, z) -> rock, Interpolated.of(value -> 0D, value -> rock))); when(complex.getImageMapRuntime()).thenReturn(imageMap); when(biome.generateLayersWithSlope(eq(dimension), anyDouble(), anyDouble(), any(RNG.class), - anyInt(), anyInt(), eq(data), any())).thenReturn(new KList<>(List.of(grass, dirt, dirt))); + anyInt(), anyInt(), MockPackData.runtimeOf(data), any())).thenReturn(new KList<>(List.of(grass, dirt, dirt))); } @Test @@ -82,7 +89,7 @@ public class IrisStructureStrataTest { IrisStructureStrata.world(engine).column(3, 5, 90, false); verify(biome).generateLayersWithSlope(eq(dimension), eq(3D), eq(5D), any(RNG.class), - eq(90 - MIN_HEIGHT), eq(90 - MIN_HEIGHT), eq(data), any()); + eq(90 - MIN_HEIGHT), eq(90 - MIN_HEIGHT), MockPackData.runtimeOf(data), any()); } @Test @@ -107,11 +114,12 @@ public class IrisStructureStrataTest { public void oreBandsAreSampledAtEachHeightSoAFillNeverStretchesOneOreBlock() { dimension.setHideOresForHiddenOre(false); NativeBlockState coal = state("minecraft:coal_ore"); - IrisOreBands bands = mock(IrisOreBands.class); + IrisOreGenerator coalSeam = new IrisOreGenerator() + .setPalette(new FixedPalette(coal)) + .setThreshold(1D) + .setRange(new IrisRange(40 - MIN_HEIGHT, 40 - MIN_HEIGHT)); when(biome.getSurfaceOreBands()).thenReturn(IrisOreBands.EMPTY); - when(biome.getUndergroundOreBands()).thenReturn(bands); - when(bands.contains(anyInt())).thenReturn(true); - when(bands.generate(eq(3), eq(40 - MIN_HEIGHT), eq(5), any(RNG.class), eq(data), any())).thenReturn(coal); + when(biome.getUndergroundOreBands()).thenReturn(IrisOreBands.of(new KList<>(List.of(coalSeam)))); StructureStrata.Column column = IrisStructureStrata.world(engine).column(3, 5, 90, false); @@ -119,6 +127,20 @@ public class IrisStructureStrataTest { assertSame(rock, column.block(41)); } + private static final class FixedPalette extends IrisMaterialPalette { + private final NativeBlockState state; + + private FixedPalette(NativeBlockState state) { + this.state = state; + setPalette(new KList<>(new IrisBlockData())); + } + + @Override + public NativeBlockState get(RNG rng, double x, double y, double z, PackRuntime runtime) { + return state; + } + } + private static NativeBlockState state(String key) { NativeBlockState state = mock(NativeBlockState.class); when(state.key()).thenReturn(key); diff --git a/core/src/test/java/art/arcane/iris/structure/placement/StructurePlacementScopeTest.java b/core/src/test/java/art/arcane/iris/structure/placement/StructurePlacementScopeTest.java index 6cfaa9370..26b767658 100644 --- a/core/src/test/java/art/arcane/iris/structure/placement/StructurePlacementScopeTest.java +++ b/core/src/test/java/art/arcane/iris/structure/placement/StructurePlacementScopeTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.structure.placement; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.IrisComplex; @@ -19,6 +20,31 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class StructurePlacementScopeTest { + @Test + public void scopeIndexIsHeldOnlyUntilTheEngineInvalidatesIt() { + Engine liveEngine = engineWithoutStructures(); + Engine closedEngine = engineWithoutStructures(); + when(closedEngine.isClosed()).thenReturn(true); + + StructurePlacementScope.placementsAt(liveEngine, 0, 0); + StructurePlacementScope.placementsAt(closedEngine, 0, 0); + + assertTrue(StructurePlacementScope.isIndexed(liveEngine)); + assertFalse(StructurePlacementScope.isIndexed(closedEngine)); + StructurePlacementScope.invalidate(liveEngine); + assertFalse(StructurePlacementScope.isIndexed(liveEngine)); + } + + private static Engine engineWithoutStructures() { + Engine engine = mock(Engine.class, RETURNS_DEEP_STUBS); + IrisDimension dimension = mock(IrisDimension.class); + when(engine.getDimension()).thenReturn(dimension); + when(engine.getAllBiomes()).thenReturn(new KList<>()); + when(dimension.getStructures()).thenReturn(new KList<>()); + when(dimension.getAllRegions(engine)).thenReturn(new KList<>()); + return engine; + } + @Test public void caveBiomeContributesOnlyCaveAnchoredPlacements() { IrisStructurePlacement surfacePlacement = new IrisStructurePlacement(); diff --git a/core/src/test/java/art/arcane/iris/testsupport/GeneratorSampling.java b/core/src/test/java/art/arcane/iris/testsupport/GeneratorSampling.java index 79370d729..dd008261a 100644 --- a/core/src/test/java/art/arcane/iris/testsupport/GeneratorSampling.java +++ b/core/src/test/java/art/arcane/iris/testsupport/GeneratorSampling.java @@ -1,7 +1,7 @@ package art.arcane.iris.testsupport; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.generation.noise.IrisGeneratorStyle; -import art.arcane.iris.pack.loading.IrisData; import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.noise.CNG; @@ -13,8 +13,8 @@ public final class GeneratorSampling { private GeneratorSampling() { } - public static double[] sampleSharedGenerator(IrisGeneratorStyle style, RNG seed, IrisData packData) { - return sampleAtBlocks(style.create(seed, packData), SAMPLE_BLOCKS); + public static double[] sampleSharedGenerator(IrisGeneratorStyle style, RNG seed, PackRuntime runtime) { + return sampleAtBlocks(style.create(seed, runtime), SAMPLE_BLOCKS); } public static double[] sampleAtBlocks(CNG generator, double[][] blocks) { diff --git a/core/src/test/java/art/arcane/iris/testsupport/MockPackData.java b/core/src/test/java/art/arcane/iris/testsupport/MockPackData.java new file mode 100644 index 000000000..b062c5b6e --- /dev/null +++ b/core/src/test/java/art/arcane/iris/testsupport/MockPackData.java @@ -0,0 +1,47 @@ +package art.arcane.iris.testsupport; + +import art.arcane.iris.generation.biome.PaletteLayerRuntime; +import art.arcane.iris.generation.decoration.DecoratorRuntime; +import art.arcane.iris.generation.runtime.PackRuntime; +import art.arcane.iris.pack.loading.IrisData; + +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.withSettings; + +/** + * Mocked pack data that still owns a standalone runtime scope, the way loaded pack data does. + */ +public final class MockPackData { + private MockPackData() { + } + + public static IrisData create() { + return withStandaloneRuntime(mock(IrisData.class)); + } + + public static IrisData stubOnly() { + return withStandaloneRuntime(mock(IrisData.class, withSettings().stubOnly())); + } + + /** Matches a runtime scope of this pack data, without touching the data mock while stubbing. */ + public static PackRuntime runtimeOf(IrisData data) { + return argThat(runtime -> runtime != null && runtime.data() == data); + } + + /** Matches a palette layer runtime built in a runtime scope of this pack data. */ + public static PaletteLayerRuntime paletteLayerRuntimeOf(IrisData data) { + return argThat(runtime -> runtime != null && runtime.packRuntime().data() == data); + } + + /** Matches a decorator runtime built in a runtime scope of this pack data. */ + public static DecoratorRuntime decoratorRuntimeOf(IrisData data) { + return argThat(runtime -> runtime != null && runtime.packRuntime().data() == data); + } + + private static IrisData withStandaloneRuntime(IrisData data) { + doReturn(PackRuntime.standalone(data)).when(data).standalonePackRuntime(); + return data; + } +} diff --git a/core/src/test/java/art/arcane/iris/testsupport/RunningEnginePackData.java b/core/src/test/java/art/arcane/iris/testsupport/RunningEnginePackData.java index e6bbefd8e..f21ee71a5 100644 --- a/core/src/test/java/art/arcane/iris/testsupport/RunningEnginePackData.java +++ b/core/src/test/java/art/arcane/iris/testsupport/RunningEnginePackData.java @@ -1,6 +1,7 @@ package art.arcane.iris.testsupport; import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.generation.runtime.PackRuntime; import art.arcane.iris.pack.loading.IrisData; import static org.mockito.Mockito.mock; @@ -12,7 +13,9 @@ public final class RunningEnginePackData { public static IrisData create() { IrisData packData = mock(IrisData.class); - when(packData.getEngine()).thenReturn(mock(Engine.class)); + Engine engine = mock(Engine.class); + when(engine.getPackRuntime()).thenReturn(PackRuntime.forEngine(engine, packData)); + when(packData.getEngine()).thenReturn(engine); return packData; } } diff --git a/probe/src/test/java/art/arcane/iris/probe/EngineReleaseProbeTest.java b/probe/src/test/java/art/arcane/iris/probe/EngineReleaseProbeTest.java new file mode 100644 index 000000000..d8eb34a72 --- /dev/null +++ b/probe/src/test/java/art/arcane/iris/probe/EngineReleaseProbeTest.java @@ -0,0 +1,142 @@ +package art.arcane.iris.probe; + +import art.arcane.iris.generation.biome.IrisBiome; +import art.arcane.iris.generation.concurrent.MultiBurst; +import art.arcane.iris.generation.noise.IrisGenerator; +import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.generation.terrain.IrisDimension; +import art.arcane.iris.generation.terrain.IrisRegion; +import art.arcane.iris.pack.loading.IrisData; +import art.arcane.iris.testsupport.IrisRuntimeState; +import com.sun.management.HotSpotDiagnosticMXBean; +import org.junit.After; +import org.junit.Test; + +import java.lang.management.ManagementFactory; +import java.lang.ref.WeakReference; +import java.net.URL; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.Callable; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.ForkJoinTask; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * A closed engine must become unreachable while everything that outlives it stays alive: the pack objects it read and + * the pooled generation workers that ran it. Anything engine-derived parked on either one pins the engine and, in a + * server, the whole world it generated. + */ +public class EngineReleaseProbeTest { + private static final long SEED = 7_331L; + private static final String DIMENSION = "release"; + private static final int CHUNK_SPAN = 4; + private static final int COLLECTION_ATTEMPTS = 40; + private static final long COLLECTION_PAUSE_MILLIS = 50L; + private static final long WORKER_TASK_TIMEOUT_SECONDS = 60L; + private static final String HEAP_DUMP_ENVIRONMENT = "IRIS_ENGINE_RELEASE_HEAP_DUMP"; + + @After + public void resetRuntime() { + IrisRuntimeState.reset(); + } + + @Test(timeout = 300_000) + public void closedEngineIsCollectableWhilePackObjectsAndWorkersStayAlive() throws Exception { + List survivingPackObjects = new ArrayList<>(); + WeakReference closedEngine; + try (RealPackProbeSupport.Workspace workspace = RealPackProbeSupport.openWorkspace( + fixturePack().toFile(), DIMENSION, "[engine-release]")) { + closedEngine = generateAndClose(workspace, survivingPackObjects); + } + ForkJoinPool workers = generationWorkers(); + assertTrue("Generation workers must still be alive for the check to mean anything", + workers.getPoolSize() > 0); + boolean released = collected(closedEngine); + if (!released) { + dumpHeapWhenRequested(); + } + assertTrue("A closed engine is still reachable from pack objects or worker threads", released); + assertTrue("Pack objects must outlive the engine", !survivingPackObjects.isEmpty()); + } + + private static WeakReference generateAndClose( + RealPackProbeSupport.Workspace workspace, + List survivingPackObjects + ) throws Exception { + try (RealPackProbeSupport.EngineSession session = workspace.openEngine(SEED, true, "release")) { + Engine engine = session.engine(); + retainPackObjects(engine.getData(), engine.getDimension(), survivingPackObjects); + generateOnCallerAndWorkers(engine); + RealPackProbeSupport.settleAndDrain(engine); + return new WeakReference<>(engine); + } + } + + private static void retainPackObjects(IrisData data, IrisDimension dimension, List survivors) { + survivors.add(dimension); + for (String regionKey : dimension.getRegions()) { + IrisRegion region = data.getRegionLoader().load(regionKey); + assertNotNull("Fixture region " + regionKey, region); + survivors.add(region); + for (String biomeKey : region.getLandBiomes()) { + IrisBiome biome = data.getBiomeLoader().load(biomeKey); + assertNotNull("Fixture biome " + biomeKey, biome); + survivors.add(biome); + } + } + IrisGenerator generator = data.getGeneratorLoader().load("terrain"); + assertNotNull("Fixture generator", generator); + survivors.add(generator); + } + + private static void generateOnCallerAndWorkers(Engine engine) throws Exception { + List> workerChunks = new ArrayList<>(); + for (int chunkX = 0; chunkX < CHUNK_SPAN; chunkX++) { + for (int chunkZ = 0; chunkZ < CHUNK_SPAN; chunkZ++) { + if (((chunkX + chunkZ) & 1) == 0) { + RealPackProbeSupport.generateChunk(engine, chunkX, chunkZ); + continue; + } + int x = chunkX; + int z = chunkZ; + workerChunks.add(MultiBurst.burst.submit(() -> RealPackProbeSupport.generateChunk(engine, x, z))); + } + } + for (Future chunk : workerChunks) { + chunk.get(WORKER_TASK_TIMEOUT_SECONDS, TimeUnit.SECONDS); + } + } + + private static ForkJoinPool generationWorkers() throws Exception { + return MultiBurst.burst.submit((Callable) ForkJoinTask::getPool) + .get(WORKER_TASK_TIMEOUT_SECONDS, TimeUnit.SECONDS); + } + + private static boolean collected(WeakReference reference) throws InterruptedException { + for (int attempt = 0; attempt < COLLECTION_ATTEMPTS && reference.get() != null; attempt++) { + System.gc(); + Thread.sleep(COLLECTION_PAUSE_MILLIS); + } + return reference.get() == null; + } + + private static void dumpHeapWhenRequested() throws Exception { + String destination = System.getenv(HEAP_DUMP_ENVIRONMENT); + if (destination == null || destination.isBlank()) { + return; + } + ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class).dumpHeap(destination, true); + } + + private static Path fixturePack() throws Exception { + URL resource = Objects.requireNonNull(EngineReleaseProbeTest.class.getResource("/engine-release")); + return Path.of(resource.toURI()); + } +} diff --git a/probe/src/test/resources/engine-release/biomes/terrain.json b/probe/src/test/resources/engine-release/biomes/terrain.json new file mode 100644 index 000000000..5b9d184df --- /dev/null +++ b/probe/src/test/resources/engine-release/biomes/terrain.json @@ -0,0 +1,23 @@ +{ + "name": "Terrain", + "derivative": "minecraft:plains", + "vanillaDerivative": "minecraft:plains", + "layers": [{ + "minHeight": 2, + "maxHeight": 5, + "style": {"style": "SIMPLEX", "zoom": 3}, + "palette": [{"block": "minecraft:stone"}, {"block": "minecraft:andesite"}] + }], + "generators": [{"generator": "terrain", "min": 20, "max": 30}], + "decorators": [{ + "chance": 0.61, + "style": {"style": "SIMPLEX", "zoom": 7}, + "variance": {"style": "SIMPLEX", "zoom": 4}, + "heightVariance": {"style": "SIMPLEX", "zoom": 9}, + "forcePlace": true, + "stackMin": 1, + "stackMax": 5, + "palette": [{"block": "minecraft:stone"}, {"block": "minecraft:dirt"}], + "topPalette": [{"block": "minecraft:granite"}, {"block": "minecraft:andesite"}] + }] +} diff --git a/probe/src/test/resources/engine-release/dimensions/release.json b/probe/src/test/resources/engine-release/dimensions/release.json new file mode 100644 index 000000000..501a54ae3 --- /dev/null +++ b/probe/src/test/resources/engine-release/dimensions/release.json @@ -0,0 +1,11 @@ +{ + "name": "Engine release fixture", + "version": 1, + "mode": {"type": "OVERWORLD"}, + "regions": ["terrain"], + "environment": "NORMAL", + "dimensionHeight": {"min": 0, "max": 64}, + "logicalHeight": 64, + "fluidHeight": 10, + "caveProfile": {"enabled": false} +} diff --git a/probe/src/test/resources/engine-release/generators/terrain.json b/probe/src/test/resources/engine-release/generators/terrain.json new file mode 100644 index 000000000..68b3b98e2 --- /dev/null +++ b/probe/src/test/resources/engine-release/generators/terrain.json @@ -0,0 +1,5 @@ +{ + "seed": 310, + "interpolator": {"function": "NONE", "horizontalScale": 1}, + "composite": [{"seed": 310, "style": {"style": "SIMPLEX", "zoom": 19}}] +} diff --git a/probe/src/test/resources/engine-release/regions/terrain.json b/probe/src/test/resources/engine-release/regions/terrain.json new file mode 100644 index 000000000..27710a70d --- /dev/null +++ b/probe/src/test/resources/engine-release/regions/terrain.json @@ -0,0 +1,6 @@ +{ + "name": "Terrain", + "landBiomes": ["terrain"], + "seaBiomes": ["terrain"], + "shoreBiomes": ["terrain"] +} From fc5db87514443e0afc6321a34436ecd795a16b12 Mon Sep 17 00:00:00 2001 From: Piexel <107539181+piexelated@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:40:08 +0100 Subject: [PATCH 02/12] Skip unused broken packs (#1265) - Skip unloadable packs no world uses and name them - Fail compilation naming the pack and worlds that use it - Exclude skipped packs from registry requirements - Always create the dimension type folder --- .../pack/datapack/IrisDatapackCompiler.java | 88 ++++++++--- .../arcane/iris/pack/datapack/PackUse.java | 111 ++++++++++++++ .../DefaultPackBootstrapProvisionerTest.java | 2 +- .../datapack/IrisDatapackCompilerTest.java | 139 ++++++++++++++++++ 4 files changed, 317 insertions(+), 23 deletions(-) create mode 100644 core/src/main/java/art/arcane/iris/pack/datapack/PackUse.java diff --git a/core/src/main/java/art/arcane/iris/pack/datapack/IrisDatapackCompiler.java b/core/src/main/java/art/arcane/iris/pack/datapack/IrisDatapackCompiler.java index 05c58959c..93f75d7ee 100644 --- a/core/src/main/java/art/arcane/iris/pack/datapack/IrisDatapackCompiler.java +++ b/core/src/main/java/art/arcane/iris/pack/datapack/IrisDatapackCompiler.java @@ -63,6 +63,7 @@ public final class IrisDatapackCompiler { private static final int INPUT_FINGERPRINT_SCHEMA = 4; private static final int INPUT_BUFFER_BYTES = 64 * 1024; private static final int WORLD_PACK_SCAN_DEPTH = 8; + private static final String DIMENSION_TYPE_FOLDER = "data/iris/dimension_type"; private static final Pattern REGISTRY_KEY_PATTERN = Pattern.compile("[a-z0-9_.-]+:[a-z0-9/._-]+"); private static final List INPUT_DIRECTORIES = List.of("dimensions", "biomes", "snippet"); private static final String FLAT_VOID_LEVEL_STEM = """ @@ -210,16 +211,7 @@ public final class IrisDatapackCompiler { if (aliasContext.retainedContract() != null) { data.bindGenerationRegistryContract(aliasContext.retainedContract()); } - ResourceLoader loader = data.getDimensionLoader(); - String[] possibleKeys = loader.getPossibleKeys(); - if (possibleKeys == null || possibleKeys.length == 0) { - throw new IOException("Iris pack has no dimension definitions: " + packRoot); - } - for (String possibleKey : possibleKeys) { - IrisDimension dimension = loader.load(possibleKey); - if (dimension == null) { - throw new IOException("Unable to load Iris dimension '" + possibleKey + "' from " + packRoot); - } + for (IrisDimension dimension : loadPack(data).dimensions()) { collectRegistryRequirements( requirements, biomeTags, @@ -455,6 +447,7 @@ public final class IrisDatapackCompiler { Map> biomes = new LinkedHashMap<>(); Map> dimensions = new LinkedHashMap<>(); Map histories = new LinkedHashMap<>(); + PackUse packUse = new PackUse(packRoots, normalizedBindings); int packCount = 0; int dimensionCount = 0; for (File packRoot : packRoots) { @@ -468,18 +461,8 @@ public final class IrisDatapackCompiler { if (aliasContext.retainedContract() != null) { data.bindGenerationRegistryContract(aliasContext.retainedContract()); } - ResourceLoader loader = data.getDimensionLoader(); - String[] possibleKeys = loader.getPossibleKeys(); - if (possibleKeys == null || possibleKeys.length == 0) { - throw new IOException("Iris pack has no dimension definitions: " + packRoot); - } - int installedDimensions = 0; - for (String possibleKey : possibleKeys) { - IrisDimension dimension = loader.load(possibleKey); - if (dimension == null) { - throw new IOException("Unable to load Iris dimension '" + possibleKey + "' from " + packRoot); - } + for (IrisDimension dimension : dimensionsOfUsedPack(packRoot, loadPack(data), packUse)) { IrisLogging.debug(" Compiling Dimension " + dimension.getLoadFile().getPath()); height.merge(dimension); dimensions.computeIfAbsent(dimension.getLoadKey(), ignored -> new ArrayList<>()) @@ -514,12 +497,73 @@ public final class IrisDatapackCompiler { } IrisDimension.writeShared(datapackRoots, height, adjustVanillaHeight); + createDimensionTypeFolders(datapackRoots); installRetainedRegistrySources(packRoots, datapackRoots, fixer, histories); installLevelStemBindings(normalizedBindings, dimensions, datapackRoots); validateOutputs(datapackRoots, dimensionCount, normalizedBindings.size()); return new CompilationResult(packCount, dimensionCount, countBiomes(biomes)); } + /** + * A pack that cannot load stops the compile when a world uses it, so the server never starts that world without + * its dimension; a pack no world uses is left out with a warning. + */ + private static List dimensionsOfUsedPack(File packRoot, LoadedPack pack, PackUse packUse) + throws IOException { + if (pack.loads()) { + return pack.dimensions(); + } + List users = packUse.worldsUsing(packRoot, pack.dimensionKeys()); + if (!users.isEmpty()) { + throw new IOException("Iris pack " + packRoot + " cannot load (" + pack.refusal() + ") and world(s) " + + String.join(", ", users) + " use it. Fix the pack, then start the server again."); + } + IrisLogging.warn("Iris pack %s cannot load (%s). No world uses it, so it is left out and the server starts.", + packRoot, pack.refusal()); + return List.of(); + } + + /** Every dimension of the pack, or none with the reason when any of them cannot load; never part of a pack. */ + private static LoadedPack loadPack(IrisData data) { + ResourceLoader loader = data.getDimensionLoader(); + String[] possibleKeys = loader.getPossibleKeys(); + if (possibleKeys == null || possibleKeys.length == 0) { + return LoadedPack.refused(List.of(), "it has no dimension definitions"); + } + List dimensionKeys = List.of(possibleKeys); + List loaded = new ArrayList<>(); + for (String key : dimensionKeys) { + IrisDimension dimension; + try { + dimension = loader.load(key); + } catch (RuntimeException failure) { + return LoadedPack.refused(dimensionKeys, "its dimension '" + key + "' failed to load: " + failure.getMessage()); + } + if (dimension == null) { + return LoadedPack.refused(dimensionKeys, "its dimension '" + key + "' failed to load; the error above says why"); + } + loaded.add(dimension); + } + return new LoadedPack(dimensionKeys, List.copyOf(loaded), null); + } + + private record LoadedPack(List dimensionKeys, List dimensions, String refusal) { + static LoadedPack refused(List dimensionKeys, String refusal) { + return new LoadedPack(dimensionKeys, List.of(), refusal); + } + + boolean loads() { + return refusal == null; + } + } + + /** The dimension type folder exists in every compiled datapack, so one built only from left-out packs reads as complete. */ + private static void createDimensionTypeFolders(Collection datapackRoots) throws IOException { + for (File datapackRoot : datapackRoots) { + Files.createDirectories(datapackRoot.toPath().resolve(DIMENSION_TYPE_FOLDER)); + } + } + public static void installRetainedRegistrySources(List packRoots, Collection datapackRoots, IDataFixer fixer) throws IOException { installRetainedRegistrySources(packRoots, datapackRoots, fixer, new LinkedHashMap<>()); @@ -988,7 +1032,7 @@ public final class IrisDatapackCompiler { if (!Files.isRegularFile(root.resolve("pack.mcmeta"))) { throw new IOException("Iris datapack metadata was not generated at " + root); } - if (dimensionCount > 0 && !Files.isDirectory(root.resolve("data/iris/dimension_type"))) { + if (dimensionCount > 0 && !Files.isDirectory(root.resolve(DIMENSION_TYPE_FOLDER))) { throw new IOException("Iris dimension types were not generated at " + root); } if (levelStemCount > 0 && !Files.isDirectory(root.resolve("data/iris/dimension"))) { diff --git a/core/src/main/java/art/arcane/iris/pack/datapack/PackUse.java b/core/src/main/java/art/arcane/iris/pack/datapack/PackUse.java new file mode 100644 index 000000000..23a7ffa4b --- /dev/null +++ b/core/src/main/java/art/arcane/iris/pack/datapack/PackUse.java @@ -0,0 +1,111 @@ +package art.arcane.iris.pack.datapack; + +import art.arcane.iris.world.WorldSlotKey; +import art.arcane.iris.world.lifecycle.BukkitWorldConfiguration.IrisGeneratorBinding; + +import java.io.File; +import java.nio.file.Path; +import java.util.Collection; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * Which worlds use a pack the startup datapack is compiled from. A pack copied into a world's folder + * ({@code /iris/pack} or {@code /iris/generation/epochs//pack}) belongs to that world, configured + * or not. A pack installed in Iris's own folder is used by every bound world that selects one of its dimensions and + * has no copy of its own. + */ +final class PackUse { + private static final String DIMENSIONS_FOLDER = "dimensions"; + private static final String WORLD_IRIS_FOLDER = "iris"; + private static final String WORLD_PACK_FOLDER = "pack"; + private static final String GENERATION_FOLDER = "generation"; + private static final String EPOCHS_FOLDER = "epochs"; + + private final Set worldsWithOwnPack; + private final List bindings; + + PackUse(Collection packRoots, List bindings) { + this.worldsWithOwnPack = packRoots.stream() + .map(root -> worldFolderOwning(root.toPath())) + .flatMap(Optional::stream) + .map(PackUse::slotKeyOf) + .flatMap(Optional::stream) + .collect(Collectors.toUnmodifiableSet()); + this.bindings = List.copyOf(bindings); + } + + /** The names of the worlds that use the pack at {@code packRoot}, which defines {@code dimensions}. */ + List worldsUsing(File packRoot, Collection dimensions) { + Optional ownerFolder = worldFolderOwning(packRoot.toPath()); + if (ownerFolder.isPresent()) { + return List.of(nameOfWorld(ownerFolder.get())); + } + return bindings.stream() + .filter(binding -> dimensions.contains(binding.dimension())) + .filter(binding -> !worldsWithOwnPack.contains(binding.worldKey())) + .map(IrisGeneratorBinding::configuredWorldName) + .toList(); + } + + private String nameOfWorld(Path worldFolder) { + Optional worldKey = slotKeyOf(worldFolder); + if (worldKey.isEmpty()) { + return nameOf(worldFolder); + } + return bindings.stream() + .filter(binding -> binding.worldKey().equals(worldKey.get())) + .map(IrisGeneratorBinding::configuredWorldName) + .findFirst() + .orElse(worldKey.get().toString()); + } + + /** The folder of the world whose copy the pack at {@code packRoot} is, or empty for a pack installed outside any world. */ + static Optional worldFolderOwning(Path packRoot) { + Path pack = packRoot.toAbsolutePath().normalize(); + if (!WORLD_PACK_FOLDER.equals(nameOf(pack))) { + return Optional.empty(); + } + Path parent = pack.getParent(); + if (WORLD_IRIS_FOLDER.equals(nameOf(parent))) { + return Optional.ofNullable(parent.getParent()); + } + Path epochs = parentOf(parent); + Path generation = parentOf(epochs); + Path iris = parentOf(generation); + if (EPOCHS_FOLDER.equals(nameOf(epochs)) + && GENERATION_FOLDER.equals(nameOf(generation)) + && WORLD_IRIS_FOLDER.equals(nameOf(iris))) { + return Optional.ofNullable(iris.getParent()); + } + return Optional.empty(); + } + + /** The key of a world stored at {@code /dimensions//}, or empty for the level's own folder. */ + static Optional slotKeyOf(Path worldFolder) { + for (Path namespace = parentOf(worldFolder); namespace != null; namespace = namespace.getParent()) { + if (DIMENSIONS_FOLDER.equals(nameOf(namespace.getParent()))) { + return slotKey(nameOf(namespace), namespace.relativize(worldFolder)); + } + } + return Optional.empty(); + } + + private static Optional slotKey(String namespace, Path world) { + try { + return Optional.of(new WorldSlotKey(namespace, world.toString().replace(File.separatorChar, '/'))); + } catch (IllegalArgumentException notAWorldKey) { + return Optional.empty(); + } + } + + private static Path parentOf(Path path) { + return path == null ? null : path.getParent(); + } + + private static String nameOf(Path path) { + return path == null || path.getFileName() == null ? null : path.getFileName().toString(); + } +} diff --git a/core/src/test/java/art/arcane/iris/pack/DefaultPackBootstrapProvisionerTest.java b/core/src/test/java/art/arcane/iris/pack/DefaultPackBootstrapProvisionerTest.java index 17c569198..ee3de8406 100644 --- a/core/src/test/java/art/arcane/iris/pack/DefaultPackBootstrapProvisionerTest.java +++ b/core/src/test/java/art/arcane/iris/pack/DefaultPackBootstrapProvisionerTest.java @@ -588,7 +588,7 @@ public class DefaultPackBootstrapProvisionerTest { byte[] metadata = Files.readAllBytes(first.datapackRoot().resolve("pack.mcmeta")); byte[] originalOverworld = Files.readAllBytes(dataDirectory.resolve("packs/overworld/biomes/local.json")); byte[] originalUnderworld = Files.readAllBytes(dataDirectory.resolve("packs/underworld/biomes/local.json")); - Path invalidPack = dataDirectory.resolve("packs/invalid"); + Path invalidPack = root.resolve("dimensions/iris/broken_world/iris/pack"); Files.createDirectories(invalidPack.resolve("dimensions")); Files.writeString(invalidPack.resolve("dimensions/broken.json"), "{", StandardCharsets.UTF_8); updateServer = server( diff --git a/core/src/test/java/art/arcane/iris/pack/datapack/IrisDatapackCompilerTest.java b/core/src/test/java/art/arcane/iris/pack/datapack/IrisDatapackCompilerTest.java index 97e0eb1a6..66eaf1cfa 100644 --- a/core/src/test/java/art/arcane/iris/pack/datapack/IrisDatapackCompilerTest.java +++ b/core/src/test/java/art/arcane/iris/pack/datapack/IrisDatapackCompilerTest.java @@ -35,6 +35,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.stream.Stream; import static org.junit.Assert.assertEquals; @@ -388,6 +389,144 @@ public class IrisDatapackCompilerTest { assertTrue(failure.getMessage().contains("selects missing dimension \"missing\"")); } + @Test + public void leavesOutAPackThatCannotLoadWhenNoWorldUsesIt() throws Exception { + Path workingPack = temporaryFolder.newFolder("unused-refused-working").toPath(); + Path refusedPack = temporaryFolder.newFolder("unused-refused-broken").toPath(); + Path datapackRoot = temporaryFolder.newFolder("unused-refused-datapack").toPath(); + createPack(workingPack, "working", "working_custom"); + createRefusedPack(refusedPack, "broken"); + + IrisDatapackCompiler.CompilationResult result = IrisDatapackCompiler.compile( + List.of(workingPack.toFile(), refusedPack.toFile()), + new KList().qadd(datapackRoot.toFile()), + List.of(binding("moon", "working")), + new DataFixerV1217(), + false + ); + + assertEquals(1, result.packCount()); + assertEquals(1, result.dimensionCount()); + assertTrue(Files.isRegularFile(datapackRoot.resolve("data/iris/dimension/moon.json"))); + } + + @Test + public void leftOutPacksStillProduceACompleteDatapack() throws Exception { + Path refusedPack = temporaryFolder.newFolder("only-refused-broken").toPath(); + Path datapackRoot = temporaryFolder.newFolder("only-refused-datapack").toPath(); + createRefusedPack(refusedPack, "broken"); + + IrisDatapackCompiler.CompilationResult result = IrisDatapackCompiler.compile( + List.of(refusedPack.toFile()), + new KList().qadd(datapackRoot.toFile()), + List.of(), + new DataFixerV1217(), + false + ); + + assertEquals(0, result.dimensionCount()); + assertTrue(Files.isRegularFile(datapackRoot.resolve("pack.mcmeta"))); + assertTrue(Files.isDirectory(datapackRoot.resolve("data/iris/dimension_type"))); + } + + @Test + public void registryRequirementsLeaveOutAPackThatCannotLoad() throws Exception { + Path workingPack = temporaryFolder.newFolder("requirements-working").toPath(); + Path refusedPack = temporaryFolder.newFolder("requirements-broken").toPath(); + createPack(workingPack, "working", "working_custom"); + createRefusedPack(refusedPack, "broken"); + DataFixerV1217 fixer = new DataFixerV1217(); + + Map withRefused = IrisDatapackCompiler.computeRegistryRequirements( + List.of(workingPack.toFile(), refusedPack.toFile()), + fixer); + Map withoutRefused = IrisDatapackCompiler.computeRegistryRequirements( + List.of(workingPack.toFile()), + fixer); + + assertEquals(withoutRefused, withRefused); + } + + @Test + public void stopsTheCompileWhenABoundWorldSelectsAPackThatCannotLoad() throws Exception { + Path refusedPack = temporaryFolder.newFolder("bound-refused-broken").toPath(); + Path datapackRoot = temporaryFolder.newFolder("bound-refused-datapack").toPath(); + createRefusedPack(refusedPack, "broken"); + + IOException failure = assertThrows( + IOException.class, + () -> IrisDatapackCompiler.compile( + List.of(refusedPack.toFile()), + new KList().qadd(datapackRoot.toFile()), + List.of(binding("moon", "broken")), + new DataFixerV1217(), + false + ) + ); + + assertTrue(failure.getMessage(), failure.getMessage().contains(refusedPack.toString())); + assertTrue(failure.getMessage(), failure.getMessage().contains("world(s) world_iris_moon use it")); + } + + @Test + public void stopsTheCompileWhenAWorldsOwnPackCannotLoad() throws Exception { + Path serverRoot = temporaryFolder.newFolder("own-refused-server").toPath(); + Path ownPack = serverRoot.resolve("dimensions/iris/moon/iris/pack"); + Path datapackRoot = temporaryFolder.newFolder("own-refused-datapack").toPath(); + createRefusedPack(ownPack, "broken"); + + IOException failure = assertThrows( + IOException.class, + () -> IrisDatapackCompiler.compile( + List.of(ownPack.toFile()), + new KList().qadd(datapackRoot.toFile()), + List.of(), + new DataFixerV1217(), + false + ) + ); + + assertTrue(failure.getMessage(), failure.getMessage().contains("world(s) iris:moon use it")); + } + + @Test + public void aWorldWithItsOwnPackDoesNotUseAnInstalledPackThatCannotLoad() throws Exception { + Path serverRoot = temporaryFolder.newFolder("own-working-server").toPath(); + Path ownPack = serverRoot.resolve("dimensions/iris/moon/iris/pack"); + Path installedPack = temporaryFolder.newFolder("own-working-installed").toPath(); + Path datapackRoot = temporaryFolder.newFolder("own-working-datapack").toPath(); + createPack(ownPack, "shared", "shared_custom"); + createRefusedPack(installedPack, "shared"); + + IrisDatapackCompiler.CompilationResult result = IrisDatapackCompiler.compile( + List.of(installedPack.toFile(), ownPack.toFile()), + new KList().qadd(datapackRoot.toFile()), + List.of(binding("moon", "shared")), + new DataFixerV1217(), + false + ); + + assertEquals(1, result.dimensionCount()); + } + + @Test + public void findsTheWorldOwningEachWorldPackLayout() { + Path level = Path.of("/server/world"); + Path moon = level.resolve("dimensions/iris/moon"); + + assertEquals(Optional.of(moon), PackUse.worldFolderOwning(moon.resolve("iris/pack"))); + assertEquals(Optional.of(moon), PackUse.worldFolderOwning(moon.resolve("iris/generation/epochs/0001/pack"))); + assertEquals(Optional.of(level), PackUse.worldFolderOwning(level.resolve("iris/pack"))); + assertEquals(Optional.empty(), PackUse.worldFolderOwning(Path.of("/server/plugins/Iris/packs/pack"))); + assertEquals(Optional.of(new WorldSlotKey("iris", "moon")), PackUse.slotKeyOf(moon)); + assertEquals(Optional.empty(), PackUse.slotKeyOf(level)); + } + + private static void createRefusedPack(Path root, String dimensionKey) throws IOException { + Files.createDirectories(root.resolve("dimensions")); + Files.writeString(root.resolve("dimensions").resolve(dimensionKey + ".json"), "{", StandardCharsets.UTF_8); + } + @Test public void rejectsBindingToConflictingDuplicateDimension() throws Exception { Path firstPack = temporaryFolder.newFolder("ambiguous-binding-first").toPath(); From 6e078ad4a0d59db630b690c4939c1108169ee696 Mon Sep 17 00:00:00 2001 From: Piexel <107539181+piexelated@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:40:19 +0100 Subject: [PATCH 03/12] Add list snippets (#1271) - Expand JSON array snippet files into list entries - Read snippet values as JSON trees and skip malformed ones once - Route snippet references through one SnippetFolder lookup - Reject references that leave snippet//, including symlinks --- .../iris/modded/ModdedWorkspaceGenerator.java | 10 +- .../iris/pack/PackDimensionValidator.java | 23 +- .../pack/PackGeneratorDuplicateValidator.java | 12 +- .../iris/pack/PackHydrologyValidator.java | 9 +- .../iris/pack/PackStaticObjectValidator.java | 10 +- .../pack/PackStyledRangeDefaultValidator.java | 14 +- .../iris/pack/PackTerrain3DValidator.java | 11 +- .../arcane/iris/pack/ingest/IngestPack.java | 4 +- .../arcane/iris/pack/loading/IrisData.java | 224 +++++++++++---- .../iris/pack/loading/SnippetFolder.java | 69 +++++ .../studio/workspace/IrisCodeWorkspace.java | 9 +- .../IrisDataSnippetMalformedValueTest.java | 111 ++++++++ .../loading/IrisDataSnippetPackWalkTest.java | 261 ++++++++++++++++++ .../pack/loading/IrisDataSnippetTest.java | 202 ++++++++++++++ 14 files changed, 857 insertions(+), 112 deletions(-) create mode 100644 core/src/main/java/art/arcane/iris/pack/loading/SnippetFolder.java create mode 100644 core/src/test/java/art/arcane/iris/pack/loading/IrisDataSnippetMalformedValueTest.java create mode 100644 core/src/test/java/art/arcane/iris/pack/loading/IrisDataSnippetPackWalkTest.java create mode 100644 core/src/test/java/art/arcane/iris/pack/loading/IrisDataSnippetTest.java diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedWorkspaceGenerator.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedWorkspaceGenerator.java index 55b9b8cb7..2587d2892 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedWorkspaceGenerator.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedWorkspaceGenerator.java @@ -20,18 +20,18 @@ package art.arcane.iris.modded; import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.pack.loading.ResourceLoader; +import art.arcane.iris.pack.loading.SnippetFolder; import art.arcane.iris.pack.schema.SchemaBuilder; import art.arcane.iris.pack.schema.annotation.Snippet; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.world.task.J; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.format.Form; import art.arcane.volmlib.util.io.IO; import art.arcane.volmlib.util.json.JSONArray; import art.arcane.volmlib.util.json.JSONObject; import java.io.File; import java.io.IOException; +import java.util.List; public final class ModdedWorkspaceGenerator { private ModdedWorkspaceGenerator() { @@ -100,11 +100,7 @@ public final class ModdedWorkspaceGenerator { try { String snipType = snippetClass.getDeclaredAnnotation(Snippet.class).value(); JSONObject entry = new JSONObject(); - KList fileMatch = new KList<>(); - - for (int depth = 1; depth < 8; depth++) { - fileMatch.add("/snippet/" + snipType + Form.repeat("/*", depth) + ".json"); - } + List fileMatch = new SnippetFolder(snipType).workspaceFileMatches(); entry.put("fileMatch", new JSONArray(fileMatch.toArray())); entry.put("url", "./.iris/schema/snippet/" + snipType + "-schema.json"); diff --git a/core/src/main/java/art/arcane/iris/pack/PackDimensionValidator.java b/core/src/main/java/art/arcane/iris/pack/PackDimensionValidator.java index 27de49967..b1600a38d 100644 --- a/core/src/main/java/art/arcane/iris/pack/PackDimensionValidator.java +++ b/core/src/main/java/art/arcane/iris/pack/PackDimensionValidator.java @@ -19,6 +19,7 @@ package art.arcane.iris.pack; import art.arcane.iris.generation.terrain.IrisDimensionType; +import art.arcane.iris.pack.loading.SnippetFolder; import art.arcane.iris.spi.IrisPlatforms; import art.arcane.iris.structure.object.IrisObjectScale; import art.arcane.iris.world.IrisWorldBoundary; @@ -35,6 +36,8 @@ import java.util.regex.Pattern; final class PackDimensionValidator { private static final String BORROWED_DIMENSION_TYPE = "borrowedDimensionType"; + 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 PackDimensionValidator() { @@ -248,7 +251,7 @@ final class PackDimensionValidator { Object rawStyle = blend.opt("style"); boolean styleObject = rawStyle instanceof JSONObject; boolean styleSnippet = rawStyle instanceof String reference - && reference.startsWith("snippet/style/"); + && new SnippetFolder(STYLE_SNIPPET_TYPE).holds(reference); if (!styleObject && !styleSnippet) { blockingErrors.add(context + ".blend.style must be an object or style snippet reference."); return; @@ -263,13 +266,12 @@ final class PackDimensionValidator { private static void validateDimensionStackStyleSnippet(File packFolder, String context, String reference, List blockingErrors) { try { - File snippetRoot = new File(packFolder, "snippet/style").getCanonicalFile(); - File snippetFile = new File(packFolder, reference + ".json").getCanonicalFile(); - if (!snippetFile.toPath().startsWith(snippetRoot.toPath()) || !snippetFile.isFile()) { + SnippetFolder.Lookup snippet = new SnippetFolder(STYLE_SNIPPET_TYPE).find(packFolder, reference); + if (!snippet.found()) { blockingErrors.add(context + " references missing style snippet '" + reference + "'."); return; } - new JSONObject(Files.readString(snippetFile.toPath(), StandardCharsets.UTF_8)); + new JSONObject(Files.readString(snippet.file().toPath(), StandardCharsets.UTF_8)); } catch (Throwable error) { blockingErrors.add(context + " references invalid style snippet '" + reference + "': " + error.getMessage()); @@ -609,17 +611,12 @@ final class PackDimensionValidator { if (reference == null || !reference.startsWith("snippet/")) { return null; } - // Mirror IrisData's snippet adapter: canonical snippet/range/... is used verbatim; any other - // snippet/... reference is re-rooted under this field's snippet folder. - if (!reference.startsWith("snippet/range/")) { - reference = "snippet/range/" + reference.substring("snippet/".length()); - } - File snippet = new File(packFolder, reference + ".json"); - if (!snippet.isFile()) { + SnippetFolder.Lookup snippet = new SnippetFolder(RANGE_SNIPPET_TYPE).find(packFolder, reference); + if (!snippet.found()) { return null; } try { - return new JSONObject(Files.readString(snippet.toPath(), StandardCharsets.UTF_8)); + return new JSONObject(Files.readString(snippet.file().toPath(), StandardCharsets.UTF_8)); } catch (Throwable e) { return null; } diff --git a/core/src/main/java/art/arcane/iris/pack/PackGeneratorDuplicateValidator.java b/core/src/main/java/art/arcane/iris/pack/PackGeneratorDuplicateValidator.java index 4da8e0af2..70cbb623c 100644 --- a/core/src/main/java/art/arcane/iris/pack/PackGeneratorDuplicateValidator.java +++ b/core/src/main/java/art/arcane/iris/pack/PackGeneratorDuplicateValidator.java @@ -18,6 +18,7 @@ package art.arcane.iris.pack; +import art.arcane.iris.pack.loading.SnippetFolder; import art.arcane.volmlib.util.json.JSONArray; import art.arcane.volmlib.util.json.JSONObject; @@ -45,7 +46,7 @@ import java.util.TreeMap; * for a warning aimed at the copy-the-file-and-forget-the-seed mistake. */ final class PackGeneratorDuplicateValidator { - private static final String GENERATOR_SNIPPET_FOLDER = "snippet/generator-layer/"; + private static final String GENERATOR_SNIPPET_TYPE = "generator-layer"; private PackGeneratorDuplicateValidator() { } @@ -125,15 +126,12 @@ final class PackGeneratorDuplicateValidator { if (reference == null || !reference.startsWith("snippet/")) { return null; } - String resolved = reference.startsWith(GENERATOR_SNIPPET_FOLDER) - ? reference - : GENERATOR_SNIPPET_FOLDER + reference.substring("snippet/".length()); - File snippet = new File(packFolder, resolved + ".json"); - if (!snippet.isFile()) { + SnippetFolder.Lookup snippet = new SnippetFolder(GENERATOR_SNIPPET_TYPE).find(packFolder, reference); + if (!snippet.found()) { return null; } try { - return new JSONObject(Files.readString(snippet.toPath(), StandardCharsets.UTF_8)); + return new JSONObject(Files.readString(snippet.file().toPath(), StandardCharsets.UTF_8)); } catch (Throwable e) { return null; } diff --git a/core/src/main/java/art/arcane/iris/pack/PackHydrologyValidator.java b/core/src/main/java/art/arcane/iris/pack/PackHydrologyValidator.java index 8b4d15d4f..16a052b96 100644 --- a/core/src/main/java/art/arcane/iris/pack/PackHydrologyValidator.java +++ b/core/src/main/java/art/arcane/iris/pack/PackHydrologyValidator.java @@ -17,6 +17,7 @@ import art.arcane.iris.generation.terrain.IrisRegion; import art.arcane.iris.generation.terrain.ShoreBiomeLineages; import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.pack.loading.IrisRegistrant; +import art.arcane.iris.pack.loading.SnippetFolder; import art.arcane.iris.pack.schema.annotation.Snippet; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.IrisPlatforms; @@ -172,13 +173,13 @@ final class PackHydrologyValidator { } private static void warnUnknownSnippetKeys(String field, String reference, Class type, KeyScan scan) { - String base = SNIPPET_ROOT + type.getDeclaredAnnotation(Snippet.class).value() + "/"; - String snippet = reference.startsWith(base) ? reference : base + reference.substring(SNIPPET_ROOT.length()); + SnippetFolder.Lookup lookup = new SnippetFolder(type.getDeclaredAnnotation(Snippet.class).value()) + .find(scan.packFolder(), reference); + String snippet = lookup.key(); if (!scan.activeSnippets().add(snippet)) { return; } - File file = new File(scan.packFolder(), snippet + ".json"); - JSONObject object = file.isFile() ? PackValidationIo.readJson(file) : null; + JSONObject object = lookup.found() ? PackValidationIo.readJson(lookup.file()) : null; if (object != null) { warnUnknownFields(field + " (" + snippet + ")", object, type, scan); } diff --git a/core/src/main/java/art/arcane/iris/pack/PackStaticObjectValidator.java b/core/src/main/java/art/arcane/iris/pack/PackStaticObjectValidator.java index 29069d2ef..936e4690c 100644 --- a/core/src/main/java/art/arcane/iris/pack/PackStaticObjectValidator.java +++ b/core/src/main/java/art/arcane/iris/pack/PackStaticObjectValidator.java @@ -1,5 +1,6 @@ package art.arcane.iris.pack; +import art.arcane.iris.pack.loading.SnippetFolder; import art.arcane.iris.structure.object.IrisObjectPlacementScaleInterpolator; import art.arcane.iris.structure.object.IrisStaticObject; import art.arcane.volmlib.util.json.JSONArray; @@ -165,16 +166,13 @@ final class PackStaticObjectValidator { return object; } if (value instanceof String reference && reference.startsWith("snippet/")) { - String base = "snippet/" + snippetType + "/"; - String key = reference.startsWith(base) ? reference : base + reference.substring("snippet/".length()); - Path root = packFolder.toPath().toAbsolutePath().normalize(); - Path snippet = resolveContained(root, key + ".json"); - if (snippet == null || !snippet.startsWith(root.resolve(base)) || !Files.isRegularFile(snippet)) { + SnippetFolder.Lookup snippet = new SnippetFolder(snippetType).find(packFolder, reference); + if (!snippet.found()) { errors.add(path + " references missing " + snippetType + " snippet '" + reference + "'."); return null; } try { - return new JSONObject(Files.readString(snippet, StandardCharsets.UTF_8)); + return new JSONObject(Files.readString(snippet.file().toPath(), StandardCharsets.UTF_8)); } catch (IOException | RuntimeException e) { errors.add(path + " could not read snippet '" + reference + "': " + e.getMessage()); return null; diff --git a/core/src/main/java/art/arcane/iris/pack/PackStyledRangeDefaultValidator.java b/core/src/main/java/art/arcane/iris/pack/PackStyledRangeDefaultValidator.java index 9b903585c..669d66a52 100644 --- a/core/src/main/java/art/arcane/iris/pack/PackStyledRangeDefaultValidator.java +++ b/core/src/main/java/art/arcane/iris/pack/PackStyledRangeDefaultValidator.java @@ -18,6 +18,7 @@ package art.arcane.iris.pack; +import art.arcane.iris.pack.loading.SnippetFolder; import art.arcane.volmlib.util.json.JSONArray; import art.arcane.volmlib.util.json.JSONObject; @@ -36,7 +37,7 @@ import java.util.Locale; * 16-32 objects per chunk, and a caveProfile.densityThreshold of {} hollows the whole cave range. */ final class PackStyledRangeDefaultValidator { - private static final String STYLE_RANGE_SNIPPET_FOLDER = "snippet/style-range/"; + private static final String STYLE_RANGE_SNIPPET_TYPE = "style-range"; record Validation(List errors, List warnings) { Validation { @@ -116,16 +117,13 @@ final class PackStyledRangeDefaultValidator { if (raw instanceof JSONObject inline) { range = inline; } else if (raw instanceof String reference && reference.startsWith("snippet/")) { - String resolved = reference.startsWith(STYLE_RANGE_SNIPPET_FOLDER) - ? reference - : STYLE_RANGE_SNIPPET_FOLDER + reference.substring("snippet/".length()); - File snippet = new File(packFolder, resolved + ".json"); - if (!snippet.isFile()) { + SnippetFolder.Lookup snippet = new SnippetFolder(STYLE_RANGE_SNIPPET_TYPE).find(packFolder, reference); + if (!snippet.found()) { return; // Missing snippets are reported by the content-key machinery. } try { - range = new JSONObject(Files.readString(snippet.toPath(), StandardCharsets.UTF_8)); - via = " (via snippet '" + resolved + "')"; + range = new JSONObject(Files.readString(snippet.file().toPath(), StandardCharsets.UTF_8)); + via = " (via snippet '" + snippet.key() + "')"; } catch (Throwable e) { return; } diff --git a/core/src/main/java/art/arcane/iris/pack/PackTerrain3DValidator.java b/core/src/main/java/art/arcane/iris/pack/PackTerrain3DValidator.java index add3b7508..ce3ffd1ed 100644 --- a/core/src/main/java/art/arcane/iris/pack/PackTerrain3DValidator.java +++ b/core/src/main/java/art/arcane/iris/pack/PackTerrain3DValidator.java @@ -1,5 +1,6 @@ package art.arcane.iris.pack; +import art.arcane.iris.pack.loading.SnippetFolder; import art.arcane.iris.generation.terrain.IrisTerrain3D; import art.arcane.iris.generation.noise.NoiseStyle; import com.google.gson.Gson; @@ -12,7 +13,6 @@ import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; -import java.nio.file.Path; import java.util.ArrayList; import java.util.Comparator; import java.util.List; @@ -169,15 +169,12 @@ final class PackTerrain3DValidator { return null; } String reference = raw.getAsString(); - String prefix = "snippet/" + snippetType + "/"; - String resolved = reference.startsWith(prefix) ? reference : prefix + reference.substring(8); - Path root = packFolder.toPath().toAbsolutePath().normalize(); - Path path = root.resolve(resolved + ".json").normalize(); - if (!path.startsWith(root.resolve(prefix)) || !Files.isRegularFile(path)) { + SnippetFolder.Lookup snippet = new SnippetFolder(snippetType).find(packFolder, reference); + if (!snippet.found()) { errors.add(location + " references an unavailable " + snippetType + " snippet '" + reference + "'."); return null; } - return readObject(path.toFile(), location + " (" + reference + ")", errors); + return readObject(snippet.file(), location + " (" + reference + ")", errors); } private static JsonObject readObject(File file, String location, List errors) { diff --git a/core/src/main/java/art/arcane/iris/pack/ingest/IngestPack.java b/core/src/main/java/art/arcane/iris/pack/ingest/IngestPack.java index 12d9d5d6c..97be1efcd 100644 --- a/core/src/main/java/art/arcane/iris/pack/ingest/IngestPack.java +++ b/core/src/main/java/art/arcane/iris/pack/ingest/IngestPack.java @@ -18,6 +18,7 @@ package art.arcane.iris.pack.ingest; +import art.arcane.iris.pack.loading.SnippetFolder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; @@ -114,8 +115,7 @@ final class IngestPack { if (!reference.startsWith(SNIPPET_PREFIX)) { return null; } - String base = SNIPPET_PREFIX + snippetType + "/"; - String key = reference.startsWith(base) ? reference : base + reference.substring(SNIPPET_PREFIX.length()); + String key = new SnippetFolder(snippetType).keyOf(reference); return find(key + ".json").map(JsonObject::deepCopy).orElse(null); } diff --git a/core/src/main/java/art/arcane/iris/pack/loading/IrisData.java b/core/src/main/java/art/arcane/iris/pack/loading/IrisData.java index 368929b24..9f4873c25 100644 --- a/core/src/main/java/art/arcane/iris/pack/loading/IrisData.java +++ b/core/src/main/java/art/arcane/iris/pack/loading/IrisData.java @@ -25,6 +25,11 @@ import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonParser; +import com.google.gson.Strictness; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.reflect.TypeToken; @@ -92,6 +97,8 @@ import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.FileReader; import java.io.IOException; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; @@ -104,6 +111,7 @@ import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Collection; import java.util.Collections; import java.util.IdentityHashMap; import java.util.Set; @@ -968,12 +976,15 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory { @Override public TypeAdapter create(Gson gson, TypeToken typeToken) { - if (!typeToken.getRawType().isAnnotationPresent(Snippet.class)) { - return null; + String listedSnippetType = snippetTypeListedBy(typeToken); + if (listedSnippetType != null) { + return snippetListAdapter(gson, typeToken, listedSnippetType); } - String snippetType = typeToken.getRawType().getDeclaredAnnotation(Snippet.class).value(); - String snippedBase = "snippet/" + snippetType + "/"; + String snippetType = snippetTypeOf(typeToken.getRawType()); + if (snippetType == null) { + return null; + } return new TypeAdapter<>() { @Override @@ -984,73 +995,184 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory { @Override public T read(JsonReader reader) throws IOException { TypeAdapter adapter = gson.getDelegateAdapter(IrisData.this, typeToken); + String path = reader.getPath(); - if (reader.peek().equals(JsonToken.STRING)) { - String r = reader.nextString(); - if (!r.startsWith("snippet/")) - return null; - if (!r.startsWith(snippedBase)) - r = snippedBase + r.substring(8); - - File f = new File(getDataFolder(), r + ".json"); - if (f.exists()) { - try (JsonReader snippetReader = new JsonReader(new FileReader(f))){ - return adapter.read(snippetReader); - } catch (IrisEngineStreamType.UnknownStreamException unknownStream) { - throw unknownStream; - } catch (Throwable e) { - IrisLogging.error("Couldn't read snippet " + r + " in " + reader.getPath() + " (" + e.getMessage() + ")"); - } - } else { - IrisLogging.error("Couldn't find snippet " + r + " in " + reader.getPath()); - } - - return null; + if (reader.peek() == JsonToken.STRING) { + return readSnippetReference(adapter, snippetType, reader.nextString(), path); } + JsonElement value = gson.getAdapter(JsonElement.class).read(reader); try { - return adapter.read(reader); + return adapter.fromJsonTree(value); } catch (IrisEngineStreamType.UnknownStreamException unknownStream) { throw unknownStream; } catch (Throwable e) { - IrisLogging.error("Failed to read " + typeToken.getRawType().getCanonicalName() + "... faking objects a little to load the file at least."); + IrisLogging.error("Failed to read " + typeToken.getRawType().getCanonicalName() + " at " + path + + " (" + e.getMessage() + "), using defaults"); IrisLogging.reportError(e); - try { - return (T) typeToken.getRawType().getConstructor().newInstance(); - } catch (Throwable ignored) { - - } + return defaultInstance(typeToken); } - return null; } }; } - public KList getPossibleSnippets(String f) { - return possibleSnippets.computeIfAbsent(f, (k) -> { - KList l = new KList<>(); + private @Nullable T readSnippetReference(TypeAdapter adapter, String snippetType, String reference, String path) { + JsonElement snippet = readSnippetFile(snippetType, reference, path); + if (snippet == null) { + return null; + } - File snippetFolder = new File(getDataFolder(), "snippet/" + f); - if (!snippetFolder.exists()) return l; + if (snippet.isJsonArray()) { + IrisLogging.error("Snippet " + reference + " in " + path + " holds several entries, which only a list can take"); + return null; + } - String absPath = snippetFolder.getAbsolutePath(); - try (var stream = Files.walk(snippetFolder.toPath())) { - stream.filter(Files::isRegularFile) - .map(Path::toAbsolutePath) - .map(Path::toString) - .filter(s -> s.endsWith(".json")) - .map(s -> s.substring(absPath.length() + 1)) - .map(s -> s.replace("\\", "/")) - .map(s -> s.substring(0, s.length() - ".json".length())) - .forEach(s -> l.add("snippet/" + s)); - } catch (Throwable e) { - IrisLogging.reportError("Failed to scan Iris snippets in " + snippetFolder + ".", e); + try { + return adapter.fromJsonTree(snippet); + } catch (IrisEngineStreamType.UnknownStreamException unknownStream) { + throw unknownStream; + } catch (Throwable e) { + IrisLogging.error("Couldn't read snippet " + reference + " in " + path + " (" + e.getMessage() + ")"); + return null; + } + } + + @SuppressWarnings("unchecked") + private static @Nullable T defaultInstance(TypeToken typeToken) { + try { + return (T) typeToken.getRawType().getConstructor().newInstance(); + } catch (Throwable ignored) { + return null; + } + } + + private static @Nullable String snippetTypeOf(Class type) { + Snippet snippet = type.getDeclaredAnnotation(Snippet.class); + return snippet == null ? null : snippet.value(); + } + + private static @Nullable String snippetTypeListedBy(TypeToken typeToken) { + if (!Collection.class.isAssignableFrom(typeToken.getRawType()) + || !(typeToken.getType() instanceof ParameterizedType listType)) { + return null; + } + + Type[] elementTypes = listType.getActualTypeArguments(); + if (elementTypes.length != 1 || !(elementTypes[0] instanceof Class elementType)) { + return null; + } + + return snippetTypeOf(elementType); + } + + /** A snippet file holding a JSON array stands for all of its entries, so inside a list it becomes that many items. */ + private TypeAdapter snippetListAdapter(Gson gson, TypeToken listType, String snippetType) { + TypeAdapter listAdapter = gson.getDelegateAdapter(this, listType); + + return new TypeAdapter<>() { + @Override + public void write(JsonWriter writer, T list) throws IOException { + listAdapter.write(writer, list); } - return l; + @Override + public T read(JsonReader reader) throws IOException { + if (reader.peek() != JsonToken.BEGIN_ARRAY) { + return listAdapter.read(reader); + } + + String path = reader.getPath(); + JsonArray entries = gson.getAdapter(JsonArray.class).read(reader); + return listAdapter.fromJsonTree(withSnippetsInlined(entries, snippetType, path)); + } + }; + } + + /** A snippet that can't be read keeps its slot as null, the way a single snippet reference loads. */ + private JsonArray withSnippetsInlined(JsonArray entries, String snippetType, String path) { + JsonArray inlined = new JsonArray(); + for (int index = 0; index < entries.size(); index++) { + JsonElement entry = entries.get(index); + if (!isSnippetReference(entry)) { + inlined.add(entry); + continue; + } + + JsonElement snippet = readSnippetFile(snippetType, entry.getAsString(), path + "[" + index + "]"); + if (snippet == null) { + inlined.add(JsonNull.INSTANCE); + } else if (snippet.isJsonArray()) { + entriesOfSnippet(snippet.getAsJsonArray()).forEach(inlined::add); + } else { + inlined.add(snippet); + } + } + + return inlined; + } + + /** The entries a snippet file holding a list stands for. Lenient parsing reads a trailing comma as a null entry. */ + public static List entriesOfSnippet(JsonArray snippet) { + return snippet.asList().stream().filter(entry -> !entry.isJsonNull()).toList(); + } + + private static boolean isSnippetReference(JsonElement entry) { + return entry.isJsonPrimitive() + && entry.getAsJsonPrimitive().isString() + && entry.getAsString().startsWith(SnippetFolder.PREFIX); + } + + /** The parsed snippet file, or null when the reference isn't a snippet or the file can't be read. */ + private @Nullable JsonElement readSnippetFile(String snippetType, String reference, String path) { + if (!reference.startsWith(SnippetFolder.PREFIX)) { + return null; + } + + SnippetFolder.Lookup lookup = new SnippetFolder(snippetType).find(getDataFolder(), reference); + if (!lookup.found()) { + IrisLogging.error("Couldn't find snippet " + lookup.key() + " in " + path); + return null; + } + + try (JsonReader snippetReader = new JsonReader(new FileReader(lookup.file()))) { + snippetReader.setStrictness(Strictness.LENIENT); + return JsonParser.parseReader(snippetReader); + } catch (Throwable e) { + IrisLogging.error("Couldn't read snippet " + lookup.key() + " in " + path + " (" + e.getMessage() + ")"); + return null; + } + } + + /** Every snippet of the type, as "snippet/<path inside its folder>". */ + public KList getPossibleSnippets(String snippetType) { + return possibleSnippets.computeIfAbsent(snippetType, (k) -> { + File snippetFolder = new File(getDataFolder(), new SnippetFolder(snippetType).path()); + return new KList<>(listSnippetReferences(snippetFolder)); }); } + private static List listSnippetReferences(File snippetFolder) { + if (!snippetFolder.exists()) { + return List.of(); + } + + String absPath = snippetFolder.getAbsolutePath(); + try (var stream = Files.walk(snippetFolder.toPath())) { + return stream.filter(Files::isRegularFile) + .map(Path::toAbsolutePath) + .map(Path::toString) + .filter(s -> s.endsWith(".json")) + .map(s -> s.substring(absPath.length() + 1)) + .map(s -> s.replace("\\", "/")) + .map(s -> s.substring(0, s.length() - ".json".length())) + .map(s -> SnippetFolder.PREFIX + s) + .toList(); + } catch (Throwable e) { + IrisLogging.reportError("Failed to scan Iris snippets in " + snippetFolder + ".", e); + return List.of(); + } + } + public boolean isClosed() { return closed; } diff --git a/core/src/main/java/art/arcane/iris/pack/loading/SnippetFolder.java b/core/src/main/java/art/arcane/iris/pack/loading/SnippetFolder.java new file mode 100644 index 000000000..75e514368 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/pack/loading/SnippetFolder.java @@ -0,0 +1,69 @@ +package art.arcane.iris.pack.loading; + +import org.jetbrains.annotations.Nullable; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.InvalidPathException; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + +/** + * The pack folder "snippet/<type>" one snippet type keeps its files in. This is the one place a + * "snippet/..." reference turns into a file. + */ +public record SnippetFolder(String snippetType) { + public static final String PREFIX = "snippet/"; + private static final String FILE_SUFFIX = ".json"; + private static final int WORKSPACE_MATCH_DEPTH = 8; + + public String path() { + return PREFIX + snippetType; + } + + public boolean holds(String reference) { + return reference.startsWith(path() + "/"); + } + + /** The file key, without ".json", a reference means: "snippet/name" is short for "snippet/<type>/name". */ + public String keyOf(String reference) { + return holds(reference) ? reference : path() + "/" + reference.substring(PREFIX.length()); + } + + public Lookup find(File packFolder, String reference) { + String key = keyOf(reference); + return new Lookup(existingFileInsideFolder(packFolder, key), key); + } + + /** The IDE file patterns the snippet schema applies to. */ + public List workspaceFileMatches() { + List matches = new ArrayList<>(); + for (int depth = 1; depth < WORKSPACE_MATCH_DEPTH; depth++) { + matches.add("/" + path() + "/*".repeat(depth) + FILE_SUFFIX); + } + return matches; + } + + private @Nullable File existingFileInsideFolder(File packFolder, String key) { + try { + Path root = packFolder.toPath().toAbsolutePath().normalize(); + Path folder = root.resolve(path()).normalize(); + Path file = root.resolve(key + FILE_SUFFIX).normalize(); + if (!file.startsWith(folder) || !Files.isRegularFile(file)) { + return null; + } + return file.toRealPath().startsWith(folder.toRealPath()) ? file.toFile() : null; + } catch (InvalidPathException | IOException ignored) { + return null; + } + } + + /** The snippet file a reference names, absent when the pack has no such file. */ + public record Lookup(@Nullable File file, String key) { + public boolean found() { + return file != null; + } + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/workspace/IrisCodeWorkspace.java b/core/src/main/java/art/arcane/iris/studio/workspace/IrisCodeWorkspace.java index ecd55e370..af4b0f754 100644 --- a/core/src/main/java/art/arcane/iris/studio/workspace/IrisCodeWorkspace.java +++ b/core/src/main/java/art/arcane/iris/studio/workspace/IrisCodeWorkspace.java @@ -23,13 +23,12 @@ import art.arcane.iris.pack.schema.SchemaBuilder; import art.arcane.iris.configuration.IrisSettings; import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.pack.loading.ResourceLoader; +import art.arcane.iris.pack.loading.SnippetFolder; import art.arcane.iris.pack.schema.annotation.Snippet; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.platform.bukkit.plugin.VolmitSender; import art.arcane.iris.world.task.J; -import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KMap; -import art.arcane.volmlib.util.format.Form; import art.arcane.volmlib.util.io.IO; import art.arcane.volmlib.util.json.JSONArray; import art.arcane.volmlib.util.json.JSONObject; @@ -183,11 +182,7 @@ public class IrisCodeWorkspace { try { String snipType = snippetClass.getDeclaredAnnotation(Snippet.class).value(); JSONObject schemaEntry = new JSONObject(); - KList fileMatches = new KList<>(); - - for (int depth = 1; depth < 8; depth++) { - fileMatches.add("/snippet/" + snipType + Form.repeat("/*", depth) + ".json"); - } + List fileMatches = new SnippetFolder(snipType).workspaceFileMatches(); schemaEntry.put("fileMatch", new JSONArray(fileMatches.toArray())); schemaEntry.put("url", "./.iris/schema/snippet/" + snipType + "-schema.json"); diff --git a/core/src/test/java/art/arcane/iris/pack/loading/IrisDataSnippetMalformedValueTest.java b/core/src/test/java/art/arcane/iris/pack/loading/IrisDataSnippetMalformedValueTest.java new file mode 100644 index 000000000..dafa4accb --- /dev/null +++ b/core/src/test/java/art/arcane/iris/pack/loading/IrisDataSnippetMalformedValueTest.java @@ -0,0 +1,111 @@ +package art.arcane.iris.pack.loading; + +import art.arcane.iris.configuration.IrisSettings; +import art.arcane.iris.generation.runtime.PreservationRegistry; +import art.arcane.iris.pack.value.IrisRange; +import art.arcane.iris.spi.IrisServices; +import art.arcane.iris.testsupport.PlatformLeakGuard; +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 java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.mock; + +public class IrisDataSnippetMalformedValueTest { + private static final long RUNAWAY_READ_TIMEOUT_MILLISECONDS = 20_000; + private static final double DEFAULT_RANGE_MIN = 16; + private static final double DEFAULT_RANGE_MAX = 32; + + @ClassRule + public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean(); + + @Rule + public final TemporaryFolder temporary = new TemporaryFolder(); + + private IrisSettings previousSettings; + private Path pack; + private IrisData data; + + public static class RangeListHolder { + public List ranges; + public KList keyedRanges; + } + + public static class RangeHolder { + public IrisRange range; + } + + @Before + public void createData() throws IOException { + previousSettings = IrisSettings.settings; + IrisSettings.settings = new IrisSettings(); + IrisServices.register(PreservationRegistry.class, mock(PreservationRegistry.class)); + pack = temporary.newFolder("pack").toPath(); + data = IrisData.get(new File(pack.toFile(), ".")); + } + + @After + public void closeData() { + data.close(); + IrisServices.remove(PreservationRegistry.class); + IrisSettings.settings = previousSettings; + } + + @Test(timeout = RUNAWAY_READ_TIMEOUT_MILLISECONDS) + public void numberInAListOfSnippetTypesIsReplacedByTheDefaultAndReadingMovesOn() { + RangeListHolder holder = data.getGson().fromJson( + "{\"ranges\":[5,{\"min\":1,\"max\":2}],\"keyedRanges\":[true]}", RangeListHolder.class); + + assertEquals(2, holder.ranges.size()); + assertDefaultRange(holder.ranges.get(0)); + assertEquals(1, holder.ranges.get(1).getMin(), 0); + assertEquals(1, holder.keyedRanges.size()); + assertDefaultRange(holder.keyedRanges.get(0)); + } + + @Test(timeout = RUNAWAY_READ_TIMEOUT_MILLISECONDS) + public void nestedArrayInAListOfSnippetTypesIsReplacedByTheDefault() { + RangeListHolder holder = data.getGson().fromJson("{\"ranges\":[[1,2],[[3]]]}", RangeListHolder.class); + + assertEquals(2, holder.ranges.size()); + assertDefaultRange(holder.ranges.get(0)); + assertDefaultRange(holder.ranges.get(1)); + } + + @Test(timeout = RUNAWAY_READ_TIMEOUT_MILLISECONDS) + public void malformedFieldKeepsTheDefaultAndTheValuesAfterIt() { + RangeHolder holder = data.getGson().fromJson("{\"range\":7}", RangeHolder.class); + + assertDefaultRange(holder.range); + } + + @Test(timeout = RUNAWAY_READ_TIMEOUT_MILLISECONDS) + public void wrongTypedEntryOfAListSnippetIsReplacedByTheDefault() throws IOException { + Path snippet = pack.resolve("snippet/range/broken.json"); + Files.createDirectories(snippet.getParent()); + Files.writeString(snippet, "[[1]]"); + + RangeListHolder holder = data.getGson().fromJson("{\"ranges\":[\"snippet/broken\"]}", RangeListHolder.class); + + assertEquals(1, holder.ranges.size()); + assertDefaultRange(holder.ranges.get(0)); + } + + private static void assertDefaultRange(IrisRange range) { + assertNotNull(range); + assertEquals(DEFAULT_RANGE_MIN, range.getMin(), 0); + assertEquals(DEFAULT_RANGE_MAX, range.getMax(), 0); + } +} diff --git a/core/src/test/java/art/arcane/iris/pack/loading/IrisDataSnippetPackWalkTest.java b/core/src/test/java/art/arcane/iris/pack/loading/IrisDataSnippetPackWalkTest.java new file mode 100644 index 000000000..a2574ee4c --- /dev/null +++ b/core/src/test/java/art/arcane/iris/pack/loading/IrisDataSnippetPackWalkTest.java @@ -0,0 +1,261 @@ +package art.arcane.iris.pack.loading; + +import art.arcane.iris.generation.biome.IrisBiome; +import art.arcane.iris.generation.noise.IrisExpression; +import art.arcane.iris.generation.noise.IrisGenerator; +import art.arcane.iris.generation.terrain.IrisDimension; +import art.arcane.iris.generation.terrain.IrisRegion; +import art.arcane.iris.pack.mod.IrisMod; +import art.arcane.iris.pack.schema.annotation.Snippet; +import art.arcane.iris.structure.jigsaw.IrisJigsawPiece; +import art.arcane.iris.structure.jigsaw.IrisJigsawPool; +import art.arcane.iris.structure.placement.IrisStructure; +import art.arcane.iris.world.entity.IrisEntity; +import art.arcane.iris.world.entity.IrisMarker; +import art.arcane.iris.world.entity.IrisSpawner; +import art.arcane.iris.world.loot.IrisLootTable; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.junit.Test; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Stream; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assume.assumeTrue; + +/** + * Walks every snippet reference of a real pack, set through IRIS_TEST_PACK, and checks it resolves for the type of the + * field it sits in. Reads the pack only; skipped when the variable is unset. + */ +public class IrisDataSnippetPackWalkTest { + private static final String PACK_ENVIRONMENT_VARIABLE = "IRIS_TEST_PACK"; + private static final String ENGINE_PACKAGE_PREFIX = "art.arcane.iris"; + private static final List> PACK_ROOT_TYPES = List.of( + IrisBiome.class, IrisRegion.class, IrisDimension.class, IrisGenerator.class, IrisEntity.class, + IrisLootTable.class, IrisSpawner.class, IrisMarker.class, IrisExpression.class, IrisMod.class, + IrisStructure.class, IrisJigsawPool.class, IrisJigsawPiece.class); + + private File pack; + private final Map> snippetTypesByFolder = new HashMap<>(); + private final List unresolved = new ArrayList<>(); + private int resolved; + private int outsideSnippetFields; + private int snippetFilesWalked; + private final List untypedSnippetFiles = new ArrayList<>(); + + @Test + public void everySnippetReferenceInThePackResolves() throws Exception { + String packPath = System.getenv(PACK_ENVIRONMENT_VARIABLE); + assumeTrue(PACK_ENVIRONMENT_VARIABLE + " is not set", packPath != null && !packPath.isBlank()); + pack = new File(packPath); + assumeTrue(pack + " is not a folder", pack.isDirectory()); + + Set> visitedTypes = new HashSet<>(); + PACK_ROOT_TYPES.forEach(root -> collectSnippetTypes(root, visitedTypes)); + for (Class root : PACK_ROOT_TYPES) { + walkRootFolder(root); + } + walkSnippetFiles(); + + System.out.println("snippet pack walk: resolved=" + resolved + " unresolved=" + unresolved.size() + + " outsideSnippetFields=" + outsideSnippetFields + " snippetFilesWalked=" + snippetFilesWalked + + " untypedSnippetFiles=" + untypedSnippetFiles.size()); + untypedSnippetFiles.forEach(file -> System.out.println("untyped snippet file: " + file)); + assertTrue("unresolved snippet references:\n" + String.join("\n", unresolved), unresolved.isEmpty()); + assertTrue("the pack holds no snippet references", resolved > 0); + } + + private void walkRootFolder(Class root) throws Exception { + String folderName = root.getConstructor().newInstance().getFolderName(); + for (File file : jsonFilesUnder(new File(pack, folderName))) { + walk(parse(file), root, relative(file)); + } + } + + private void walkSnippetFiles() throws IOException { + for (File file : jsonFilesUnder(new File(pack, "snippet"))) { + Class type = typeOfSnippetFile(file); + if (type == null) { + untypedSnippetFiles.add(relative(file)); + continue; + } + snippetFilesWalked++; + JsonElement content = parse(file); + if (content != null && content.isJsonArray()) { + content.getAsJsonArray().forEach(entry -> walk(entry, type, relative(file))); + } else { + walk(content, type, relative(file)); + } + } + } + + private Class typeOfSnippetFile(File file) { + String[] segments = relative(file).split("/"); + return snippetTypesByFolder.get(segments[1]); + } + + private void walk(JsonElement value, Type type, String path) { + if (value == null || value.isJsonNull()) { + return; + } + Class raw = rawClass(type); + if (value.isJsonPrimitive()) { + checkReference(value, raw, path); + return; + } + if (value.isJsonArray()) { + walkElements(value.getAsJsonArray(), elementTypeOf(type), path); + return; + } + walkObject(value.getAsJsonObject(), type, raw, path); + } + + private void walkElements(JsonArray elements, Type elementType, String path) { + for (int index = 0; index < elements.size(); index++) { + walk(elements.get(index), elementType, path + "[" + index + "]"); + } + } + + private void walkObject(JsonObject object, Type type, Class raw, String path) { + if (raw == null) { + return; + } + if (Map.class.isAssignableFrom(raw)) { + Type valueType = typeArgument(type, 1); + object.entrySet().forEach(entry -> walk(entry.getValue(), valueType, path + "." + entry.getKey())); + return; + } + Map fields = fieldTypesOf(raw); + object.entrySet().forEach(entry -> { + Type fieldType = fields.get(entry.getKey()); + if (fieldType != null) { + walk(entry.getValue(), fieldType, path + "." + entry.getKey()); + } + }); + } + + private void checkReference(JsonElement value, Class raw, String path) { + if (!value.getAsJsonPrimitive().isString() || !value.getAsString().startsWith(SnippetFolder.PREFIX)) { + return; + } + String reference = value.getAsString(); + SnippetFolder folder = raw == null ? null : folderOf(raw); + if (folder == null) { + outsideSnippetFields++; + return; + } + if (folder.find(pack, reference).found()) { + resolved++; + return; + } + unresolved.add(path + " -> " + reference + " (tried " + folder.keyOf(reference) + ")"); + } + + private SnippetFolder folderOf(Class type) { + Snippet snippet = type.getDeclaredAnnotation(Snippet.class); + return snippet == null ? null : new SnippetFolder(snippet.value()); + } + + private void collectSnippetTypes(Type type, Set> visited) { + if (type instanceof ParameterizedType parameterized) { + for (Type argument : parameterized.getActualTypeArguments()) { + collectSnippetTypes(argument, visited); + } + } + Class raw = rawClass(type); + if (raw == null) { + return; + } + if (raw.isArray()) { + collectSnippetTypes(raw.getComponentType(), visited); + return; + } + if (!raw.getName().startsWith(ENGINE_PACKAGE_PREFIX) || raw.isEnum() || raw.isInterface() || !visited.add(raw)) { + return; + } + Snippet snippet = raw.getDeclaredAnnotation(Snippet.class); + if (snippet != null) { + snippetTypesByFolder.putIfAbsent(snippet.value(), raw); + } + fieldTypesOf(raw).values().forEach(fieldType -> collectSnippetTypes(fieldType, visited)); + } + + private static Map fieldTypesOf(Class type) { + Map fields = new HashMap<>(); + for (Class current = type; current != null && current != Object.class; current = current.getSuperclass()) { + for (Field field : current.getDeclaredFields()) { + if (!Modifier.isStatic(field.getModifiers()) && !Modifier.isTransient(field.getModifiers())) { + fields.putIfAbsent(field.getName(), field.getGenericType()); + } + } + } + return fields; + } + + private static Class rawClass(Type type) { + if (type instanceof Class raw) { + return raw; + } + if (type instanceof ParameterizedType parameterized && parameterized.getRawType() instanceof Class raw) { + return raw; + } + return null; + } + + private static Type elementTypeOf(Type type) { + if (type instanceof Class raw && raw.isArray()) { + return raw.getComponentType(); + } + return typeArgument(type, 0); + } + + private static Type typeArgument(Type type, int index) { + if (type instanceof ParameterizedType parameterized && index < parameterized.getActualTypeArguments().length) { + return parameterized.getActualTypeArguments()[index]; + } + return Object.class; + } + + private static JsonElement parse(File file) { + try { + return JsonParser.parseString(Files.readString(file.toPath())); + } catch (Exception unreadable) { + return null; + } + } + + private static List jsonFilesUnder(File folder) { + if (!folder.isDirectory()) { + return List.of(); + } + try (Stream files = Files.walk(folder.toPath())) { + return files.filter(Files::isRegularFile) + .filter(file -> file.getFileName().toString().endsWith(".json")) + .map(Path::toFile) + .sorted() + .toList(); + } catch (IOException unreadable) { + throw new IllegalStateException(unreadable); + } + } + + private String relative(File file) { + return pack.toPath().relativize(file.toPath()).toString().replace('\\', '/'); + } +} diff --git a/core/src/test/java/art/arcane/iris/pack/loading/IrisDataSnippetTest.java b/core/src/test/java/art/arcane/iris/pack/loading/IrisDataSnippetTest.java new file mode 100644 index 000000000..9d0bcc4e6 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/pack/loading/IrisDataSnippetTest.java @@ -0,0 +1,202 @@ +package art.arcane.iris.pack.loading; + +import art.arcane.iris.configuration.IrisSettings; +import art.arcane.iris.generation.runtime.PreservationRegistry; +import art.arcane.iris.pack.value.IrisRate; +import art.arcane.iris.spi.IrisServices; +import art.arcane.iris.testsupport.PlatformLeakGuard; +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 java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.mock; + +public class IrisDataSnippetTest { + @ClassRule + public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean(); + + @Rule + public final TemporaryFolder temporary = new TemporaryFolder(); + + private IrisSettings previousSettings; + private Path pack; + private IrisData data; + + public static class RateHolder { + public IrisRate rate; + } + + public static class RateListHolder { + public List rates; + public KList keyedRates; + } + + @Before + public void createPack() throws IOException { + previousSettings = IrisSettings.settings; + IrisSettings.settings = new IrisSettings(); + IrisServices.register(PreservationRegistry.class, mock(PreservationRegistry.class)); + pack = temporary.newFolder("pack").toPath(); + } + + @After + public void closeData() { + if (data != null) { + data.close(); + } + IrisServices.remove(PreservationRegistry.class); + IrisSettings.settings = previousSettings; + } + + @Test + public void nestedPathResolves() throws IOException { + write("snippet/rate/groups/fast.json", "{\"amount\":8}"); + + assertEquals(8, rateOf("\"snippet/groups/fast\"").getAmount()); + assertEquals(8, rateOf("\"snippet/rate/groups/fast\"").getAmount()); + } + + @Test + public void shortAndFullReferencesResolve() throws IOException { + write("snippet/rate/slow.json", "{\"amount\":3}"); + + assertEquals(3, rateOf("\"snippet/slow\"").getAmount()); + assertEquals(3, rateOf("\"snippet/rate/slow\"").getAmount()); + } + + @Test + public void snippetsOfAnotherTypeAreNotUsed() throws IOException { + write("snippet/duration/fast.json", "{\"amount\":7}"); + + assertNull(rateOf("\"snippet/fast\"")); + } + + @Test + public void referenceCannotLeaveItsSnippetFolder() throws IOException { + write("snippet/duration/fast.json", "{\"amount\":7}"); + write("snippet/rate/other.json", "{\"amount\":1}"); + + assertNull(rateOf("\"snippet/rate/../duration/fast\"")); + } + + @Test + public void symlinkLeadingOutOfItsSnippetFolderIsNotFound() throws IOException { + write("snippet/duration/fast.json", "{\"amount\":7}"); + link("snippet/rate/fast.json", "snippet/duration/fast.json"); + + assertNull(rateOf("\"snippet/fast\"")); + } + + @Test + public void symlinkStayingInsideItsSnippetFolderResolves() throws IOException { + write("snippet/rate/real.json", "{\"amount\":4}"); + link("snippet/rate/alias.json", "snippet/rate/real.json"); + + assertEquals(4, rateOf("\"snippet/alias\"").getAmount()); + } + + @Test + public void missingSnippetYieldsNull() throws IOException { + write("snippet/rate/other.json", "{\"amount\":1}"); + + assertNull(rateOf("\"snippet/absent\"")); + } + + @Test + public void arraySnippetInAListStandsForAllItsEntries() throws IOException { + write("snippet/rate/many.json", "[{\"amount\":1},{\"amount\":2},]"); + write("snippet/rate/one.json", "{\"amount\":5}"); + + RateListHolder holder = data().getGson().fromJson( + "{\"rates\":[\"snippet/many\",\"snippet/one\",{\"amount\":9}]," + + "\"keyedRates\":[\"snippet/many\",{\"amount\":9}]}", + RateListHolder.class); + + assertEquals(List.of(1, 2, 5, 9), amountsOf(holder.rates)); + assertEquals(List.of(1, 2, 9), amountsOf(holder.keyedRates)); + } + + @Test + public void unreadableSnippetKeepsItsSlotInAList() throws IOException { + write("snippet/rate/one.json", "{\"amount\":5}"); + + RateListHolder holder = data().getGson().fromJson( + "{\"rates\":[\"snippet/missing\",\"snippet/one\"]}", RateListHolder.class); + + assertEquals(2, holder.rates.size()); + assertNull(holder.rates.get(0)); + assertEquals(5, holder.rates.get(1).getAmount()); + } + + @Test + public void singleReferenceToAnArraySnippetYieldsNull() throws IOException { + write("snippet/rate/many.json", "[{\"amount\":1},{\"amount\":2}]"); + + assertNull(rateOf("\"snippet/many\"")); + } + + @Test + public void listsWithoutReferencesStillLoad() { + RateListHolder holder = data().getGson().fromJson( + "{\"rates\":[{\"amount\":4},{\"amount\":6}]}", RateListHolder.class); + + assertEquals(List.of(4, 6), amountsOf(holder.rates)); + } + + @Test + public void possibleSnippetsListTheTypeFolderAsShortReferences() throws IOException { + write("snippet/rate/a.json", "{}"); + write("snippet/rate/nested/c.json", "{}"); + write("snippet/duration/other.json", "{}"); + + assertEquals(List.of("snippet/a", "snippet/nested/c"), + data().getPossibleSnippets("rate").stream().sorted().toList()); + } + + private IrisRate rateOf(String jsonValue) { + return data().getGson().fromJson("{\"rate\":" + jsonValue + "}", RateHolder.class).rate; + } + + private IrisData data() { + if (data == null) { + data = IrisData.get(new File(pack.toFile(), ".")); + } + return data; + } + + private void write(String relative, String content) throws IOException { + Path file = pack.resolve(relative); + Files.createDirectories(file.getParent()); + Files.writeString(file, content); + } + + private void link(String relative, String target) throws IOException { + Path link = pack.resolve(relative); + Files.createDirectories(link.getParent()); + Files.createSymbolicLink(link, pack.resolve(target)); + } + + private static List amountsOf(List rates) { + assertNotNull(rates); + List amounts = new ArrayList<>(); + for (IrisRate rate : rates) { + assertNotNull(rate); + amounts.add(rate.getAmount()); + } + return amounts; + } +} From 25c612b3c353be3cdc5694abcf81c9c2d8ffd629 Mon Sep 17 00:00:00 2001 From: Piexel <107539181+piexelated@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:58:38 +0100 Subject: [PATCH 04/12] 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 --- .../generation/terrain/IrisDimension.java | 2 + .../arcane/iris/pack/PackContentReach.java | 100 ++++++++++++++++ .../art/arcane/iris/pack/PackValidator.java | 86 ++++++++++++-- ...ackValidatorMissingContentFailureTest.java | 108 ++++++++++++++++++ .../schema/SchemaBuilderIdentityTest.java | 2 +- ...ssingContentFailurePackValidationTest.java | 93 +++++++++++++++ 6 files changed, 382 insertions(+), 9 deletions(-) create mode 100644 core/src/main/java/art/arcane/iris/pack/PackContentReach.java create mode 100644 core/src/test/java/art/arcane/iris/pack/PackValidatorMissingContentFailureTest.java create mode 100644 core/src/test/java/art/arcane/iris/pack/validation/MissingContentFailurePackValidationTest.java diff --git a/core/src/main/java/art/arcane/iris/generation/terrain/IrisDimension.java b/core/src/main/java/art/arcane/iris/generation/terrain/IrisDimension.java index 8575d4bdc..5048b3040 100644 --- a/core/src/main/java/art/arcane/iris/generation/terrain/IrisDimension.java +++ b/core/src/main/java/art/arcane/iris/generation/terrain/IrisDimension.java @@ -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 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 blockDrops = new KList<>(); diff --git a/core/src/main/java/art/arcane/iris/pack/PackContentReach.java b/core/src/main/java/art/arcane/iris/pack/PackContentReach.java new file mode 100644 index 000000000..0d0f8c22c --- /dev/null +++ b/core/src/main/java/art/arcane/iris/pack/PackContentReach.java @@ -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 . + */ + +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 referencedFrom(File packFolder, File dimensionFile, String dimensionKey, Collection folders) { + Set reached = new HashSet<>(); + Set visited = new HashSet<>(); + ArrayDeque 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 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 pending, File candidate) { + if (candidate.isFile()) { + pending.add(candidate); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/pack/PackValidator.java b/core/src/main/java/art/arcane/iris/pack/PackValidator.java index 881a350cc..9970a9c7f 100644 --- a/core/src/main/java/art/arcane/iris/pack/PackValidator.java +++ b/core/src/main/java/art/arcane/iris/pack/PackValidator.java @@ -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 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 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,11 @@ public final class PackValidator { if (!data.getContentGate().ready()) { return List.of(); } - boolean dimensionExcluded = loadEverything(packFolder, data, dimensionFiles); + GatedDimensions dimensions = loadEverything(packFolder, data, dimensionFiles); List 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); return findings; } catch (Throwable e) { IrisLogging.reportError("Version-content gating failed for pack '" + packFolder.getName() + "'", e); @@ -225,10 +233,13 @@ 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> reachedByRequiringDimension = new LinkedHashMap<>(); + List 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( @@ -239,6 +250,10 @@ public final class PackValidator { if (dimension.isCompatExcluded()) { dimensionExcluded = true; } + 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 +271,10 @@ public final class PackValidator { for (IrisObjectPlacement placement : placements) { placement.evaluateCompat(data); } - return dimensionExcluded; + return new GatedDimensions(dimensionExcluded, reachedByRequiringDimension); + } + + private record GatedDimensions(boolean anyExcluded, Map> reachedByRequiringDimension) { } private static void collectPlacements(IrisRegistrant registrant, Set out) { @@ -315,9 +333,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 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 reasons = new LinkedHashSet<>(); if (findings != null) { for (CompatFinding finding : findings) { @@ -332,6 +348,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> reachedByRequiringDimension, + String minecraftVersion, + List findings, + List blockingErrors + ) { + if (reachedByRequiringDimension == null || reachedByRequiringDimension.isEmpty()) { + return; + } + List removed = removedContent(findings); + for (Map.Entry> dimension : reachedByRequiringDimension.entrySet()) { + List 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 removedContent(List 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 removed + ) { + List 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 compatBootLines(PackValidationResult result, String minecraftVersion, int perKeyCap) { if (result == null || result.getCompatFindings().isEmpty()) { diff --git a/core/src/test/java/art/arcane/iris/pack/PackValidatorMissingContentFailureTest.java b/core/src/test/java/art/arcane/iris/pack/PackValidatorMissingContentFailureTest.java new file mode 100644 index 000000000..03a477f9c --- /dev/null +++ b/core/src/test/java/art/arcane/iris/pack/PackValidatorMissingContentFailureTest.java @@ -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> 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 blockingErrors(Map> requiringDimensions, List findings) { + List blockingErrors = new ArrayList<>(); + PackValidator.applyRequireAllContent(PACK, requiringDimensions, "26.1.2", findings, blockingErrors); + return blockingErrors; + } + + @Test + public void requirementIsOffByDefaultAndMissingContentStaysNonBlocking() { + assertFalse(new IrisDimension().isRequireAllContent()); + + List 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 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 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 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 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 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")); + } +} diff --git a/core/src/test/java/art/arcane/iris/pack/schema/SchemaBuilderIdentityTest.java b/core/src/test/java/art/arcane/iris/pack/schema/SchemaBuilderIdentityTest.java index 2ac84d437..5d3ae2867 100644 --- a/core/src/test/java/art/arcane/iris/pack/schema/SchemaBuilderIdentityTest.java +++ b/core/src/test/java/art/arcane/iris/pack/schema/SchemaBuilderIdentityTest.java @@ -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 = "907c3f1d5a33281be801a23d86c4b8e1b5d933ddfc3445b179ece7898aa65d46"; private static final List> SCHEMA_ROOTS = List.of( IrisDimension.class, diff --git a/core/src/test/java/art/arcane/iris/pack/validation/MissingContentFailurePackValidationTest.java b/core/src/test/java/art/arcane/iris/pack/validation/MissingContentFailurePackValidationTest.java new file mode 100644 index 000000000..07581eb0f --- /dev/null +++ b/core/src/test/java/art/arcane/iris/pack/validation/MissingContentFailurePackValidationTest.java @@ -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); + } +} From 4c900953614fca99bcbeecde7e5b5c61d685d15d Mon Sep 17 00:00:00 2001 From: Piexel <107539181+piexelated@users.noreply.github.com> Date: Fri, 27 Nov 2026 18:58:04 +0100 Subject: [PATCH 05/12] 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 --- .../iris/pack/PackDimensionValidator.java | 21 ++++++ ...ackValidatorImportedFeatureHeightTest.java | 68 +++++++++++++++++++ 2 files changed, 89 insertions(+) create mode 100644 core/src/test/java/art/arcane/iris/pack/PackValidatorImportedFeatureHeightTest.java diff --git a/core/src/main/java/art/arcane/iris/pack/PackDimensionValidator.java b/core/src/main/java/art/arcane/iris/pack/PackDimensionValidator.java index b1600a38d..59f50ffc0 100644 --- a/core/src/main/java/art/arcane/iris/pack/PackDimensionValidator.java +++ b/core/src/main/java/art/arcane/iris/pack/PackDimensionValidator.java @@ -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); @@ -278,6 +281,24 @@ final class PackDimensionValidator { } } + static void validateImportedFeatureHeight(File packFolder, String dimensionKey, JSONObject dimension, + List 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 blockingErrors) { if (!dimension.has("staticObjects")) { diff --git a/core/src/test/java/art/arcane/iris/pack/PackValidatorImportedFeatureHeightTest.java b/core/src/test/java/art/arcane/iris/pack/PackValidatorImportedFeatureHeightTest.java new file mode 100644 index 000000000..f8490d1f8 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/pack/PackValidatorImportedFeatureHeightTest.java @@ -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 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 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 validate(JSONObject dimension) { + List 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); + } +} From d7c5526eabb0ca0b102177a1493feb171a2f5185 Mon Sep 17 00:00:00 2001 From: Piexel <107539181+piexelated@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:44:03 +0100 Subject: [PATCH 06/12] 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 --- .../iris/generation/biome/IrisBiome.java | 3 +- .../biome/IrisBiomeLayerGenerator.java | 8 +- .../biome/IrisBiomePaletteLayer.java | 10 +- .../generation/decoration/IrisDecorator.java | 15 +- .../generation/noise/GeneratorProgram.java | 8 +- .../iris/generation/noise/IrisGenerator.java | 22 +- .../generation/noise/IrisGeneratorStyle.java | 38 ++- .../stage/IrisFloatingChildBiomeModifier.java | 2 +- .../terrain/IrisDimensionCarvingEntry.java | 8 +- .../terrain/IrisMaterialPalette.java | 7 +- .../compile/noise/NoiseStyleCompiler.java | 22 +- .../compile/terrain/GeneratorCompiler.java | 6 + .../biome/IrisBiomeLayerSlopeSourceTest.java | 2 + .../biome/IrisSurfaceLayerFallbackTest.java | 1 + .../noise/IrisGeneratorExponentTest.java | 133 ++++++++ .../noise/IrisGeneratorStyleSeedTest.java | 288 ++++++++++++++++++ .../schema/SchemaBuilderIdentityTest.java | 2 +- 17 files changed, 550 insertions(+), 25 deletions(-) create mode 100644 core/src/test/java/art/arcane/iris/generation/noise/IrisGeneratorExponentTest.java create mode 100644 core/src/test/java/art/arcane/iris/generation/noise/IrisGeneratorStyleSeedTest.java diff --git a/core/src/main/java/art/arcane/iris/generation/biome/IrisBiome.java b/core/src/main/java/art/arcane/iris/generation/biome/IrisBiome.java index 3dde27044..0ae7d696a 100644 --- a/core/src/main/java/art/arcane/iris/generation/biome/IrisBiome.java +++ b/core/src/main/java/art/arcane/iris/generation/biome/IrisBiome.java @@ -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) { diff --git a/core/src/main/java/art/arcane/iris/generation/biome/IrisBiomeLayerGenerator.java b/core/src/main/java/art/arcane/iris/generation/biome/IrisBiomeLayerGenerator.java index 03484f70c..952d0493c 100644 --- a/core/src/main/java/art/arcane/iris/generation/biome/IrisBiomeLayerGenerator.java +++ b/core/src/main/java/art/arcane/iris/generation/biome/IrisBiomeLayerGenerator.java @@ -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 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"); } diff --git a/core/src/main/java/art/arcane/iris/generation/biome/IrisBiomePaletteLayer.java b/core/src/main/java/art/arcane/iris/generation/biome/IrisBiomePaletteLayer.java index f4192a042..b91dc12e4 100644 --- a/core/src/main/java/art/arcane/iris/generation/biome/IrisBiomePaletteLayer.java +++ b/core/src/main/java/art/arcane/iris/generation/biome/IrisBiomePaletteLayer.java @@ -112,11 +112,19 @@ public class IrisBiomePaletteLayer { private NativeBlockState fit(KList 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); } diff --git a/core/src/main/java/art/arcane/iris/generation/decoration/IrisDecorator.java b/core/src/main/java/art/arcane/iris/generation/decoration/IrisDecorator.java index 70574f844..6add17ca5 100644 --- a/core/src/main/java/art/arcane/iris/generation/decoration/IrisDecorator.java +++ b/core/src/main/java/art/arcane/iris/generation/decoration/IrisDecorator.java @@ -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) { diff --git a/core/src/main/java/art/arcane/iris/generation/noise/GeneratorProgram.java b/core/src/main/java/art/arcane/iris/generation/noise/GeneratorProgram.java index bc4daf274..cba7732c1 100644 --- a/core/src/main/java/art/arcane/iris/generation/noise/GeneratorProgram.java +++ b/core/src/main/java/art/arcane/iris/generation/noise/GeneratorProgram.java @@ -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) { diff --git a/core/src/main/java/art/arcane/iris/generation/noise/IrisGenerator.java b/core/src/main/java/art/arcane/iris/generation/noise/IrisGenerator.java index 300a3fa20..c0019a056 100644 --- a/core/src/main/java/art/arcane/iris/generation/noise/IrisGenerator.java +++ b/core/src/main/java/art/arcane/iris/generation/noise/IrisGenerator.java @@ -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); diff --git a/core/src/main/java/art/arcane/iris/generation/noise/IrisGeneratorStyle.java b/core/src/main/java/art/arcane/iris/generation/noise/IrisGeneratorStyle.java index 7cbdff5ff..3a1d81c55 100644 --- a/core/src/main/java/art/arcane/iris/generation/noise/IrisGeneratorStyle.java +++ b/core/src/main/java/art/arcane/iris/generation/noise/IrisGeneratorStyle.java @@ -83,6 +83,8 @@ public class IrisGeneratorStyle { @MaxNumber(8192) @Description("If the cache size is set above 0, this generator will be cached") private int cacheSize = 0; + @Description("Rolls this noise from the world seed and this number, so every style with the same seed shares one noise. Child biomes, palettes and decorator placement read a seeded style flat in blocks: zoom is its only scale, so a layer's zoom, childShrinkFactor and the decorator's extra zoom don't apply.") + private Long seed = null; public IrisGeneratorStyle(NoiseStyle s) { this.style = s; @@ -119,7 +121,34 @@ public class IrisGeneratorStyle { } private int hash() { - return Objects.hash(expression, imageMapHash(), multiplier, fracture != null ? fracture.hash() : 0, exponent, cacheSize, zoom, cellularZoom, cellularFrequency, style == null ? null : style.name()); + int unseededHash = Objects.hash(expression, imageMapHash(), multiplier, fracture != null ? fracture.hash() : 0, exponent, cacheSize, zoom, cellularZoom, cellularFrequency, style == null ? null : style.name()); + return isSeeded() ? Objects.hash(unseededHash, seed) : unseededHash; + } + + public boolean isSeeded() { + return seed != null; + } + + /** The random a style is built from: the caller's, or for a seeded style one rolled from its seed and the world seed. */ + public RNG rollFor(RNG callerRandom, Engine engine) { + if (!isSeeded()) { + return callerRandom; + } + + return new RNG(rolledSeed(engine)); + } + + private long rolledSeed(Engine engine) { + long worldSeed = engine == null ? 0L : engine.getSeedManager().getSeed(); + return splitMix(worldSeed ^ splitMix(seed)); + } + + // Spreads nearby seed numbers far apart; Iris's own seed forking only adds. + private static long splitMix(long value) { + long mixed = value + 0x9E3779B97F4A7C15L; + mixed = (mixed ^ (mixed >>> 30)) * 0xBF58476D1CE4E5B9L; + mixed = (mixed ^ (mixed >>> 27)) * 0x94D049BB133111EBL; + return mixed ^ (mixed >>> 31); } public int prebakeSignature() { @@ -163,10 +192,11 @@ public class IrisGeneratorStyle { } } - private CNG createNoCache(RNG rng, PackRuntime runtime, int octaveMultiplier, int fallbackCacheSize, + private CNG createNoCache(RNG callerRandom, PackRuntime runtime, int octaveMultiplier, int fallbackCacheSize, boolean quietCacheLog) { IrisData data = runtime.data(); Engine engine = runtime.engine(); + RNG rng = rollFor(callerRandom, engine); requirePositiveFinite("zoom", zoom); requirePositiveFinite("exponent", exponent); if (!Double.isFinite(cellularFrequency) || cellularFrequency < 0D) { @@ -231,8 +261,8 @@ public class IrisGeneratorStyle { return create(rng.getSeed(), runtime); } - public CNG create(long seed, PackRuntime runtime) { - return runtime.styleGenerator(this, seed); + public CNG create(long callerSeed, PackRuntime runtime) { + return runtime.styleGenerator(this, isSeeded() ? rolledSeed(runtime.engine()) : callerSeed); } @SuppressWarnings("BooleanMethodIsAlwaysInverted") diff --git a/core/src/main/java/art/arcane/iris/generation/stage/IrisFloatingChildBiomeModifier.java b/core/src/main/java/art/arcane/iris/generation/stage/IrisFloatingChildBiomeModifier.java index 2c1802e4b..e7c4e94ca 100644 --- a/core/src/main/java/art/arcane/iris/generation/stage/IrisFloatingChildBiomeModifier.java +++ b/core/src/main/java/art/arcane/iris/generation/stage/IrisFloatingChildBiomeModifier.java @@ -102,7 +102,7 @@ public class IrisFloatingChildBiomeModifier extends EngineAssignedModifier getTile(RNG rng, double x, double y, double z, IrisData rdata) { diff --git a/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/noise/NoiseStyleCompiler.java b/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/noise/NoiseStyleCompiler.java index a49a886d5..bd987a5c7 100644 --- a/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/noise/NoiseStyleCompiler.java +++ b/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/noise/NoiseStyleCompiler.java @@ -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 diagnostics; + private final Set reportedSeeds = ConcurrentHashMap.newKeySet(); private final Map leaves = new ConcurrentHashMap<>(); private final Map 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 cellular, StyleCompiler selectors) { + private NoiseStyleCompiler(Function cellular, StyleCompiler selectors, + List diagnostics) { this.cellular = Objects.requireNonNull(cellular.apply(this), "cellular"); this.selectors = selectors == null ? this : selectors; + this.diagnostics = diagnostics; } public static NoiseStyleCompiler create(List 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); diff --git a/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/terrain/GeneratorCompiler.java b/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/terrain/GeneratorCompiler.java index 19dbdf98b..c36052adc 100644 --- a/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/terrain/GeneratorCompiler.java +++ b/core/src/main/java/art/arcane/iris/pack/datapack/export/compile/terrain/GeneratorCompiler.java @@ -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"); } diff --git a/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeLayerSlopeSourceTest.java b/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeLayerSlopeSourceTest.java index 9335920c3..41539fb12 100644 --- a/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeLayerSlopeSourceTest.java +++ b/core/src/test/java/art/arcane/iris/generation/biome/IrisBiomeLayerSlopeSourceTest.java @@ -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)); diff --git a/core/src/test/java/art/arcane/iris/generation/biome/IrisSurfaceLayerFallbackTest.java b/core/src/test/java/art/arcane/iris/generation/biome/IrisSurfaceLayerFallbackTest.java index c6f7c8102..76b5006bc 100644 --- a/core/src/test/java/art/arcane/iris/generation/biome/IrisSurfaceLayerFallbackTest.java +++ b/core/src/test/java/art/arcane/iris/generation/biome/IrisSurfaceLayerFallbackTest.java @@ -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); diff --git a/core/src/test/java/art/arcane/iris/generation/noise/IrisGeneratorExponentTest.java b/core/src/test/java/art/arcane/iris/generation/noise/IrisGeneratorExponentTest.java new file mode 100644 index 000000000..c5532e1db --- /dev/null +++ b/core/src/test/java/art/arcane/iris/generation/noise/IrisGeneratorExponentTest.java @@ -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 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)); + } +} diff --git a/core/src/test/java/art/arcane/iris/generation/noise/IrisGeneratorStyleSeedTest.java b/core/src/test/java/art/arcane/iris/generation/noise/IrisGeneratorStyleSeedTest.java new file mode 100644 index 000000000..c1c40b0bb --- /dev/null +++ b/core/src/test/java/art/arcane/iris/generation/noise/IrisGeneratorStyleSeedTest.java @@ -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; + } +} diff --git a/core/src/test/java/art/arcane/iris/pack/schema/SchemaBuilderIdentityTest.java b/core/src/test/java/art/arcane/iris/pack/schema/SchemaBuilderIdentityTest.java index 5d3ae2867..aff78d2e8 100644 --- a/core/src/test/java/art/arcane/iris/pack/schema/SchemaBuilderIdentityTest.java +++ b/core/src/test/java/art/arcane/iris/pack/schema/SchemaBuilderIdentityTest.java @@ -84,7 +84,7 @@ public class SchemaBuilderIdentityTest { @ClassRule public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean(); - private static final String EXPECTED_SCHEMA_DIGEST = "907c3f1d5a33281be801a23d86c4b8e1b5d933ddfc3445b179ece7898aa65d46"; + private static final String EXPECTED_SCHEMA_DIGEST = "1a10c843c6dbe0f60b2dd2cd3a48c04407f30b0ade212cc69a6ba1c4188f25ce"; private static final List> SCHEMA_ROOTS = List.of( IrisDimension.class, From ac5788ef02c9c8f0dddb323c3aa0c68fc994355a Mon Sep 17 00:00:00 2001 From: Piexel <107539181+piexelated@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:52:26 +0100 Subject: [PATCH 07/12] 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 --- .../arcane/iris/modded/ModdedLootApplier.java | 10 +- .../mantle/MantleObjectComponent.java | 27 +- .../pack/loading/ImageResourceLoader.java | 31 ++- .../arcane/iris/pack/loading/IrisData.java | 25 ++ .../loading/MatterObjectResourceLoader.java | 11 +- .../pack/loading/ObjectResourceLoader.java | 11 +- .../iris/pack/loading/ResourceLoader.java | 30 ++- .../structure/object/IrisObjectPlacement.java | 6 +- .../art/arcane/iris/world/loot/IrisLoot.java | 11 +- .../PlacementMarkerOnceWarningTest.java | 62 +++++ .../ResourceLoaderOnceWarningTest.java | 241 ++++++++++++++++++ .../art/arcane/iris/spi/IrisLoggingTest.java | 62 +++++ .../IrisObjectPlacementOnceWarningTest.java | 84 ++++++ .../arcane/iris/testsupport/CapturedLog.java | 85 ++++++ .../world/loot/IrisLootOnceWarningTest.java | 78 ++++++ .../java/art/arcane/iris/spi/IrisLogging.java | 60 ++++- 16 files changed, 773 insertions(+), 61 deletions(-) create mode 100644 core/src/test/java/art/arcane/iris/generation/mantle/PlacementMarkerOnceWarningTest.java create mode 100644 core/src/test/java/art/arcane/iris/pack/loading/ResourceLoaderOnceWarningTest.java create mode 100644 core/src/test/java/art/arcane/iris/structure/object/IrisObjectPlacementOnceWarningTest.java create mode 100644 core/src/test/java/art/arcane/iris/testsupport/CapturedLog.java create mode 100644 core/src/test/java/art/arcane/iris/world/loot/IrisLootOnceWarningTest.java diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedLootApplier.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedLootApplier.java index 7129371bc..c57002ce8 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedLootApplier.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedLootApplier.java @@ -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); diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/MantleObjectComponent.java b/core/src/main/java/art/arcane/iris/generation/mantle/MantleObjectComponent.java index 176ee80d6..071895339 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/MantleObjectComponent.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/MantleObjectComponent.java @@ -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 CAVE_REJECT_LOG_STATE = new ConcurrentHashMap<>(); - private static final Set 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 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 ? "" : 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 ? "" : 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 ? "" : 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 ? "" : 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/")) diff --git a/core/src/main/java/art/arcane/iris/pack/loading/ImageResourceLoader.java b/core/src/main/java/art/arcane/iris/pack/loading/ImageResourceLoader.java index e43dafeee..d7ea34618 100644 --- a/core/src/main/java/art/arcane/iris/pack/loading/ImageResourceLoader.java +++ b/core/src/main/java/art/arcane/iris/pack/loading/ImageResourceLoader.java @@ -63,14 +63,14 @@ public class ImageResourceLoader extends ResourceLoader { 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 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 { 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 { } } } 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 { 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 { 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 { 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 { 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); diff --git a/core/src/main/java/art/arcane/iris/pack/loading/IrisData.java b/core/src/main/java/art/arcane/iris/pack/loading/IrisData.java index 9f4873c25..6d617c9b2 100644 --- a/core/src/main/java/art/arcane/iris/pack/loading/IrisData.java +++ b/core/src/main/java/art/arcane/iris/pack/loading/IrisData.java @@ -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 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(); diff --git a/core/src/main/java/art/arcane/iris/pack/loading/MatterObjectResourceLoader.java b/core/src/main/java/art/arcane/iris/pack/loading/MatterObjectResourceLoader.java index 2c5195678..525b13e73 100644 --- a/core/src/main/java/art/arcane/iris/pack/loading/MatterObjectResourceLoader.java +++ b/core/src/main/java/art/arcane/iris/pack/loading/MatterObjectResourceLoader.java @@ -58,8 +58,7 @@ public class MatterObjectResourceLoader extends ResourceLoader 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 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 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 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 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); diff --git a/core/src/main/java/art/arcane/iris/pack/loading/ObjectResourceLoader.java b/core/src/main/java/art/arcane/iris/pack/loading/ObjectResourceLoader.java index c11320af1..46466f309 100644 --- a/core/src/main/java/art/arcane/iris/pack/loading/ObjectResourceLoader.java +++ b/core/src/main/java/art/arcane/iris/pack/loading/ObjectResourceLoader.java @@ -60,13 +60,12 @@ public class ObjectResourceLoader extends ResourceLoader { 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 { 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 { 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 { 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; } diff --git a/core/src/main/java/art/arcane/iris/pack/loading/ResourceLoader.java b/core/src/main/java/art/arcane/iris/pack/loading/ResourceLoader.java index 3335e7262..26d45054c 100644 --- a/core/src/main/java/art/arcane/iris/pack/loading/ResourceLoader.java +++ b/core/src/main/java/art/arcane/iris/pack/loading/ResourceLoader.java @@ -91,6 +91,9 @@ public class ResourceLoader 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 schemaBuildQueue = ConcurrentHashMap.newKeySet(); protected final AtomicCache> folderCache; @@ -217,7 +220,7 @@ public class ResourceLoader 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 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 implements MeteredCache { .orElse("")); } + 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 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; } diff --git a/core/src/main/java/art/arcane/iris/structure/object/IrisObjectPlacement.java b/core/src/main/java/art/arcane/iris/structure/object/IrisObjectPlacement.java index f1ad4953d..99342890b 100644 --- a/core/src/main/java/art/arcane/iris/structure/object/IrisObjectPlacement.java +++ b/core/src/main/java/art/arcane/iris/structure/object/IrisObjectPlacement.java @@ -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()) { diff --git a/core/src/main/java/art/arcane/iris/world/loot/IrisLoot.java b/core/src/main/java/art/arcane/iris/world/loot/IrisLoot.java index a3f11b834..a6170f5f0 100644 --- a/core/src/main/java/art/arcane/iris/world/loot/IrisLoot.java +++ b/core/src/main/java/art/arcane/iris/world/loot/IrisLoot.java @@ -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 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 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(); diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/PlacementMarkerOnceWarningTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/PlacementMarkerOnceWarningTest.java new file mode 100644 index 000000000..6f3a02ae1 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/generation/mantle/PlacementMarkerOnceWarningTest.java @@ -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()); + } +} diff --git a/core/src/test/java/art/arcane/iris/pack/loading/ResourceLoaderOnceWarningTest.java b/core/src/test/java/art/arcane/iris/pack/loading/ResourceLoaderOnceWarningTest.java new file mode 100644 index 000000000..2aba25b85 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/pack/loading/ResourceLoaderOnceWarningTest.java @@ -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); + } +} diff --git a/core/src/test/java/art/arcane/iris/spi/IrisLoggingTest.java b/core/src/test/java/art/arcane/iris/spi/IrisLoggingTest.java index fb68e4b02..cb3e24cb8 100644 --- a/core/src/test/java/art/arcane/iris/spi/IrisLoggingTest.java +++ b/core/src/test/java/art/arcane/iris/spi/IrisLoggingTest.java @@ -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; diff --git a/core/src/test/java/art/arcane/iris/structure/object/IrisObjectPlacementOnceWarningTest.java b/core/src/test/java/art/arcane/iris/structure/object/IrisObjectPlacementOnceWarningTest.java new file mode 100644 index 000000000..de6d26590 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/structure/object/IrisObjectPlacementOnceWarningTest.java @@ -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().qadd(loot)); + return placement; + } + + private void lookUpTable(IrisObjectPlacement placement) { + placement.getCache(data); + } +} diff --git a/core/src/test/java/art/arcane/iris/testsupport/CapturedLog.java b/core/src/test/java/art/arcane/iris/testsupport/CapturedLog.java new file mode 100644 index 000000000..57e762642 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/testsupport/CapturedLog.java @@ -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 levels = new ArrayList<>(); + private final List messages = new ArrayList<>(); + private final List 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 warnings(String prefix) { + List 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 messages() { + return messages; + } + + public List reportedErrors() { + return reportedErrors; + } + + @Override + public void close() { + IrisPlatforms.unbind(); + } +} diff --git a/core/src/test/java/art/arcane/iris/world/loot/IrisLootOnceWarningTest.java b/core/src/test/java/art/arcane/iris/world/loot/IrisLootOnceWarningTest.java new file mode 100644 index 000000000..46269ffe9 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/world/loot/IrisLootOnceWarningTest.java @@ -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 + } + } +} diff --git a/spi/src/main/java/art/arcane/iris/spi/IrisLogging.java b/spi/src/main/java/art/arcane/iris/spi/IrisLogging.java index 3b35fd757..4d029c74b 100644 --- a/spi/src/main/java/art/arcane/iris/spi/IrisLogging.java +++ b/spi/src/main/java/art/arcane/iris/spi/IrisLogging.java @@ -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 ONCE_KEYS = ConcurrentHashMap.newKeySet(); + static final int MAX_ONCE_KEYS = 512; + private static final Map ONCE_KEYS = Collections.synchronizedMap( + new LinkedHashMap<>(64, 0.75F, true) { + @Override + protected boolean removeEldestEntry(Map.Entry 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)\\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 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) { From 77969617d896ffbedf0880e5e3bd56f12ac9b566 Mon Sep 17 00:00:00 2001 From: Brian Fopiano Date: Fri, 27 Nov 2026 20:36:20 -0500 Subject: [PATCH 08/12] Fix Bukkit jar build - Keep TomlSegments and ConfigComments in the shaded config classes - Update the Mac noise hash after the fracture fix --- core/build.gradle | 2 +- .../art/arcane/iris/generation/noise/NoiseSeedCohesionTest.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/core/build.gradle b/core/build.gradle index 8409f6e52..162d97ebe 100644 --- a/core/build.gradle +++ b/core/build.gradle @@ -482,7 +482,7 @@ List 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) diff --git a/core/src/test/java/art/arcane/iris/generation/noise/NoiseSeedCohesionTest.java b/core/src/test/java/art/arcane/iris/generation/noise/NoiseSeedCohesionTest.java index 9be2435de..583290af0 100644 --- a/core/src/test/java/art/arcane/iris/generation/noise/NoiseSeedCohesionTest.java +++ b/core/src/test/java/art/arcane/iris/generation/noise/NoiseSeedCohesionTest.java @@ -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() { From c71feb62e0b1190abb744a77264a97f061cb6aa6 Mon Sep 17 00:00:00 2001 From: Brian Fopiano Date: Sat, 28 Nov 2026 08:18:44 -0500 Subject: [PATCH 09/12] 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 --- .../pack/datapack/v1217/DataFixerV1217.java | 2 +- .../v1217/DataFixerV1217BedRuleTest.java | 45 +++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 core/src/test/java/art/arcane/iris/pack/datapack/v1217/DataFixerV1217BedRuleTest.java diff --git a/core/src/main/java/art/arcane/iris/pack/datapack/v1217/DataFixerV1217.java b/core/src/main/java/art/arcane/iris/pack/datapack/v1217/DataFixerV1217.java index c1edff8b5..1a027ad0d 100644 --- a/core/src/main/java/art/arcane/iris/pack/datapack/v1217/DataFixerV1217.java +++ b/core/src/main/java/art/arcane/iris/pack/datapack/v1217/DataFixerV1217.java @@ -143,7 +143,7 @@ public class DataFixerV1217 extends DataFixerV1213 { attributes.put("minecraft:gameplay/bed_rule", new JSONObject() .put("can_set_spawn", "never") .put("can_sleep", "never") - .put("explodes", true)); + .put("destroy_on_use", true)); } attributes.put("minecraft:gameplay/respawn_anchor_works", json.remove("respawn_anchor_works")); diff --git a/core/src/test/java/art/arcane/iris/pack/datapack/v1217/DataFixerV1217BedRuleTest.java b/core/src/test/java/art/arcane/iris/pack/datapack/v1217/DataFixerV1217BedRuleTest.java new file mode 100644 index 000000000..9d1d694ff --- /dev/null +++ b/core/src/test/java/art/arcane/iris/pack/datapack/v1217/DataFixerV1217BedRuleTest.java @@ -0,0 +1,45 @@ +package art.arcane.iris.pack.datapack.v1217; + +import art.arcane.iris.pack.datapack.IDataFixer.Dimension; +import art.arcane.volmlib.util.json.JSONObject; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class DataFixerV1217BedRuleTest { + private final DataFixerV1217 fixer = new DataFixerV1217(); + + @Test + public void overworldBedsSleepWhenDark() { + JSONObject rule = bedRule(Dimension.OVERWORLD); + + assertEquals("when_dark", rule.getString("can_sleep")); + assertEquals("always", rule.getString("can_set_spawn")); + assertTrue(rule.has("error_message")); + } + + @Test + public void netherBedsAreDestroyedOnUse() { + assertDestroyedOnUse(bedRule(Dimension.NETHER)); + } + + @Test + public void endBedsAreDestroyedOnUse() { + assertDestroyedOnUse(bedRule(Dimension.END)); + } + + private JSONObject bedRule(Dimension dimension) { + return fixer.createDimension(dimension, -64, 384, 384, null) + .getJSONObject("attributes") + .getJSONObject("minecraft:gameplay/bed_rule"); + } + + private static void assertDestroyedOnUse(JSONObject rule) { + assertEquals("never", rule.getString("can_sleep")); + assertEquals("never", rule.getString("can_set_spawn")); + assertTrue(rule.getBoolean("destroy_on_use")); + assertFalse(rule.has("explodes")); + } +} From 95395cbc8794e953872e881c6a2124d3080dd7ca Mon Sep 17 00:00:00 2001 From: Brian Fopiano Date: Sat, 28 Nov 2026 09:55:11 -0500 Subject: [PATCH 10/12] 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 --- .../iris/world/history/GenerationHistory.java | 3 +- .../history/SavedTerrainRecoveryScan.java | 78 +++- .../history/SavedTerrainStatusCache.java | 379 ++++++++++++++++++ .../history/SavedTerrainRecoveryScanTest.java | 211 ++++++++++ 4 files changed, 665 insertions(+), 6 deletions(-) create mode 100644 core/src/main/java/art/arcane/iris/world/history/SavedTerrainStatusCache.java diff --git a/core/src/main/java/art/arcane/iris/world/history/GenerationHistory.java b/core/src/main/java/art/arcane/iris/world/history/GenerationHistory.java index 548ad2e5b..8b1b73081 100644 --- a/core/src/main/java/art/arcane/iris/world/history/GenerationHistory.java +++ b/core/src/main/java/art/arcane/iris/world/history/GenerationHistory.java @@ -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) diff --git a/core/src/main/java/art/arcane/iris/world/history/SavedTerrainRecoveryScan.java b/core/src/main/java/art/arcane/iris/world/history/SavedTerrainRecoveryScan.java index e3fba4542..71b83745b 100644 --- a/core/src/main/java/art/arcane/iris/world/history/SavedTerrainRecoveryScan.java +++ b/core/src/main/java/art/arcane/iris/world/history/SavedTerrainRecoveryScan.java @@ -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 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> 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; diff --git a/core/src/main/java/art/arcane/iris/world/history/SavedTerrainStatusCache.java b/core/src/main/java/art/arcane/iris/world/history/SavedTerrainStatusCache.java new file mode 100644 index 000000000..60e352b6a --- /dev/null +++ b/core/src/main/java/art/arcane/iris/world/history/SavedTerrainStatusCache.java @@ -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 previous; + private final Long2ObjectOpenHashMap 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 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 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 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 regions) { + static final Contents EMPTY = new Contents(0L, new Long2ObjectOpenHashMap<>()); + } +} diff --git a/core/src/test/java/art/arcane/iris/world/history/SavedTerrainRecoveryScanTest.java b/core/src/test/java/art/arcane/iris/world/history/SavedTerrainRecoveryScanTest.java index 58e1f2966..46ec07ebc 100644 --- a/core/src/test/java/art/arcane/iris/world/history/SavedTerrainRecoveryScanTest.java +++ b/core/src/test/java/art/arcane/iris/world/history/SavedTerrainRecoveryScanTest.java @@ -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); From 9425e802dc347115acaca489af925e6b05344b07 Mon Sep 17 00:00:00 2001 From: Brian Fopiano Date: Sat, 28 Nov 2026 09:32:14 -0500 Subject: [PATCH 11/12] 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 --- .../mantle/ObjectContinuationBundle.java | 23 ++- .../storage/matter/RetiredMatterSlices.java | 20 +++ .../ObjectContinuationRetiredSliceTest.java | 153 ++++++++++++++++++ 3 files changed, 194 insertions(+), 2 deletions(-) create mode 100644 core/src/main/java/art/arcane/iris/world/storage/matter/RetiredMatterSlices.java create mode 100644 core/src/test/java/art/arcane/iris/generation/mantle/ObjectContinuationRetiredSliceTest.java diff --git a/core/src/main/java/art/arcane/iris/generation/mantle/ObjectContinuationBundle.java b/core/src/main/java/art/arcane/iris/generation/mantle/ObjectContinuationBundle.java index 2719aaabe..fc3d1395b 100644 --- a/core/src/main/java/art/arcane/iris/generation/mantle/ObjectContinuationBundle.java +++ b/core/src/main/java/art/arcane/iris/generation/mantle/ObjectContinuationBundle.java @@ -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 fragments) { Matter matter = new IrisMatter(width, height, depth); int sliceCount = input.readUnsignedByte(); matter.getHeader().read(input); + HashSet 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 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) { diff --git a/core/src/main/java/art/arcane/iris/world/storage/matter/RetiredMatterSlices.java b/core/src/main/java/art/arcane/iris/world/storage/matter/RetiredMatterSlices.java new file mode 100644 index 000000000..f64689e81 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/world/storage/matter/RetiredMatterSlices.java @@ -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 IDS = Set.of(TREE_CANOPY); + + private RetiredMatterSlices() { + } + + public static boolean isRetired(String id) { + return IDS.contains(id); + } +} diff --git a/core/src/test/java/art/arcane/iris/generation/mantle/ObjectContinuationRetiredSliceTest.java b/core/src/test/java/art/arcane/iris/generation/mantle/ObjectContinuationRetiredSliceTest.java new file mode 100644 index 000000000..db40b9fb7 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/generation/mantle/ObjectContinuationRetiredSliceTest.java @@ -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 byte[] sliceBytes(Class type, T value) throws IOException { + Matter matter = new IrisMatter(16, 16, 16); + MatterSlice 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 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, Object> byType = new HashMap<>((Map, Object>) byTypeAccessor.invoke(registry)); + Map byId = new HashMap<>((Map) 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); + } +} From 512ea0b0d7ab6651cbcec42bee140b7a0567f2af Mon Sep 17 00:00:00 2001 From: Brian Fopiano Date: Sat, 28 Nov 2026 09:51:11 -0500 Subject: [PATCH 12/12] 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 --- .../runtime/DimensionTerrainContext.java | 16 +++- .../iris/generation/runtime/IrisComplex.java | 85 +++++++++++++++--- .../iris/pack/PackDimensionValidator.java | 13 +-- .../art/arcane/iris/pack/PackValidator.java | 29 +++++- .../arcane/iris/studio/map/BiomeExplorer.java | 2 +- .../iris/studio/map/PackFileOpener.java | 8 +- .../map/components/MapTileRenderer.java | 3 +- .../iris/studio/render/IrisRenderer.java | 5 ++ .../runtime/IrisComplexSurfaceBiomeTest.java | 90 +++++++++++++++++++ .../PackValidatorRegionLandBiomesTest.java | 55 ++++++++++++ 10 files changed, 281 insertions(+), 25 deletions(-) create mode 100644 core/src/test/java/art/arcane/iris/pack/PackValidatorRegionLandBiomesTest.java diff --git a/core/src/main/java/art/arcane/iris/generation/runtime/DimensionTerrainContext.java b/core/src/main/java/art/arcane/iris/generation/runtime/DimensionTerrainContext.java index eed52c3ae..5fe2acf11 100644 --- a/core/src/main/java/art/arcane/iris/generation/runtime/DimensionTerrainContext.java +++ b/core/src/main/java/art/arcane/iris/generation/runtime/DimensionTerrainContext.java @@ -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 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 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 biomeKeys(IrisRegion region, InferredType type) { + return type == InferredType.SEA ? region.getSeaBiomes() : region.getShoreBiomes(); + } + private static KList loadInferredBiomes( IrisData data, KList keys, diff --git a/core/src/main/java/art/arcane/iris/generation/runtime/IrisComplex.java b/core/src/main/java/art/arcane/iris/generation/runtime/IrisComplex.java index e96d2667b..88c4a69b1 100644 --- a/core/src/main/java/art/arcane/iris/generation/runtime/IrisComplex.java +++ b/core/src/main/java/art/arcane/iris/generation/runtime/IrisComplex.java @@ -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 NO_BIOMES = ProceduralStream.of((x, z) -> null, + Interpolated.of(value -> 0D, value -> null)); @Getter(AccessLevel.NONE) private final transient ThreadSlots gridBoundsCache = new ThreadSlots<>(GridBoundsCache::new); @Getter(AccessLevel.NONE) @@ -206,6 +212,8 @@ public class IrisComplex implements DataProvider { private ProceduralStream regionStyleStream; private ProceduralStream regionIdentityStream; private ProceduralStream bridgeStream; + @Getter(AccessLevel.NONE) + private ProceduralStream baseTypeStream; private ProceduralStream landBiomeStream; private ProceduralStream caveBiomeStream; private ProceduralStream 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 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 picked = new RarityStream<>(biomePickNoiseStream(engine.getDimension(), region, inferredType), - loadInferredBiomes(biomeKeys(region, inferredType), inferredType)); - return inferredType == InferredType.CAVE ? picked.onNull(emptyBiome) : picked; + ProceduralStream noise = biomePickNoiseStream(engine.getDimension(), region, inferredType); + KList 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 requireLandBiomes(IrisRegion region, KList landBiomes) { + if (!landBiomes.isEmpty()) { + return landBiomes; + } + String regionKey = region.getLoadKey() == null || region.getLoadKey().isBlank() ? "" : 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>> streams, InferredType inferredType) { + for (Map> 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>> 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 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 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; diff --git a/core/src/main/java/art/arcane/iris/pack/PackDimensionValidator.java b/core/src/main/java/art/arcane/iris/pack/PackDimensionValidator.java index 59f50ffc0..c9bd9d543 100644 --- a/core/src/main/java/art/arcane/iris/pack/PackDimensionValidator.java +++ b/core/src/main/java/art/arcane/iris/pack/PackDimensionValidator.java @@ -104,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++; } diff --git a/core/src/main/java/art/arcane/iris/pack/PackValidator.java b/core/src/main/java/art/arcane/iris/pack/PackValidator.java index 9970a9c7f..745723ab2 100644 --- a/core/src/main/java/art/arcane/iris/pack/PackValidator.java +++ b/core/src/main/java/art/arcane/iris/pack/PackValidator.java @@ -211,6 +211,7 @@ public final class PackValidator { applyCompatFindings(minecraftVersion, dimensions.anyExcluded(), findings, blockingErrors, warnings); applyRequireAllContent(packFolder.getName(), dimensions.reachedByRequiringDimension(), minecraftVersion, findings, blockingErrors); + addDistinct(blockingErrors, excludedLandErrors(data, dimensions.regionKeys(), minecraftVersion)); return findings; } catch (Throwable e) { IrisLogging.reportError("Version-content gating failed for pack '" + packFolder.getName() + "'", e); @@ -239,6 +240,7 @@ public final class PackValidator { private static GatedDimensions loadEverything(File packFolder, IrisData data, File[] dimensionFiles) { boolean dimensionExcluded = false; Map> reachedByRequiringDimension = new LinkedHashMap<>(); + Set regionKeys = new LinkedHashSet<>(); List folders = data.getLoaders().values().stream().map(ResourceLoader::getFolderName).toList(); File dimensionsFolder = new File(packFolder, DIMENSIONS_FOLDER); for (File dimensionFile : dimensionFiles) { @@ -249,6 +251,8 @@ public final class PackValidator { } if (dimension.isCompatExcluded()) { dimensionExcluded = true; + } else { + regionKeys.addAll(dimension.getRegions()); } if (dimension.isRequireAllContent()) { reachedByRequiringDimension.put(dimension.getLoadKey(), PackContentReach.referencedFrom( @@ -271,10 +275,31 @@ public final class PackValidator { for (IrisObjectPlacement placement : placements) { placement.evaluateCompat(data); } - return new GatedDimensions(dimensionExcluded, reachedByRequiringDimension); + return new GatedDimensions(dimensionExcluded, reachedByRequiringDimension, regionKeys); } - private record GatedDimensions(boolean anyExcluded, Map> reachedByRequiringDimension) { + private record GatedDimensions(boolean anyExcluded, Map> reachedByRequiringDimension, + Set 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 excludedLandErrors(IrisData data, Collection regionKeys, String minecraftVersion) { + List errors = new ArrayList<>(); + for (String regionKey : regionKeys) { + IrisRegion region = data.getRegionLoader().load(regionKey, false); + if (region == null || region.isCompatExcluded()) { + continue; + } + List 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 out) { diff --git a/core/src/main/java/art/arcane/iris/studio/map/BiomeExplorer.java b/core/src/main/java/art/arcane/iris/studio/map/BiomeExplorer.java index bbdd6568c..91586b057 100644 --- a/core/src/main/java/art/arcane/iris/studio/map/BiomeExplorer.java +++ b/core/src/main/java/art/arcane/iris/studio/map/BiomeExplorer.java @@ -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)); diff --git a/core/src/main/java/art/arcane/iris/studio/map/PackFileOpener.java b/core/src/main/java/art/arcane/iris/studio/map/PackFileOpener.java index b02562d76..fb99e0416 100644 --- a/core/src/main/java/art/arcane/iris/studio/map/PackFileOpener.java +++ b/core/src/main/java/art/arcane/iris/studio/map/PackFileOpener.java @@ -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(); diff --git a/core/src/main/java/art/arcane/iris/studio/map/components/MapTileRenderer.java b/core/src/main/java/art/arcane/iris/studio/map/components/MapTileRenderer.java index 20e0628e1..3b43244d7 100644 --- a/core/src/main/java/art/arcane/iris/studio/map/components/MapTileRenderer.java +++ b/core/src/main/java/art/arcane/iris/studio/map/components/MapTileRenderer.java @@ -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 regions = complex.getRegionStream(); - ProceduralStream types = complex.getBridgeStream(); Map>> 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); }; } diff --git a/core/src/main/java/art/arcane/iris/studio/render/IrisRenderer.java b/core/src/main/java/art/arcane/iris/studio/render/IrisRenderer.java index 35502c31e..1fade00fb 100644 --- a/core/src/main/java/art/arcane/iris/studio/render/IrisRenderer.java +++ b/core/src/main/java/art/arcane/iris/studio/render/IrisRenderer.java @@ -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 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(); diff --git a/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexSurfaceBiomeTest.java b/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexSurfaceBiomeTest.java index 49d657b73..f4160348b 100644 --- a/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexSurfaceBiomeTest.java +++ b/core/src/test/java/art/arcane/iris/generation/runtime/IrisComplexSurfaceBiomeTest.java @@ -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>> 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 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); diff --git a/core/src/test/java/art/arcane/iris/pack/PackValidatorRegionLandBiomesTest.java b/core/src/test/java/art/arcane/iris/pack/PackValidatorRegionLandBiomesTest.java new file mode 100644 index 000000000..5db8c47b1 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/pack/PackValidatorRegionLandBiomesTest.java @@ -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 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 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 errors = validate("{\"landBiomes\":[\"ocean\"]}"); + + assertTrue(errors.toString(), errors.isEmpty()); + } + + private List 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 errors = new ArrayList<>(); + PackDimensionValidator.validateDimensions(pack, new File[]{dimension}, errors, new ArrayList<>()); + return errors; + } +}