From 190301d0f541baab4ea845611ee4b11311607506 Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 17 Sep 2026 13:55:53 +0200 Subject: [PATCH] save point 7 --- .../arcane/iris/engine/EngineHotloader.java | 3 +- .../art/arcane/iris/engine/EngineRuntime.java | 10 +- .../iris/engine/EngineRuntimeBuilder.java | 6 +- .../art/arcane/iris/engine/IrisEngine.java | 13 + .../arcane/iris/engine/framework/Engine.java | 4 + .../object/IrisObjectPlacementRunner.java | 648 +----------------- .../iris/engine/object/ObjectBlockPass.java | 145 ++-- .../engine/object/ObjectMarkerPlacement.java | 13 +- .../object/ObjectModuleCeilingHang.java | 12 +- .../iris/engine/object/ObjectPlaceMode.java | 45 +- .../iris/engine/object/PlacementBlock.java | 8 + .../engine/object/PlacementBlockWrite.java | 6 + .../iris/engine/object/PlacementContext.java | 143 +--- .../iris/engine/object/PlacementFunction.java | 6 +- .../engine/object/PlacementLifecycle.java | 35 + .../object/PlacementLifecycleBuilder.java | 85 ++- .../object/PlacementLifecycleDependency.java | 15 +- .../engine/object/PlacementLifecycles.java | 43 ++ .../iris/engine/object/PlacementModule.java | 30 +- .../engine/object/PlacementModuleAnchor.java | 42 ++ .../engine/object/PlacementModuleBlocks.java | 18 + .../engine/object/PlacementModuleBore.java | 24 + .../engine/object/PlacementModuleBounds.java | 43 ++ .../object/PlacementModuleCenterHeight.java | 16 +- .../object/PlacementModuleCollision.java | 41 ++ .../object/PlacementModuleFloating.java | 6 +- .../engine/object/PlacementModuleHeight.java | 70 +- .../engine/object/PlacementModuleLimits.java | 34 + ...cementModuleNativeStructureProtection.java | 111 +++ .../engine/object/PlacementModulePaint.java | 16 +- .../object/PlacementModulePreparation.java | 95 +++ .../engine/object/PlacementModuleSlope.java | 69 ++ .../engine/object/PlacementModuleSnow.java | 44 ++ .../engine/object/PlacementModuleStilt.java | 351 +++++----- .../object/PlacementModuleSurfaceSupport.java | 65 ++ .../engine/object/PlacementModuleVacuum.java | 89 +++ .../iris/engine/object/PlacementStage.java | 38 + .../iris/engine/object/PlacementState.java | 57 +- .../engine/EnginePlacementLifecycleTest.java | 55 ++ ...tingObjectComponentBoundaryRadiusTest.java | 17 +- ...ntleObjectComponentBoundaryRadiusTest.java | 17 +- ...isObjectPlacementRunnerRegressionTest.java | 290 +++++++- .../IrisObjectStructurePieceAirTest.java | 14 +- ...IrisObjectSurfaceSupportPlacementTest.java | 15 +- .../object/NativeStructureObjectVetoTest.java | 17 +- .../engine/object/PlacementLifecycleTest.java | 200 ++++++ 46 files changed, 1965 insertions(+), 1159 deletions(-) create mode 100644 core/src/main/java/art/arcane/iris/engine/object/PlacementBlock.java create mode 100644 core/src/main/java/art/arcane/iris/engine/object/PlacementBlockWrite.java create mode 100644 core/src/main/java/art/arcane/iris/engine/object/PlacementLifecycle.java create mode 100644 core/src/main/java/art/arcane/iris/engine/object/PlacementLifecycles.java create mode 100644 core/src/main/java/art/arcane/iris/engine/object/PlacementModuleAnchor.java create mode 100644 core/src/main/java/art/arcane/iris/engine/object/PlacementModuleBlocks.java create mode 100644 core/src/main/java/art/arcane/iris/engine/object/PlacementModuleBore.java create mode 100644 core/src/main/java/art/arcane/iris/engine/object/PlacementModuleBounds.java create mode 100644 core/src/main/java/art/arcane/iris/engine/object/PlacementModuleCollision.java create mode 100644 core/src/main/java/art/arcane/iris/engine/object/PlacementModuleLimits.java create mode 100644 core/src/main/java/art/arcane/iris/engine/object/PlacementModuleNativeStructureProtection.java create mode 100644 core/src/main/java/art/arcane/iris/engine/object/PlacementModulePreparation.java create mode 100644 core/src/main/java/art/arcane/iris/engine/object/PlacementModuleSlope.java create mode 100644 core/src/main/java/art/arcane/iris/engine/object/PlacementModuleSnow.java create mode 100644 core/src/main/java/art/arcane/iris/engine/object/PlacementModuleSurfaceSupport.java create mode 100644 core/src/main/java/art/arcane/iris/engine/object/PlacementModuleVacuum.java create mode 100644 core/src/main/java/art/arcane/iris/engine/object/PlacementStage.java create mode 100644 core/src/test/java/art/arcane/iris/engine/EnginePlacementLifecycleTest.java create mode 100644 core/src/test/java/art/arcane/iris/engine/object/PlacementLifecycleTest.java diff --git a/core/src/main/java/art/arcane/iris/engine/EngineHotloader.java b/core/src/main/java/art/arcane/iris/engine/EngineHotloader.java index 763325b0f..575cbd632 100644 --- a/core/src/main/java/art/arcane/iris/engine/EngineHotloader.java +++ b/core/src/main/java/art/arcane/iris/engine/EngineHotloader.java @@ -67,7 +67,8 @@ final class EngineHotloader { nextComplex = assembly.complex; assembly.upperContext = engine.runtimeBuilder.buildUpperContext(); BiomeMaxes biomeMaxes = engine.runtimeBuilder.computeBiomeMaxes(); - next = previous.withComplex(assembly.cacheId, assembly.complex, assembly.upperContext, biomeMaxes); + next = previous.withComplex(assembly.cacheId, assembly.complex, assembly.upperContext, biomeMaxes, + assembly.placementLifecycles); } finally { engine.runtimeAssembly.remove(); } diff --git a/core/src/main/java/art/arcane/iris/engine/EngineRuntime.java b/core/src/main/java/art/arcane/iris/engine/EngineRuntime.java index 1686edc9d..103233a58 100644 --- a/core/src/main/java/art/arcane/iris/engine/EngineRuntime.java +++ b/core/src/main/java/art/arcane/iris/engine/EngineRuntime.java @@ -22,6 +22,7 @@ import art.arcane.iris.engine.framework.EngineEffects; import art.arcane.iris.engine.framework.EngineMode; import art.arcane.iris.engine.framework.EngineTarget; import art.arcane.iris.engine.framework.EngineWorldManager; +import art.arcane.iris.engine.object.PlacementLifecycles; import java.util.concurrent.CompletableFuture; @@ -38,13 +39,15 @@ record EngineRuntime( EngineMode mode, EngineWorldManager worldManager, CompletableFuture hash32, - BiomeMaxes biomeMaxes + BiomeMaxes biomeMaxes, + PlacementLifecycles placementLifecycles ) { EngineRuntime withComplex( int nextCacheId, IrisComplex nextComplex, UpperDimensionContext nextUpperContext, - BiomeMaxes nextBiomeMaxes + BiomeMaxes nextBiomeMaxes, + PlacementLifecycles nextPlacementLifecycles ) { return new EngineRuntime( nextCacheId, @@ -55,7 +58,8 @@ record EngineRuntime( mode, worldManager, hash32, - nextBiomeMaxes); + nextBiomeMaxes, + nextPlacementLifecycles); } record BiomeMaxes(double objectDensity, double layerDensity, double decoratorDensity) { diff --git a/core/src/main/java/art/arcane/iris/engine/EngineRuntimeBuilder.java b/core/src/main/java/art/arcane/iris/engine/EngineRuntimeBuilder.java index baa90d9b0..fdb5aea88 100644 --- a/core/src/main/java/art/arcane/iris/engine/EngineRuntimeBuilder.java +++ b/core/src/main/java/art/arcane/iris/engine/EngineRuntimeBuilder.java @@ -35,6 +35,7 @@ import art.arcane.iris.engine.object.IrisDimension; import art.arcane.iris.engine.object.IrisDimensionMode; import art.arcane.iris.engine.object.IrisDimensionModeType; import art.arcane.iris.engine.object.IrisObjectPlacement; +import art.arcane.iris.engine.object.PlacementLifecycles; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.IrisServices; import art.arcane.iris.util.project.context.IrisContext; @@ -300,10 +301,12 @@ final class EngineRuntimeBuilder { EngineMode mode; EngineWorldManager worldManager; CompletableFuture hash32; + final PlacementLifecycles placementLifecycles; RuntimeAssembly(int cacheId, EngineTarget target) { this.cacheId = cacheId; this.target = target; + this.placementLifecycles = PlacementLifecycles.resolve(); } EngineRuntime freeze(BiomeMaxes biomeMaxes) { @@ -319,7 +322,8 @@ final class EngineRuntimeBuilder { mode, worldManager, hash32, - biomeMaxes); + biomeMaxes, + placementLifecycles); } } } diff --git a/core/src/main/java/art/arcane/iris/engine/IrisEngine.java b/core/src/main/java/art/arcane/iris/engine/IrisEngine.java index 94ce8cc04..b504b449b 100644 --- a/core/src/main/java/art/arcane/iris/engine/IrisEngine.java +++ b/core/src/main/java/art/arcane/iris/engine/IrisEngine.java @@ -500,6 +500,19 @@ public class IrisEngine implements Engine { return current == null ? null : current.complex(); } + @Override + public art.arcane.iris.engine.object.PlacementLifecycles getPlacementLifecycles() { + RuntimeAssembly assembly = runtimeAssembly.get(); + if (assembly != null) { + return assembly.placementLifecycles; + } + EngineRuntime current = runtime; + if (current == null) { + throw new IllegalStateException("Placement requires an active Iris runtime."); + } + return current.placementLifecycles(); + } + @Override public EngineTarget getTarget() { RuntimeAssembly assembly = runtimeAssembly.get(); diff --git a/core/src/main/java/art/arcane/iris/engine/framework/Engine.java b/core/src/main/java/art/arcane/iris/engine/framework/Engine.java index 6f2adc84f..356ffc4d6 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/Engine.java +++ b/core/src/main/java/art/arcane/iris/engine/framework/Engine.java @@ -84,6 +84,10 @@ import java.util.stream.Collectors; public interface Engine extends DataProvider, Fallible, BlockUpdater, Renderer, Hotloadable { IrisComplex getComplex(); + default art.arcane.iris.engine.object.PlacementLifecycles getPlacementLifecycles() { + return art.arcane.iris.engine.object.PlacementLifecycles.defaults(); + } + default @Nullable UpperDimensionContext getUpperContext() { return null; } diff --git a/core/src/main/java/art/arcane/iris/engine/object/IrisObjectPlacementRunner.java b/core/src/main/java/art/arcane/iris/engine/object/IrisObjectPlacementRunner.java index b453a1e52..13b59cc18 100644 --- a/core/src/main/java/art/arcane/iris/engine/object/IrisObjectPlacementRunner.java +++ b/core/src/main/java/art/arcane/iris/engine/object/IrisObjectPlacementRunner.java @@ -19,661 +19,23 @@ package art.arcane.iris.engine.object; import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.IrisComplex; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.NativeStructureVolume; -import art.arcane.iris.engine.framework.PlacedObject; -import art.arcane.iris.engine.framework.placer.HeightmapObjectPlacer; -import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; -import art.arcane.iris.util.common.data.VectorMap; -import art.arcane.iris.util.common.math.IrisBlockVector; -import art.arcane.iris.util.project.noise.CNG; -import art.arcane.iris.util.project.noise.SimplexNoise; -import art.arcane.iris.util.project.stream.ProceduralStream; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.collection.KMap; -import art.arcane.iris.engine.object.PlacementContext.TransformedBounds; import art.arcane.volmlib.util.math.BlockPosition; -import art.arcane.volmlib.util.math.Position2; import art.arcane.volmlib.util.math.RNG; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiConsumer; -/** - * One-shot placement of an {@link IrisObject} into the world. Instances are cheap and single use: they exist so - * the placement pass can hoist its per-placement invariants without leaking that state onto the loader-cached - * (and thread-shared) object itself. - */ +/** Entry point for executing an engine's resolved placement plan. */ final class IrisObjectPlacementRunner { - private static final long IMPLAUSIBLE_BEDROCK_WARN_THROTTLE_MS = 5000L; - private static final long VACUUM_WAVE_SEED = 7392113L; - private static final ConcurrentHashMap IMPLAUSIBLE_BEDROCK_WARNS = new ConcurrentHashMap<>(); - private final IrisObject self; IrisObjectPlacementRunner(IrisObject self) { this.self = self; } - int place(int x, int yv, int z, IObjectPlacer oplacer, IrisObjectPlacement config, RNG rng, BiConsumer listener, CarveResult c, IrisData rdata) { - Objects.requireNonNull(oplacer, "Object placer is required."); - Objects.requireNonNull(config, "Object placement config is required."); - Objects.requireNonNull(rng, "Object placement RNG is required."); - Objects.requireNonNull(rdata, "Object placement data is required."); - - IObjectPlacer placer = config.getHeightmap() != null ? new HeightmapObjectPlacer(rng, x, yv, z, config, oplacer) : oplacer; - - boolean evaluateSlopeCondition = !config.isForcePlace() && !config.getSlopeCondition().isDefault(); - if (evaluateSlopeCondition || config.isRotateTowardsSlope()) { - Engine placementEngine = requireSlopeEngine(placer); - if (evaluateSlopeCondition && - !config.getSlopeCondition().isValid(placementEngine.getComplex().getSlopeStream().get(x, z))) { - return -1; - } - if (config.isRotateTowardsSlope()) { - withRotateTowardsSlope(config, rdata.getEngine(), x, z); - } - } - - if (config.isSmartBore()) { - IrisObjectShaping.ensureSmartBored(self); - } - - boolean warped = !config.getWarp().isFlat(); - // Placement-invariant hoists off the per-voxel loop: the warp CNG resolution went - // through a keyed cache probe per block, and the two boolean gates below cut per-block - // property scans that can never match for this placement. - CNG surfaceWarp = warped ? config.getSurfaceWarp(rng, self.getLoader()) : null; - double warpHalf = warped ? config.getWarp().getMultiplier() / 2D : 0D; - boolean preventingDecay = placer.isPreventingDecay(); - boolean waterlogCandidate = config.isWaterloggable() || config.isUnderwater(); - boolean rawStructurePiece = config.getMode() == ObjectPlaceMode.STRUCTURE_PIECE; - boolean organicFloor = config.getMode() == ObjectPlaceMode.ORGANIC_STILT; - boolean ceilingHang = config.getMode() == ObjectPlaceMode.CEILING_HANG; - boolean organic = organicFloor || ceilingHang; - boolean vacuuming = IrisObjectVacuum.isVacuumMode(config.getMode()); - boolean stilting = (config.getMode().equals(ObjectPlaceMode.STILT) || config.getMode().equals(ObjectPlaceMode.FAST_STILT) || - config.getMode() == ObjectPlaceMode.MIN_STILT || config.getMode() == ObjectPlaceMode.FAST_MIN_STILT || - config.getMode() == ObjectPlaceMode.CENTER_STILT || config.getMode() == ObjectPlaceMode.ERODE_STILT || organic); - boolean eroding = config.getMode() == ObjectPlaceMode.ERODE_STILT; - KMap heightmap = config.getSnow() > 0 ? new KMap<>() : null; - int spinx = rng.imax() / 1000; - int spiny = rng.imax() / 1000; - int spinz = rng.imax() / 1000; - int rty = config.getRotation().rotate(new IrisBlockVector(0, self.getCenter().getBlockY(), 0), spinx, spiny, spinz).getBlockY(); - int ty = config.getTranslate().translate(new IrisBlockVector(0, self.getCenter().getBlockY(), 0), config.getRotation(), spinx, spiny, spinz).getBlockY(); - // Per-placement invariants. The rotation kernel, the rotated translate offset and the edit-list emptiness - // are pure functions of (config, spin), all of which are fixed from here down. Recomputing them per block - // only cost allocations and transcendentals. - ObjectSpinKernel spin = new ObjectSpinKernel(config.getRotation(), spinx, spiny, spinz); - IrisObjectTranslate translate = config.getTranslate(); - boolean translating = translate.canTranslate(); - IrisBlockVector translateOffset = translating - ? config.getRotation().rotate(new IrisBlockVector(translate.getX(), translate.getY(), translate.getZ()), spinx, spiny, spinz) - : null; - boolean hasEdits = !config.getEdit().isEmpty(); - //int y = -1; - int xx, zz; - int yrand = config.getTranslate().getYRandom(); - yrand = yrand > 0 ? rng.i(0, yrand) : yrand < 0 ? rng.i(yrand, 0) : yrand; - int warpMargin = warped ? (int) Math.ceil(Math.abs(config.getWarp().getMultiplier()) / 2D) : 0; - PlacementContext context = new PlacementContext(config, rdata, placer, c, rng, spin, self, x, z, yv, rty); - TransformedBounds placementBounds = context.transformedBounds(spin, translating, translateOffset, ceilingHang, warpMargin); - PlacementState state = new PlacementState(-1, placementBounds); - -// if (config.isFromBottom()) { -// // todo Convert this to a dedicated mode. -// y = (self.getH() + 1) + rty; -// if (!config.isForcePlace()) { -// if (shouldBailForCarvingAnchor(placer, config, context.x, y, context.z)) { -// bail = true; -// } -// } -// } else - PlacementModule behavior = config.getMode().createBehavior(context, state); - - if (yv < 0) { - behavior.setHeight(); - - } else { - state.y = yv; - if (!config.isForcePlace() && !rawStructurePiece) { - if (context.shouldBailForCarvingAnchor(context.x, state.y, context.z)) { - state.bail = true; - } - } - } - - if (yv >= 0 && config.isBottom() && !rawStructurePiece) { - state.y += Math.floorDiv(self.h, 2); - CarvingMode carvingMode = config.getCarvingSupport(); - if (!config.isForcePlace() && !carvingMode.equals(CarvingMode.CARVING_ONLY)) { - if (context.shouldBailForCarvingAnchor(context.x, state.y, context.z)) { - state.bail = true; - } - } - } - - if (yv < 0 - && !config.isForcePlace() - && !config.isFromBottom() - && config.getMode() != ObjectPlaceMode.FLOATING - && !rawStructurePiece - && config.getCarvingSupport().supportsSurface() - && placer.getEngine() != null - && placer.getEngine().getDimension().isBedrock() - && state.y <= 1) { - warnImplausibleBedrockPlacement(placer, config, context.x, state.y, context.z); - return -1; - } - - if (state.bail && !config.isForcePlace()) { - return -1; - } - - // Surface-anchored placements may never roof or bridge a carved hole. Explicit-Y anchors are only - // guarded for SURFACE_ONLY: ANYWHERE covers the inverted upper dimension and CARVING_ONLY covers - // cave anchors, and neither reads the terrain surface this stencil samples. - boolean surfaceAnchored = yv < 0 - ? config.getCarvingSupport().supportsSurface() - : config.getCarvingSupport() == CarvingMode.SURFACE_ONLY; - if (surfaceAnchored - && !config.isForcePlace() - && !config.isFromBottom() - && config.getMode() != ObjectPlaceMode.FLOATING - && !rawStructurePiece - && !config.isUnderwater() - && !config.isOnwater() - && config.isRequireSurfaceSupport() - && IrisSurfaceSupport.isUnsupported(oplacer, self.getLoader(), context.x, context.z, config.getTranslate(), - config.getRotation(), spinx, spiny, spinz, self.getSurfaceSupportOffsets(), - config.getSurfaceSupportBuffer(), config.getSurfaceSupportDepth())) { - return -1; - } - - if (yv < 0 && !config.getMode().equals(ObjectPlaceMode.FLOATING) && !rawStructurePiece) { - if (!config.isForcePlace() && !config.isUnderwater() && !config.isOnwater() && placer.isUnderwater(context.x, context.z)) { - return -1; - } - } - - if (!config.isForcePlace() && !rawStructurePiece && c != null && Math.max(0, self.h + yrand + ty) + 1 >= c.getHeight()) { - return -1; - } - - if (!config.isForcePlace() && !rawStructurePiece && config.isUnderwater() && state.y + rty + ty >= placer.getFluidHeight()) { - return -1; - } - - if (!config.isForcePlace() && !rawStructurePiece && !config.getClamp().canPlace(state.y + rty + ty, state.y - rty + ty)) { - return -1; - } - - if (!rawStructurePiece && nativeStructureVetoes(placer, config, spin, translating, translateOffset, ceilingHang, - yv < 0 && config.getMode() == ObjectPlaceMode.PAINT, warpMargin, context.x, state.y + yrand, context.z)) { - return -1; - } - - boolean paint = yv < 0 && config.getMode() == ObjectPlaceMode.PAINT; - PlacementContext.WorldBounds worldBounds = null; - if (config.isBore() || (!config.isForcePlace() && !rawStructurePiece - && (!config.getAllowedCollisions().isEmpty() || !config.getForbiddenCollisions().isEmpty()))) { - worldBounds = context.resolveWorldBounds(state.bounds, paint, context.x, state.y + yrand, context.z); - } - - if (!config.isForcePlace() && !rawStructurePiece && (!config.getAllowedCollisions().isEmpty() || !config.getForbiddenCollisions().isEmpty())) { - Engine engine = requireDataEngine(rdata, "collision settings"); - for (int i = worldBounds.minX(); i <= worldBounds.maxX(); i++) { - for (int j = worldBounds.minY(); j <= worldBounds.maxY(); j++) { - for (int k = worldBounds.minZ(); k <= worldBounds.maxZ(); k++) { - PlacedObject p = engine.getObjectPlacement(i, j, k); - if (p == null) continue; - IrisObject o = p.getObject(); - if (o == null) continue; - String key = o.getLoadKey(); - if (key != null) { - if (config.getForbiddenCollisions().contains(key) && !config.getAllowedCollisions().contains(key)) { - return -1; - } - } - } - } - } - } - - state.y += yrand; - - if (config.isBore()) { - for (int i = worldBounds.minX(); i <= worldBounds.maxX(); i++) { - for (int j = worldBounds.minY() - config.getBoreExtendMinY(); j <= worldBounds.maxY() + config.getBoreExtendMaxY(); j++) { - for (int k = worldBounds.minZ(); k <= worldBounds.maxZ(); k++) { - placer.set(i, j, k, IrisObject.States.AIR); - } - } - } - } - - int lowest = Integer.MAX_VALUE; - int topLayer = Integer.MIN_VALUE; - int vacuumLowest = Integer.MAX_VALUE; - int vacuumHighest = Integer.MIN_VALUE; - self.readLock.lock(); - - ObjectBlockPass pass = new ObjectBlockPass(context, state, behavior, listener); - ObjectMarkerPlacement markerPlacer = null; - - try { - VectorMap blocks = self.blocks; - VectorMap states = self.states; - // Zero-tile objects are the common case: skip the two Key allocations VectorMap#get needs to prove null. - boolean hasStates = !states.isEmpty(); - - if (config.getMarkers().isNotEmpty() && placer.getEngine() != null) { - markerPlacer = new ObjectMarkerPlacement(config, context); - markerPlacer.loadPossibleMarkers(); - } - - VectorMap.Cursor cursor = blocks.cursor(); - while (cursor.next()) { - IrisBlockVector g = cursor.key(); - PlatformBlockState d; - TileData tile = null; - - try { - d = cursor.value(); - if (hasStates) { - tile = states.get(g); - } - } catch (Throwable e) { - IrisLogging.reportError(e); - IrisLogging.warn("Failed to read block node " + g.getBlockX() + "," + g.getBlockY() + "," + g.getBlockZ() + " in object " + self.getLoadKey() + " (cme)"); - d = IrisObject.States.AIR; - } - - if (d == null) { - IrisLogging.warn("Failed to read block node " + g.getBlockX() + "," + g.getBlockY() + "," + g.getBlockZ() + " in object " + self.getLoadKey() + " (null)"); - d = IrisObject.States.AIR; - } - - if (placer.isDebugSmartBore() && IrisObject.States.VAIR.equals(d)) { - d = IrisObject.States.VAIR_DEBUG; - } - - PlatformBlockState data = d; - IrisBlockVector i = g.clone(); - spin.rotate(i); - if (ceilingHang) { - i.setY(-i.getBlockY()); - } - if (translating) { - i.add(translateOffset); - } - - //todo move this under stilt mode -// if (stilting && IrisObjectShaping.shouldStilt(data)) { -// if (i.getBlockY() < lowest) { -// lowest = i.getBlockY(); -// } -// if (i.getBlockY() > topLayer) { -// topLayer = i.getBlockY(); -// } -// } - - if (preventingDecay && IrisProceduralBlocks.hasProperty(data, "distance") && "false".equals(IrisProceduralBlocks.propertyValue(data, "persistent"))) { - data = data.withProperty("persistent", "true"); - } - - if (hasEdits) { - for (IrisObjectReplace j : config.getEdit()) { - if (rng.chance(j.getChance())) { - for (PlatformBlockState k : j.getFind(rdata)) { - if (j.isExact() ? k.matches(data) : IrisObjectShaping.materialKey(k).equals(IrisObjectShaping.materialKey(data))) { - PlatformBlockState newData = j.getReplace(rng, i.getX() + context.x, i.getY() + state.y, i.getZ() + context.z, rdata); - - if (IrisObjectShaping.materialKey(newData).equals(IrisObjectShaping.materialKey(data)) && !(newData.isCustom() || data.isCustom())) - data = BlockDataMergeSupport.merge(data, newData); - else - data = newData; - - Optional t = j.getReplace().getTile(rng, context.x, state.y, context.z, rdata); - if (t.isPresent()) { - tile = t.get(); - } - } - } - } - } - } - - List matchingMarkers = markerPlacer != null ? markerPlacer.matchMarkers(data) : null; - - data = config.getRotation().rotate(data, spinx, spiny, spinz); - xx = context.x + (int) Math.round(i.getX()); - - int yy = state.y + (int) Math.round(i.getY()); - zz = context.z + (int) Math.round(i.getZ()); - - if (warped) { - xx += surfaceWarp.fitDouble(-warpHalf, warpHalf, i.getX() + context.x, i.getY() + state.y, i.getZ() + context.z); - zz += surfaceWarp.fitDouble(-warpHalf, warpHalf, i.getZ() + context.z, i.getY() + state.y, i.getX() + context.x); - } - - if (yv < 0 && (config.getMode().equals(ObjectPlaceMode.PAINT)) && !B.isVineBlock(data)) { - yy = (int) Math.round(i.getY()) + Math.floorDiv(self.h, 2) + placer.getHighest(xx, zz, self.getLoader(), config.isUnderwater()); - } - - if (config.isMeld() && !rawStructurePiece && !placer.isSolid(xx, yy, zz)) { - continue; - } - - if (waterlogCandidate && IrisProceduralBlocks.hasProperty(data, "waterlogged") && pass.shouldAutoWaterlogBlock(yv, xx, yy, zz)) { - data = data.withProperty("waterlogged", "true"); - } - - if (B.isVineBlock(data)) { - data = attachVineFaces(placer, data, xx, yy, zz); - } - - // Short-circuit order matters for cost only: the mantle read is paid solely - // for vine blocks. Both operands are pure, so the value is unchanged. - boolean wouldReplace = B.isVineBlock(data) && B.isSolid(placer.get(xx, yy, zz)); - String material = IrisObjectShaping.materialKey(data); - boolean air = material.equals("minecraft:air") || material.equals("minecraft:cave_air"); - boolean place = shouldPlaceObjectBlock(rawStructurePiece, air, wouldReplace); - - if (data.isCustom() || place) { - placer.set(xx, yy, zz, data); - if (heightmap != null) { - Position2 pos = new Position2(xx, zz); - Integer currentHeight = heightmap.get(pos); - if (currentHeight == null || currentHeight < yy) { - heightmap.put(pos, yy); - } - } - if (tile != null) { - placer.setTile(xx, yy, zz, tile); - } - if (matchingMarkers != null) { - BlockPosition markerPosition = new BlockPosition(xx, yy, zz); - for (ObjectMarkerPlacement.MarkerPlacement markerPlacement : matchingMarkers) { - markerPlacement.candidates.add(markerPosition); - } - } - if (listener != null) { - listener.accept(new BlockPosition(xx, yy, zz), data); - } - if (vacuuming && yy < vacuumLowest) { - vacuumLowest = yy; - } - if (vacuuming && yy > vacuumHighest) { - vacuumHighest = yy; - } - } - } - - - if (markerPlacer != null) { - markerPlacer.placeMarkers(); - } - - } finally { - self.readLock.unlock(); - } - - - // todo stilt was here - config.getMode().getBehavior().postHeight(); -// if (stilting) { -// // todo stilting -// -// } - - if (vacuuming && vacuumLowest != Integer.MAX_VALUE && placer.getEngine() != null) { - vacuumTerrain(placer, config, context.x, context.z, placementBounds.minX(), placementBounds.maxX(), - placementBounds.minZ(), placementBounds.maxZ(), vacuumLowest, vacuumHighest); - } - - if (heightmap != null) { - RNG rngx = rng.nextParallelRNG(3468854); - - for (Position2 i : heightmap.k()) { - int vx = i.getX(); - int vy = heightmap.get(i); - int vz = i.getZ(); - - if (config.getSnow() > 0) { - int height = rngx.i(0, (int) (config.getSnow() * 7)); - placer.set(vx, vy + 1, vz, IrisObject.States.SNOW_LAYERS[Math.max(Math.min(height, 7), 0)]); - } - } - } - - return state.y; - } - - static boolean shouldPlaceObjectBlock(boolean rawStructurePiece, boolean air, boolean wouldReplace) { - return !wouldReplace && (rawStructurePiece || !air); - } - - private void withRotateTowardsSlope(IrisObjectPlacement config, Engine engine, int x, int z) { - int slopeRotationY = 0; - ProceduralStream heightStream = engine.getComplex().getHeightStream(); - // Whichever side of the rectangle that bounds the object is lowest is the 'direction' of the slope (simply said). - double hNorth = heightStream.get(x, z + ((float) self.d) / 2); - double hEast = heightStream.get(x + ((float) self.w) / 2, z); - double hSouth = heightStream.get(x, z - ((float) self.d) / 2); - double hWest = heightStream.get(x - ((float) self.w) / 2, z); - double min = Math.min(Math.min(hNorth, hEast), Math.min(hSouth, hWest)); - if (mind == hNorth) { - slopeRotationY = 0; - } else if (min == hEast) { - slopeRotationY = 90; - } else if (min == hSouth) { - slopeRotationY = 180; - } else if (min == hWest) { - slopeRotationY = 270; - } - - double newRotation = config.getRotation().getYAxis().getMin() + slopeRotationY; - IrisObjectRotation originalRotation = config.getRotation(); - IrisObjectRotation slopeRotation = new IrisObjectRotation(); - slopeRotation.setXAxis(originalRotation.getXAxis()); - slopeRotation.setZAxis(originalRotation.getZAxis()); - if (newRotation == 0) { - slopeRotation.setYAxis(new IrisAxisRotationClamp(false, false, 0, 0, 90)); - slopeRotation.setEnabled(originalRotation.canRotateX() || originalRotation.canRotateZ()); - } else { - slopeRotation.setYAxis(new IrisAxisRotationClamp(true, false, newRotation, newRotation, 90)); - slopeRotation.setEnabled(true); - } - config = config.toPlacement(config.getPlace().toArray(new String[0])); - config.setRotation(slopeRotation); - } - - private static Engine requireSlopeEngine(IObjectPlacer placer) { - return requirePlacementEngine(placer, "slope settings"); - } - - private static Engine requirePlacementEngine(IObjectPlacer placer, String feature) { - Engine engine = placer.getEngine(); - if (engine == null) { - throw new IllegalStateException("Object placement requires an active Iris engine for " + feature + "."); - } - return engine; - } - - private static Engine requireDataEngine(IrisData data, String feature) { - Engine engine = data.getEngine(); - if (engine == null) { - throw new IllegalStateException("Object placement requires active Iris data for " + feature + "."); - } - return engine; - } - - /** - * Objects may never intersect a native structure piece. The rect query is the fast path: no native structures - * near this placement means no per block work at all. Only when the placement envelope meets a piece does the - * precise pass run, and the first solid block inside a piece rejects the whole object before any write. - */ - private boolean nativeStructureVetoes(IObjectPlacer placer, IrisObjectPlacement config, ObjectSpinKernel spin, - boolean translating, IrisBlockVector translateOffset, boolean ceilingHang, - boolean paint, int warpMargin, int x, int y, int z) { - Engine engine = placer.getEngine(); - if (engine == null) { - return false; - } - - int margin = (Math.max(self.getW(), Math.max(self.getH(), self.getD())) / 2) + 1 + warpMargin; - if (translating) { - margin += Math.max(Math.abs(translateOffset.getBlockX()), - Math.max(Math.abs(translateOffset.getBlockY()), Math.abs(translateOffset.getBlockZ()))); - } - - KList volumes = engine.getNativeStructureVolumes(x - margin, z - margin, x + margin, z + margin); - if (volumes == null || volumes.isEmpty()) { - return false; - } - - int worldY = y + engine.getMinHeight(); - int envelopeMinY = paint ? Integer.MIN_VALUE : worldY - margin; - int envelopeMaxY = paint ? Integer.MAX_VALUE : worldY + margin; - boolean envelopeMeetsPiece = false; - for (NativeStructureVolume volume : volumes) { - if (volume.intersects(x - margin, envelopeMinY, z - margin, x + margin, envelopeMaxY, z + margin)) { - envelopeMeetsPiece = true; - break; - } - } - - if (!envelopeMeetsPiece) { - return false; - } - - self.readLock.lock(); - try { - VectorMap.Cursor cursor = self.blocks.cursor(); - while (cursor.next()) { - PlatformBlockState state = cursor.value(); - if (state == null || isAirBlock(state)) { - continue; - } - - IrisBlockVector i = cursor.key().clone(); - spin.rotate(i); - if (ceilingHang) { - i.setY(-i.getBlockY()); - } - if (translating) { - i.add(translateOffset); - } - - int xx = x + (int) Math.round(i.getX()); - int zz = z + (int) Math.round(i.getZ()); - int yy = paint - ? (int) Math.round(i.getY()) + Math.floorDiv(self.h, 2) - + placer.getHighest(xx, zz, self.getLoader(), config.isUnderwater()) - : y + (int) Math.round(i.getY()); - int worldBlockY = yy + engine.getMinHeight(); - - for (NativeStructureVolume volume : volumes) { - if (volume.containsWithin(xx, worldBlockY, zz, warpMargin)) { - return true; - } - } - } - } finally { - self.readLock.unlock(); - } - - return false; - } - - private static boolean isAirBlock(PlatformBlockState state) { - String material = IrisObjectShaping.materialKey(state); - return material.equals("minecraft:air") || material.equals("minecraft:cave_air"); - } - - private void warnImplausibleBedrockPlacement(IObjectPlacer placer, IrisObjectPlacement config, int x, int y, int z) { - String key = self.getLoadKey(); - String fingerprint = (key == null ? "" : key) + "|" + config.getMode(); - long now = System.currentTimeMillis(); - Long last = IMPLAUSIBLE_BEDROCK_WARNS.get(fingerprint); - if (last != null && now - last < IMPLAUSIBLE_BEDROCK_WARN_THROTTLE_MS) { - return; - } - IMPLAUSIBLE_BEDROCK_WARNS.put(fingerprint, now); - IrisLogging.warn("Implausible object placement rejected: " - + (key == null ? "" : key) - + " resolved anchorY=" + y + " at (" + x + "," + z + ") mode=" + config.getMode() - + " carving=" + config.getCarvingSupport() - + ". Surface-anchored placement should never land on the bedrock row. " - + "Height sampling returned a bogus value — not configured for floor placement " - + "(forcePlace=false, fromBottom=false, mode!=FLOATING). Skipping to protect bedrock."); - } - - private void vacuumTerrain(IObjectPlacer placer, IrisObjectPlacement config, int centerX, int centerZ, int lowX, int highX, int lowZ, int highZ, int baseY, int topY) { - ObjectPlaceMode mode = config.getMode(); - IrisVacuumSettings settings = config.getVacuumSettings(); - int radius = IrisObjectVacuum.resolveRadius(mode, settings); - int step = IrisObjectVacuum.resolveStep(mode); - double falloff = IrisObjectVacuum.resolveFalloff(settings); - int jitter = settings != null ? Math.max(0, settings.getOrganicJitter()) : 4; - boolean organicEdge = mode == ObjectPlaceMode.VACUUM_ORGANIC; - boolean wavyEdge = mode == ObjectPlaceMode.VACUUM_WAVY; - double waveAmplitude = IrisObjectVacuum.resolveWaveAmplitude(settings); - double waveScale = IrisObjectVacuum.resolveWaveScale(settings); - SimplexNoise waveNoise = (wavyEdge && waveAmplitude > 0) ? new SimplexNoise(VACUUM_WAVE_SEED) : null; - int meetY = baseY - 1; - - IrisComplex complex = placer.getEngine().getComplex(); - int worldMin = placer.getEngine().getMinHeight(); - int worldMax = worldMin + placer.getEngine().getHeight() - 1; - - for (int dx = lowX - radius; dx <= highX + radius; dx += step) { - for (int dz = lowZ - radius; dz <= highZ + radius; dz += step) { - int cx = centerX + dx; - int cz = centerZ + dz; - double effRadius = radius; - if (organicEdge && jitter > 0) { - long h = ((long) cx * 341873128712L) ^ ((long) cz * 132897987541L); - double n = ((Math.abs(h) % 1000) / 1000.0) - 0.5; - effRadius = Math.max(1.0, radius + (n * 2.0 * jitter)); - } - int origY = placer.getHighest(cx, cz, self.getLoader(), true); - int targetY = IrisObjectVacuum.columnTargetY(dx, dz, lowX, highX, lowZ, highZ, effRadius, falloff, origY, meetY); - if (waveNoise != null) { - int outX = IrisObjectVacuum.outset(dx, lowX, highX); - int outZ = IrisObjectVacuum.outset(dz, lowZ, highZ); - double waveDistance = Math.sqrt((double) (outX * outX) + (double) (outZ * outZ)); - double sample = waveNoise.noiseSigned(cx * waveScale, cz * waveScale); - targetY += IrisObjectVacuum.waveOffset(waveDistance, effRadius, sample, waveAmplitude); - } - if (targetY == origY) { - continue; - } - targetY = Math.max(worldMin + 1, Math.min(worldMax, targetY)); - if (targetY > origY) { - PlatformBlockState fill = complex != null ? complex.getRockStream().get(cx, cz) : null; - if (B.isAir(fill)) { - fill = IrisObject.States.STONE; - } - for (int yy = origY + 1; yy <= targetY; yy++) { - placer.set(cx, yy, cz, fill); - } - } else if (targetY < origY) { - boolean inside = IrisObjectVacuum.outset(dx, lowX, highX) == 0 && IrisObjectVacuum.outset(dz, lowZ, highZ) == 0; - int carveFloor = IrisObjectVacuum.carveFloorY(targetY, topY, inside); - for (int yy = origY; yy >= carveFloor; yy--) { - placer.set(cx, yy, cz, IrisObject.States.AIR); - } - } - } - } + int place(int x, int yv, int z, IObjectPlacer placer, IrisObjectPlacement config, RNG rng, + BiConsumer listener, CarveResult cave, IrisData data) { + PlacementContext context = new PlacementContext(config, data, placer, cave, rng, self, x, z, yv, listener); + return PlacementLifecycles.forPlacer(placer).get(config.getMode()).execute(context).heightOrRejected(); } } diff --git a/core/src/main/java/art/arcane/iris/engine/object/ObjectBlockPass.java b/core/src/main/java/art/arcane/iris/engine/object/ObjectBlockPass.java index bdabd3def..5b313f19c 100644 --- a/core/src/main/java/art/arcane/iris/engine/object/ObjectBlockPass.java +++ b/core/src/main/java/art/arcane/iris/engine/object/ObjectBlockPass.java @@ -7,84 +7,83 @@ import art.arcane.iris.util.common.data.B; import art.arcane.iris.util.common.data.VectorMap; import art.arcane.iris.util.common.math.IrisBlockVector; import art.arcane.iris.util.project.noise.CNG; -import art.arcane.volmlib.util.collection.KMap; import art.arcane.volmlib.util.math.BlockPosition; -import art.arcane.volmlib.util.math.Position2; import java.util.List; import java.util.Optional; import java.util.function.BiConsumer; -class ObjectBlockPass { +final class ObjectBlockPass { - private KMap heightmap; private List matchingMarkers; - private BiConsumer listener; + private final BiConsumer listener; - private PlacementContext context; - private PlacementState state; - private VectorMap blocks; - private VectorMap states; - private ObjectMarkerPlacement markerPlacer; - private PlacementModule behavior; + private final PlacementContext context; + private final PlacementState state; + private final VectorMap blocks; + private final VectorMap states; + private final ObjectMarkerPlacement markerPlacer; + private final PlacementLifecycle lifecycle; - ObjectBlockPass( - PlacementContext context, - PlacementState state, - PlacementModule behavior, - BiConsumer listener - ) { + ObjectBlockPass( + PlacementContext context, + PlacementState state, + PlacementLifecycle lifecycle, + BiConsumer listener + ) { this.context = context; this.state = state; - this.behavior = behavior; + this.lifecycle = lifecycle; this.listener = listener; this.blocks = context.self.blocks; this.states = context.self.states; - this.heightmap = context.config.getSnow() > 0 ? new KMap<>() : null; - if (context.config.getMarkers().isNotEmpty() && context.placer.getEngine() != null) { - markerPlacer = new ObjectMarkerPlacement(context.config, context); + if (state.config.getMarkers().isNotEmpty() && state.placer.getEngine() != null) { + markerPlacer = new ObjectMarkerPlacement(context, state); markerPlacer.loadPossibleMarkers(); + } else { + markerPlacer = null; } } void process() { VectorMap.Cursor cursor = blocks.cursor(); - IrisObjectTranslate translate = context.config.getTranslate(); - CNG surfaceWarp = !context.config.getWarp().isFlat() ? context.config.getSurfaceWarp(context.rng, context.self.getLoader()) : null; + IrisObjectTranslate translate = state.config.getTranslate(); + CNG surfaceWarp = !state.config.getWarp().isFlat() ? state.config.getSurfaceWarp(context.rng, context.self.getLoader()) : null; + boolean preventingDecay = state.placer.isPreventingDecay(); + boolean waterlogCandidate = state.config.isWaterloggable() || state.config.isUnderwater(); + boolean hasStates = !states.isEmpty(); int xx, zz; - double warpHalf = context.config.getWarp().isFlat() ? context.config.getWarp().getMultiplier() / 2D : 0D; + double warpHalf = !state.config.getWarp().isFlat() ? state.config.getWarp().getMultiplier() / 2D : 0D; while (cursor.next()) { - var read = readStateFrom(cursor); + var read = readStateFrom(cursor, hasStates); PlatformBlockState data = read.getA(); TileData tile = read.getB(); IrisBlockVector vector = cursor.key().clone(); - context.spin.rotate(vector); - behavior.onBlock(blocks, states, data, tile, vector); - - if (translate.canTranslate()) { - vector.add(translateOffset); + state.spin.rotate(vector); + PlacementBlock block = new PlacementBlock(data, tile, vector); + lifecycle.run(PlacementStage.TRANSFORM_BLOCK, context, state, block); + if (state.isRejected()) { + return; } - if (context.placer.isPreventingDecay() && IrisProceduralBlocks.hasProperty(data, "distance") && "false".equals(IrisProceduralBlocks.propertyValue(data, "persistent"))) { + if (translate.canTranslate()) { + vector.add(state.translateOffset); + } + + lifecycle.run(PlacementStage.COLLECT_BLOCK, context, state, block); + if (state.isRejected()) { + return; + } + if (preventingDecay && IrisProceduralBlocks.hasProperty(data, "distance") && "false".equals(IrisProceduralBlocks.propertyValue(data, "persistent"))) { data = data.withProperty("persistent", "true"); } - //todo move this under stilt mode -// if (stilting && IrisObjectShaping.shouldStilt(data)) { -// if (i.getBlockY() < lowest) { -// lowest = i.getBlockY(); -// } -// if (i.getBlockY() > topLayer) { -// topLayer = i.getBlockY(); -// } -// } - - if (!context.config.getEdit().isEmpty()) { + if (!state.config.getEdit().isEmpty()) { var result = applyEdits(vector, data, tile); data = result.data(); tile = result.tile(); @@ -92,39 +91,37 @@ class ObjectBlockPass { matchingMarkers = markerPlacer != null ? markerPlacer.matchMarkers(data) : null; - data = context.spin.rotate(data); + data = state.spin.rotate(data); xx = context.x + (int) Math.round(vector.getX()); int yy = state.y + (int) Math.round(vector.getY()); zz = context.z + (int) Math.round(vector.getZ()); - if (!context.config.getWarp().isFlat()) { + if (!state.config.getWarp().isFlat()) { xx += surfaceWarp.fitDouble(-warpHalf, warpHalf, vector.getX() + context.x, vector.getY() + state.y, vector.getZ() + context.z); zz += surfaceWarp.fitDouble(-warpHalf, warpHalf, vector.getZ() + context.z, vector.getY() + state.y, vector.getX() + context.x); } if (context.yv < 0 && (is(ObjectPlaceMode.PAINT)) && !B.isVineBlock(data)) { - yy = (int) Math.round(vector.getY()) + Math.floorDiv(context.self.h, 2) + context.placer.getHighest(xx, zz, context.self.getLoader(), context.config.isUnderwater()); + yy = (int) Math.round(vector.getY()) + Math.floorDiv(context.self.h, 2) + state.placer.getHighest(xx, zz, context.self.getLoader(), state.config.isUnderwater()); } - if (context.config.isMeld() && !is(ObjectPlaceMode.STRUCTURE_PIECE) && !context.placer.isSolid(xx, yy, zz)) { + if (state.config.isMeld() && !is(ObjectPlaceMode.STRUCTURE_PIECE) && !state.placer.isSolid(xx, yy, zz)) { continue; } - if ((context.config.isWaterloggable() || context.config.isUnderwater()) && IrisProceduralBlocks.hasProperty(data, "waterlogged") && shouldAutoWaterlogBlock(context.yv, xx, yy, zz)) { + if (waterlogCandidate && IrisProceduralBlocks.hasProperty(data, "waterlogged") && shouldAutoWaterlogBlock(context, state, xx, yy, zz)) { data = data.withProperty("waterlogged", "true"); } if (B.isVineBlock(data)) { - data = attachVineFaces(context.placer, data, xx, yy, zz); + data = attachVineFaces(state.placer, data, xx, yy, zz); } - handleCustomData(data, tile, xx, yy, zz); - - if (vacuuming && yy < vacuumLowest) { - vacuumLowest = yy; - } - if (vacuuming && yy > vacuumHighest) { - vacuumHighest = yy; + if (handleCustomData(data, tile, xx, yy, zz)) { + lifecycle.run(PlacementStage.BLOCK_WRITTEN, context, state, new PlacementBlockWrite(xx, yy, zz, data)); + if (state.isRejected()) { + return; + } } } @@ -136,31 +133,24 @@ class ObjectBlockPass { } private boolean is(ObjectPlaceMode mode) { - return context.config.getMode() == mode; + return state.config.getMode() == mode; } static boolean shouldPlaceObjectBlock(boolean rawStructurePiece, boolean air, boolean wouldReplace) { return !wouldReplace && (rawStructurePiece || !air); } - private void handleCustomData(PlatformBlockState data, TileData tile, int xx, int yy, int zz) { + private boolean handleCustomData(PlatformBlockState data, TileData tile, int xx, int yy, int zz) { // Short-circuit order matters for cost only: the mantle read is paid solely // for vine blocks. Both operands are pure, so the value is unchanged. - boolean wouldReplace = B.isVineBlock(data) && B.isSolid(context.placer.get(xx, yy, zz)); + boolean wouldReplace = B.isVineBlock(data) && B.isSolid(state.placer.get(xx, yy, zz)); String material = IrisObjectShaping.materialKey(data); boolean air = material.equals("minecraft:air") || material.equals("minecraft:cave_air"); boolean place = shouldPlaceObjectBlock(is(ObjectPlaceMode.STRUCTURE_PIECE), air, wouldReplace); if (data.isCustom() || place) { - context.placer.set(xx, yy, zz, data); - if (heightmap != null) { - Position2 pos = new Position2(xx, zz); - Integer currentHeight = heightmap.get(pos); - if (currentHeight == null || currentHeight < yy) { - heightmap.put(pos, yy); - } - } + state.placer.set(xx, yy, zz, data); if (tile != null) { - context.placer.setTile(xx, yy, zz, tile); + state.placer.setTile(xx, yy, zz, tile); } if (matchingMarkers != null) { BlockPosition markerPosition = new BlockPosition(xx, yy, zz); @@ -171,11 +161,13 @@ class ObjectBlockPass { if (listener != null) { listener.accept(new BlockPosition(xx, yy, zz), data); } + return true; } + return false; } private EditResult applyEdits(IrisBlockVector vector, PlatformBlockState data, TileData tile) { - for (IrisObjectReplace j : context.config.getEdit()) { + for (IrisObjectReplace j : state.config.getEdit()) { if (context.rng.chance(j.getChance())) { for (PlatformBlockState k : j.getFind(context.rdata)) { if (j.isExact() ? k.matches(data) : IrisObjectShaping.materialKey(k).equals(IrisObjectShaping.materialKey(data))) { @@ -194,19 +186,19 @@ class ObjectBlockPass { } } } - new EditResult(data, tile); + return new EditResult(data, tile); } - public boolean shouldAutoWaterlogBlock(int yv, int x, int y, int z) { - if (!(context.config.isWaterloggable() || context.config.isUnderwater())) { + static boolean shouldAutoWaterlogBlock(PlacementContext context, PlacementState state, int x, int y, int z) { + if (!(state.config.isWaterloggable() || state.config.isUnderwater())) { return false; } - if (yv >= 0 && context.config.getCarvingSupport().equals(CarvingMode.CARVING_ONLY)) { + if (context.yv >= 0 && state.config.getCarvingSupport().equals(CarvingMode.CARVING_ONLY)) { return false; } - PlatformBlockState existing = context.placer.get(x, y, z); + PlatformBlockState existing = state.placer.get(x, y, z); if (existing == null) { return false; } @@ -214,7 +206,7 @@ class ObjectBlockPass { return B.isWater(existing) || B.isWaterLogged(existing); } - private static PlatformBlockState attachVineFaces(IObjectPlacer placer, PlatformBlockState data, int x, int y, int z) { + static PlatformBlockState attachVineFaces(IObjectPlacer placer, PlatformBlockState data, int x, int y, int z) { PlatformBlockState result = data; for (String face : IrisProceduralBlocks.FACE_PROPERTIES) { if (!IrisProceduralBlocks.hasProperty(data, face)) { @@ -230,11 +222,10 @@ class ObjectBlockPass { } - private Pair readStateFrom(VectorMap.Cursor cursor) { + private Pair readStateFrom(VectorMap.Cursor cursor, boolean hasStates) { PlatformBlockState block; TileData tile = null; IrisBlockVector vector = cursor.key(); - boolean hasStates = !states.isEmpty(); try { block = cursor.value(); if (hasStates) { @@ -250,7 +241,7 @@ class ObjectBlockPass { IrisLogging.warn("Failed to read block node " + vector.getBlockX() + "," + vector.getBlockY() + "," + vector.getBlockZ() + " in object " + context.self.getLoadKey() + " (null)"); block = IrisObject.States.AIR; } - if (context.placer.isDebugSmartBore() && IrisObject.States.VAIR.equals(block)) { + if (state.placer.isDebugSmartBore() && IrisObject.States.VAIR.equals(block)) { block = IrisObject.States.VAIR_DEBUG; } return new Pair<>(block, tile); diff --git a/core/src/main/java/art/arcane/iris/engine/object/ObjectMarkerPlacement.java b/core/src/main/java/art/arcane/iris/engine/object/ObjectMarkerPlacement.java index 792509bb7..63ad6aa7d 100644 --- a/core/src/main/java/art/arcane/iris/engine/object/ObjectMarkerPlacement.java +++ b/core/src/main/java/art/arcane/iris/engine/object/ObjectMarkerPlacement.java @@ -14,11 +14,13 @@ class ObjectMarkerPlacement { private IrisObjectPlacement config; private PlacementContext context; + private final IObjectPlacer placer; private RNG markerRng; List placements; - public ObjectMarkerPlacement(IrisObjectPlacement config, PlacementContext context) { - this.config = config; + public ObjectMarkerPlacement(PlacementContext context, PlacementState state) { + this.config = state.config; + this.placer = state.placer; this.context = context; this.markerRng = context.rng.nextParallelRNG(((((long) context.x) << 32) | (context.z & 0xFFFFFFFFL)) * 31L + context.yv); this.placements = new ArrayList<>(); @@ -59,10 +61,10 @@ class ObjectMarkerPlacement { break; } - boolean firstAboveAir = B.isAir(context.placer.get(position.getX(), position.getY() + 1, position.getZ())); - boolean secondAboveAir = B.isAir(context.placer.get(position.getX(), position.getY() + 2, position.getZ())); + boolean firstAboveAir = B.isAir(placer.get(position.getX(), position.getY() + 1, position.getZ())); + boolean secondAboveAir = B.isAir(placer.get(position.getX(), position.getY() + 2, position.getZ())); if (!markerPlacement.marker.isEmptyAbove() || (firstAboveAir && secondAboveAir)) { - context.placer.setData(position.getX(), position.getY(), position.getZ(), + placer.setData(position.getX(), position.getY(), position.getZ(), new MatterMarker(markerPlacement.config.getMarker())); max--; } @@ -99,4 +101,3 @@ class ObjectMarkerPlacement { } } - diff --git a/core/src/main/java/art/arcane/iris/engine/object/ObjectModuleCeilingHang.java b/core/src/main/java/art/arcane/iris/engine/object/ObjectModuleCeilingHang.java index c2a6086e0..90806dd6d 100644 --- a/core/src/main/java/art/arcane/iris/engine/object/ObjectModuleCeilingHang.java +++ b/core/src/main/java/art/arcane/iris/engine/object/ObjectModuleCeilingHang.java @@ -1,13 +1,11 @@ package art.arcane.iris.engine.object; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.VectorMap; -import art.arcane.iris.util.common.math.IrisBlockVector; - -public class ObjectModuleCeilingHang extends PlacementModule { +public final class ObjectModuleCeilingHang implements PlacementModule { + static final PlacementLifecycleDependency FLIP = new PlacementLifecycleDependency("ceiling.flip"); @Override - public void onBlock(VectorMap blocks, VectorMap states, PlatformBlockState block, TileData tile, IrisBlockVector vector) { - vector.setY(-vector.getBlockY()); + public void install(PlacementLifecycleBuilder lifecycle) { + lifecycle.add(FLIP, PlacementStage.TRANSFORM_BLOCK, + (context, state, block) -> block.vector().setY(-block.vector().getBlockY())); } } diff --git a/core/src/main/java/art/arcane/iris/engine/object/ObjectPlaceMode.java b/core/src/main/java/art/arcane/iris/engine/object/ObjectPlaceMode.java index c2aea7880..de22cbfce 100644 --- a/core/src/main/java/art/arcane/iris/engine/object/ObjectPlaceMode.java +++ b/core/src/main/java/art/arcane/iris/engine/object/ObjectPlaceMode.java @@ -73,27 +73,27 @@ public enum ObjectPlaceMode { @Desc("Hangs the object upside-down from a cave ceiling. The object is flipped vertically (its tip points down like a stalactite) and its top is anchored to the ceiling, while an organic, noise-varied stilt grows up into the ceiling so it never floats below the roof. Use inside caves; tune with stilt-settings (organicMaxScan, organicJitter, organicScratch).") - CEILING_HANG, + CEILING_HANG(() -> new PlacementModuleStilt(PlacementModuleStilt.Mode.CEILING, false)), @Desc("Anchors the object at the terrain surface (plus translate.y) like CENTER_HEIGHT, then bends the surrounding terrain to be flush with the object's base. Columns inside the object footprint are raised (or lowered) to meet the base, and the deformation falls off parabolically out to a radius so the terrain smoothly blends back to its natural height. Use this to seat a floating/translated object on the ground without a flat stilt disc, e.g. a cube translated up 10 on a mountain pulls the terrain up to meet it. Tune with vacuum-settings (radius, falloff).") - VACUUM, + VACUUM(PlacementModuleCenterHeight::new), @Desc("VACUUM with a larger radius and finer per-column sampling for the smoothest terrain blend. More expensive.") - VACUUM_HIGH, + VACUUM_HIGH(PlacementModuleCenterHeight::new), @Desc("VACUUM with a smaller radius and coarser sampling for performance. Use when seating many objects.") - VACUUM_FAST, + VACUUM_FAST(PlacementModuleCenterHeight::new), @Desc("VACUUM whose falloff radius is perturbed by noise per column, so the terrain meets the object with an irregular organic edge rather than a clean parabolic bowl.") - VACUUM_ORGANIC, + VACUUM_ORGANIC(PlacementModuleCenterHeight::new), @Desc("VACUUM whose terrain bend is bent by smooth coherent simplex noise so the surface meets the object with a gently rolling, wavy slope instead of the ragged white-noise edge of VACUUM_ORGANIC or a clean parabolic bowl. The object itself still seats flush; the waves fade to zero under the object and at the outer rim, peaking across the mid-slope. Tune with vacuum-settings (waveAmplitude, waveScale).") - VACUUM_WAVY, + VACUUM_WAVY(PlacementModuleCenterHeight::new), @Desc("Samples the height of the terrain at every x,z position of your object and pushes it down to the surface. It's pretty much like a melt function over the terrain.") @@ -105,7 +105,8 @@ public enum ObjectPlaceMode { @Desc("Raw stamp at the caller-supplied (x, y, z). No terrain sampling, no stilting, no Y recomputation, no underwater or carving anchor guards. Used internally to route native Minecraft structure pieces (villages etc.) through the Iris object placer.") - STRUCTURE_PIECE; + STRUCTURE_PIECE(() -> lifecycle -> PlacementModuleAnchor.install(lifecycle, + (context, state, ignored) -> state.y = context.yv)); private final Supplier factory; @@ -114,8 +115,34 @@ public enum ObjectPlaceMode { this.factory = factory; } - PlacementModule createBehavior(PlacementContext context, PlacementState state) { - return factory.get().load(context, state); + PlacementLifecycle createLifecycle() { + PlacementLifecycleBuilder lifecycle = new PlacementLifecycleBuilder(); + install(lifecycle); + return lifecycle.build(); + } + + void install(PlacementLifecycleBuilder lifecycle) { + new PlacementModulePreparation().install(lifecycle); + new PlacementModuleSlope().install(lifecycle); + factory.get().install(lifecycle); + new PlacementModuleAnchor().install(lifecycle); + new PlacementModuleSurfaceSupport().install(lifecycle); + new PlacementModuleLimits().install(lifecycle); + new PlacementModuleNativeStructureProtection().install(lifecycle); + new PlacementModuleBounds().install(lifecycle); + new PlacementModuleCollision().install(lifecycle); + new PlacementModuleBore().install(lifecycle); + new PlacementModuleBlocks().install(lifecycle); + PlacementLifecycleDependency finish = switch (this) { + case STILT, FAST_STILT, MIN_STILT, FAST_MIN_STILT, CENTER_STILT, ERODE_STILT, ORGANIC_STILT, CEILING_HANG -> + PlacementModuleStilt.FILL; + case VACUUM, VACUUM_HIGH, VACUUM_FAST, VACUUM_ORGANIC, VACUUM_WAVY -> { + new PlacementModuleVacuum().install(lifecycle); + yield PlacementModuleVacuum.FINISH; + } + default -> PlacementModuleBlocks.COMPLETE; + }; + new PlacementModuleSnow(finish).install(lifecycle); } diff --git a/core/src/main/java/art/arcane/iris/engine/object/PlacementBlock.java b/core/src/main/java/art/arcane/iris/engine/object/PlacementBlock.java new file mode 100644 index 000000000..2c06c6e98 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/object/PlacementBlock.java @@ -0,0 +1,8 @@ +package art.arcane.iris.engine.object; + +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.math.IrisBlockVector; + +/** Source data and a placement-owned vector; changing the vector does not change the cached object. */ +public record PlacementBlock(PlatformBlockState data, TileData tile, IrisBlockVector vector) { +} diff --git a/core/src/main/java/art/arcane/iris/engine/object/PlacementBlockWrite.java b/core/src/main/java/art/arcane/iris/engine/object/PlacementBlockWrite.java new file mode 100644 index 000000000..dad2ae790 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/object/PlacementBlockWrite.java @@ -0,0 +1,6 @@ +package art.arcane.iris.engine.object; + +import art.arcane.iris.spi.PlatformBlockState; + +/** A completed object write, after its tile data and listener have been handled. */ +public record PlacementBlockWrite(int x, int y, int z, PlatformBlockState data) {} diff --git a/core/src/main/java/art/arcane/iris/engine/object/PlacementContext.java b/core/src/main/java/art/arcane/iris/engine/object/PlacementContext.java index 8bff42d9b..cc9fd28ab 100644 --- a/core/src/main/java/art/arcane/iris/engine/object/PlacementContext.java +++ b/core/src/main/java/art/arcane/iris/engine/object/PlacementContext.java @@ -1,136 +1,43 @@ package art.arcane.iris.engine.object; - import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.util.common.math.IrisBlockVector; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.volmlib.util.math.BlockPosition; import art.arcane.volmlib.util.math.RNG; +import lombok.Getter; -final class PlacementContext { - public record TransformedBounds(int minX, int maxX, int minY, int maxY, int minZ, int maxZ) { - } +import java.util.Objects; +import java.util.function.BiConsumer; - public record WorldBounds(int minX, int maxX, int minY, int maxY, int minZ, int maxZ) { - } +/** Caller inputs for one placement. Modules keep derived values in PlacementState. */ +@Getter +public final class PlacementContext { + public record TransformedBounds(int minX, int maxX, int minY, int maxY, int minZ, int maxZ) {} + public record WorldBounds(int minX, int maxX, int minY, int maxY, int minZ, int maxZ) {} - IrisObjectPlacement config; + final IrisObjectPlacement config; final IrisData rdata; final IObjectPlacer placer; final CarveResult caveResult; final RNG rng; - ObjectSpinKernel spin; - IrisObject self; - int x; - int z; - int rty; - int yv; + final IrisObject self; + final int x; + final int z; + final int yv; + final BiConsumer listener; - public PlacementContext( - IrisObjectPlacement config, - IrisData rdata, - IObjectPlacer placer, - CarveResult caveResult, - RNG rng, - ObjectSpinKernel spin, - IrisObject self, - int x, - int z, - int yv, - int rty - ) { - this.config = config; - this.rdata = rdata; - this.placer = placer; + public PlacementContext(IrisObjectPlacement config, IrisData rdata, IObjectPlacer placer, + CarveResult caveResult, RNG rng, IrisObject self, int x, int z, int yv, + BiConsumer listener) { + this.placer = Objects.requireNonNull(placer, "Object placer is required."); + 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.self = Objects.requireNonNull(self, "Object is required."); this.caveResult = caveResult; - this.rng = rng; - this.spin = spin; - this.self = self; this.x = x; this.z = z; this.yv = yv; - this.rty = rty; - } - - public boolean shouldBailForCarvingAnchor(int x, int y, int z) { - CarvingMode carvingMode = config.getCarvingSupport(); - return switch (carvingMode) { - case SURFACE_ONLY -> placer.isCarved(x, y, z); - case CARVING_ONLY -> !isCarvedCaveAnchor(x, y, z); - case ANYWHERE -> false; - }; - } - - public boolean isCarvedCaveAnchor(int x, int y, int z) { - return placer.isCarved(x, y, z) - || placer.isCarved(x, y - 1, z) - || placer.isCarved(x, y - 2, z) - || placer.isCarved(x, y - 3, z); - } - - public TransformedBounds transformedBounds(ObjectSpinKernel spin, boolean translating, IrisBlockVector translateOffset, - boolean ceilingHang, int margin) { - int sourceMinX = -self.getCenter().getBlockX(); - int sourceMaxX = self.getW() - self.getCenter().getBlockX() - 1; - int sourceMinY = -self.getCenter().getBlockY(); - int sourceMaxY = self.getH() - self.getCenter().getBlockY() - 1; - int sourceMinZ = -self.getCenter().getBlockZ(); - int sourceMaxZ = self.getD() - self.getCenter().getBlockZ() - 1; - int minX = Integer.MAX_VALUE; - int maxX = Integer.MIN_VALUE; - int minY = Integer.MAX_VALUE; - int maxY = Integer.MIN_VALUE; - int minZ = Integer.MAX_VALUE; - int maxZ = Integer.MIN_VALUE; - - for (int xCorner = 0; xCorner < 2; xCorner++) { - int sourceX = xCorner == 0 ? sourceMinX : sourceMaxX; - for (int yCorner = 0; yCorner < 2; yCorner++) { - int sourceY = yCorner == 0 ? sourceMinY : sourceMaxY; - for (int zCorner = 0; zCorner < 2; zCorner++) { - int sourceZ = zCorner == 0 ? sourceMinZ : sourceMaxZ; - IrisBlockVector corner = new IrisBlockVector(sourceX, sourceY, sourceZ); - spin.rotate(corner); - if (ceilingHang) { - corner.setY(-corner.getBlockY()); - } - if (translating) { - corner.add(translateOffset); - } - int transformedX = (int) Math.round(corner.getX()); - int transformedY = (int) Math.round(corner.getY()); - int transformedZ = (int) Math.round(corner.getZ()); - minX = Math.min(minX, transformedX); - maxX = Math.max(maxX, transformedX); - minY = Math.min(minY, transformedY); - maxY = Math.max(maxY, transformedY); - minZ = Math.min(minZ, transformedZ); - maxZ = Math.max(maxZ, transformedZ); - } - } - } - - return new TransformedBounds(minX - margin, maxX + margin, minY, maxY, minZ - margin, maxZ + margin); - } - - WorldBounds resolveWorldBounds(TransformedBounds bounds, boolean paint, int x, int y, int z) { - int minX = x + bounds.minX(); - int maxX = x + bounds.maxX(); - int minZ = z + bounds.minZ(); - int maxZ = z + bounds.maxZ(); - if (!paint) { - return new WorldBounds(minX, maxX, y + bounds.minY(), y + bounds.maxY(), minZ, maxZ); - } - - int minimumSurface = Integer.MAX_VALUE; - int maximumSurface = Integer.MIN_VALUE; - for (int worldX = minX; worldX <= maxX; worldX++) { - for (int worldZ = minZ; worldZ <= maxZ; worldZ++) { - int surface = placer.getHighest(worldX, worldZ, self.getLoader(), config.isUnderwater()); - minimumSurface = Math.min(minimumSurface, surface); - maximumSurface = Math.max(maximumSurface, surface); - } - } - int paintOffset = Math.floorDiv(self.h, 2); - return new WorldBounds(minX, maxX, minimumSurface + bounds.minY() + paintOffset, - maximumSurface + bounds.maxY() + paintOffset, minZ, maxZ); + this.listener = listener; } } diff --git a/core/src/main/java/art/arcane/iris/engine/object/PlacementFunction.java b/core/src/main/java/art/arcane/iris/engine/object/PlacementFunction.java index a7d30a76a..39d8a0d22 100644 --- a/core/src/main/java/art/arcane/iris/engine/object/PlacementFunction.java +++ b/core/src/main/java/art/arcane/iris/engine/object/PlacementFunction.java @@ -1,6 +1,6 @@ package art.arcane.iris.engine.object; @FunctionalInterface - interface PlacementFunction { - void execute(C context); - } +public interface PlacementFunction { + void execute(PlacementContext context, PlacementState state, C input); +} diff --git a/core/src/main/java/art/arcane/iris/engine/object/PlacementLifecycle.java b/core/src/main/java/art/arcane/iris/engine/object/PlacementLifecycle.java new file mode 100644 index 000000000..ca0d52766 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/object/PlacementLifecycle.java @@ -0,0 +1,35 @@ +package art.arcane.iris.engine.object; + +import java.util.List; + +/** Immutable plan. Placement performs no registration, graph traversal, or sorting. */ +public final class PlacementLifecycle { + private final List>> stages; + + PlacementLifecycle(List> ordered) { + stages = PlacementStage.ALL.stream() + .map(stage -> ordered.stream().filter(step -> step.stage() == stage).toList()).toList(); + } + + public PlacementState execute(PlacementContext context) { + PlacementState state = new PlacementState(context); + for (PlacementStage stage : PlacementStage.BEFORE_PASS) { + run(stage, context, state, null); + } + run(PlacementStage.BLOCKS, context, state, this); + run(PlacementStage.AFTER_BLOCKS, context, state, null); + return state; + } + + public void run(PlacementStage stage, PlacementContext context, PlacementState state, C input) { + for (PlacementLifecycleBuilder.Step step : stages.get(stage.order)) { + if (state.isRejected()) { + return; + } + // Registration pairs each function with its typed stage. + @SuppressWarnings("unchecked") + PlacementFunction function = (PlacementFunction) step.function(); + function.execute(context, state, input); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/object/PlacementLifecycleBuilder.java b/core/src/main/java/art/arcane/iris/engine/object/PlacementLifecycleBuilder.java index 74d990ca4..51e4cf7fd 100644 --- a/core/src/main/java/art/arcane/iris/engine/object/PlacementLifecycleBuilder.java +++ b/core/src/main/java/art/arcane/iris/engine/object/PlacementLifecycleBuilder.java @@ -1,13 +1,84 @@ package art.arcane.iris.engine.object; -import lombok.Builder; - -import java.util.HashSet; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.PriorityQueue; -@Builder -public class PlacementLifecycleBuilder { - HashSet dependencies; - +/** + * Registers steps and resolves their graph before an engine runtime is published. + * A dependency names a required step, not a Java class: two instances of the same module can + * register distinct work. Declaring a dependency does not install its prerequisite. + * The module composition must register it, in any order, before calling {@link #build()}. + * + *
{@code
+ * lifecycle.add(FILL, PlacementStage.AFTER_BLOCKS, this::fill, HEIGHT, BOUNDS);
+ * }
+ * + * Independent steps retain registration order within their stage. Invalid graphs fail construction; + * the builder never executes functions. Functions must not capture mutable placement state. + */ +public final class PlacementLifecycleBuilder { + private final Map> steps = new LinkedHashMap<>(); + public void add(PlacementLifecycleDependency id, PlacementStage stage, + PlacementFunction function, PlacementLifecycleDependency... after) { + Objects.requireNonNull(id, "Step id"); + Objects.requireNonNull(stage, "Stage"); + Objects.requireNonNull(function, "Function"); + Step step = new Step<>(id, stage, function, List.of(after), steps.size()); + if (steps.putIfAbsent(id, step) != null) { + throw new IllegalArgumentException("Duplicate placement step '" + id.name() + "'"); + } + } + + /** Stable topological sort; stage barriers do not need all-to-all edges. */ + public PlacementLifecycle build() { + Map remaining = new HashMap<>(); + Map>> dependents = new HashMap<>(); + PriorityQueue> ready = new PriorityQueue<>(Comparator.>comparingInt(step -> step.stage.order).thenComparingInt(Step::index)); + for (Step step : steps.values()) { + var prerequisites = step.after.stream().distinct().toList(); + remaining.put(step.id, prerequisites.size()); + for (PlacementLifecycleDependency id : prerequisites) { + Step prerequisite = steps.get(id); + if (prerequisite == null) { + throw new IllegalArgumentException("Placement step '" + step.id.name() + + "' requires missing step '" + id.name() + "'"); + } + if (prerequisite.stage.order > step.stage.order) { + throw new IllegalArgumentException("Placement step '" + step.id.name() + "' in " + step.stage + + " cannot depend on later step '" + id.name() + "' in " + prerequisite.stage); + } + dependents.computeIfAbsent(id, ignored -> new ArrayList<>()).add(step); + } + if (prerequisites.isEmpty()) { + ready.add(step); + } + } + List> ordered = new ArrayList<>(steps.size()); + while (!ready.isEmpty()) { + Step step = ready.remove(); + ordered.add(step); + for (Step dependent : dependents.getOrDefault(step.id, List.of())) { + if (remaining.compute(dependent.id, (ignored, count) -> count - 1) == 0) { + ready.add(dependent); + } + } + } + if (ordered.size() != steps.size()) { + throw new IllegalArgumentException("Placement dependency cycle; unresolved steps: " + + steps.keySet().stream().filter(id -> remaining.get(id) > 0) + .map(PlacementLifecycleDependency::name).toList()); + } + return new PlacementLifecycle(ordered); + } + + record Step(PlacementLifecycleDependency id, PlacementStage stage, PlacementFunction function, + List after, int index) { + } } diff --git a/core/src/main/java/art/arcane/iris/engine/object/PlacementLifecycleDependency.java b/core/src/main/java/art/arcane/iris/engine/object/PlacementLifecycleDependency.java index 19ccf1c5a..8b76e50db 100644 --- a/core/src/main/java/art/arcane/iris/engine/object/PlacementLifecycleDependency.java +++ b/core/src/main/java/art/arcane/iris/engine/object/PlacementLifecycleDependency.java @@ -1,10 +1,13 @@ package art.arcane.iris.engine.object; -import lombok.Builder; - -@Builder -public class PlacementLifecycleDependency { - PlacementFunction function; - +import java.util.Objects; +/** A named prerequisite, scoped to one placement plan. */ +public record PlacementLifecycleDependency(String name) { + public PlacementLifecycleDependency { + Objects.requireNonNull(name, "Dependency name"); + if (name.isBlank()) { + throw new IllegalArgumentException("Placement dependency name cannot be blank"); + } + } } diff --git a/core/src/main/java/art/arcane/iris/engine/object/PlacementLifecycles.java b/core/src/main/java/art/arcane/iris/engine/object/PlacementLifecycles.java new file mode 100644 index 000000000..7b93d3978 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/object/PlacementLifecycles.java @@ -0,0 +1,43 @@ +package art.arcane.iris.engine.object; + +import java.util.EnumMap; +import java.util.Map; + +/** One resolved plan per mode in an engine runtime. Engine-less tools share a separate default set. */ +public final class PlacementLifecycles { + private final Map plans; + + private PlacementLifecycles(Map plans) { + this.plans = Map.copyOf(plans); + } + + public static PlacementLifecycles resolve() { + Map plans = new EnumMap<>(ObjectPlaceMode.class); + for (ObjectPlaceMode mode : ObjectPlaceMode.values()) { + try { + plans.put(mode, mode.createLifecycle()); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException("Invalid placement lifecycle for " + mode + ": " + e.getMessage(), e); + } + } + return new PlacementLifecycles(plans); + } + + public static PlacementLifecycles defaults() { + return Defaults.INSTANCE; + } + + static PlacementLifecycles forPlacer(IObjectPlacer placer) { + var engine = placer.getEngine(); + PlacementLifecycles plans = engine == null ? null : engine.getPlacementLifecycles(); + return plans == null ? defaults() : plans; + } + + public PlacementLifecycle get(ObjectPlaceMode mode) { + return plans.get(java.util.Objects.requireNonNull(mode, "Placement mode")); + } + + private static final class Defaults { + private static final PlacementLifecycles INSTANCE = resolve(); + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/object/PlacementModule.java b/core/src/main/java/art/arcane/iris/engine/object/PlacementModule.java index 303ef9613..ea9973528 100644 --- a/core/src/main/java/art/arcane/iris/engine/object/PlacementModule.java +++ b/core/src/main/java/art/arcane/iris/engine/object/PlacementModule.java @@ -1,27 +1,9 @@ package art.arcane.iris.engine.object; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.VectorMap; -import art.arcane.iris.util.common.math.IrisBlockVector; - -public abstract class PlacementModule { - PlacementContext context; - PlacementState state; - - final PlacementModule load(PlacementContext context, PlacementState state) { - this.context = context; - this.state = state; - return this; - } - - void install() { - - } - - void setHeight() {} - - void onBlock(VectorMap blocks, VectorMap states, PlatformBlockState block, TileData tile, IrisBlockVector vector) {} - - void postHeight() {} - +/** + * Registers work during runtime construction. Functions are shared by concurrent placements: + * implementations must receive placement state at execution time, never capture it at installation. + */ +public interface PlacementModule { + void install(PlacementLifecycleBuilder lifecycle); } diff --git a/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleAnchor.java b/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleAnchor.java new file mode 100644 index 000000000..efe365da0 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleAnchor.java @@ -0,0 +1,42 @@ +package art.arcane.iris.engine.object; + +/** Common caller-supplied and from-bottom anchors wrap each mode's sampled height. */ +final class PlacementModuleAnchor implements PlacementModule { + static final PlacementLifecycleDependency HEIGHT = new PlacementLifecycleDependency("anchor.height"); + static final PlacementLifecycleDependency POSITIONED = new PlacementLifecycleDependency("anchor.positioned"); + static final PlacementLifecycleDependency FINAL_HEIGHT = new PlacementLifecycleDependency("anchor.final"); + + @Override + public void install(PlacementLifecycleBuilder lifecycle) { + lifecycle.add(POSITIONED, PlacementStage.HEIGHT, (context, state, ignored) -> { + if (context.yv >= 0 && state.config.isBottom() + && state.config.getMode() != ObjectPlaceMode.STRUCTURE_PIECE) { + state.y += Math.floorDiv(context.self.h, 2); + if (!state.config.isForcePlace() && state.config.getCarvingSupport() != CarvingMode.CARVING_ONLY + && PlacementModuleSurfaceSupport.rejectsAnchor(context, state, context.x, state.y, context.z)) { + state.reject("carving-anchor"); + } + } + }, HEIGHT); + lifecycle.add(FINAL_HEIGHT, PlacementStage.BEFORE_BLOCKS, + (context, state, ignored) -> state.y += state.yrand, POSITIONED, PlacementModuleCollision.CHECK); + } + + static void install(PlacementLifecycleBuilder lifecycle, PlacementFunction sampledHeight) { + lifecycle.add(HEIGHT, PlacementStage.HEIGHT, (context, state, ignored) -> { + if (state.config.isFromBottom()) { + state.y = context.self.getH() + 1 + state.rty; + } else if (context.yv < 0) { + sampledHeight.execute(context, state, null); + return; + } else { + state.y = context.yv; + } + if (!state.config.isForcePlace() + && state.config.getMode() != ObjectPlaceMode.STRUCTURE_PIECE + && PlacementModuleSurfaceSupport.rejectsAnchor(context, state, context.x, state.y, context.z)) { + state.reject("carving-anchor"); + } + }, PlacementModulePreparation.TRANSFORMS); + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleBlocks.java b/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleBlocks.java new file mode 100644 index 000000000..1586366c3 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleBlocks.java @@ -0,0 +1,18 @@ +package art.arcane.iris.engine.object; + +/** Owns block-pass execution and the object read lock. */ +final class PlacementModuleBlocks implements PlacementModule { + static final PlacementLifecycleDependency COMPLETE = new PlacementLifecycleDependency("blocks.complete"); + + @Override + public void install(PlacementLifecycleBuilder lifecycle) { + lifecycle.add(COMPLETE, PlacementStage.BLOCKS, (context, state, plan) -> { + context.self.readLock.lock(); + try { + new ObjectBlockPass(context, state, plan, context.listener).process(); + } finally { + context.self.readLock.unlock(); + } + }, PlacementModuleBore.BORE); + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleBore.java b/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleBore.java new file mode 100644 index 000000000..d813f1c30 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleBore.java @@ -0,0 +1,24 @@ +package art.arcane.iris.engine.object; + +/** The first world-writing step; all placement guards must have completed. */ +final class PlacementModuleBore implements PlacementModule { + static final PlacementLifecycleDependency BORE = new PlacementLifecycleDependency("bore"); + + @Override + public void install(PlacementLifecycleBuilder lifecycle) { + lifecycle.add(BORE, PlacementStage.BEFORE_BLOCKS, (context, state, ignored) -> { + if (!state.config.isBore()) { + return; + } + var bounds = state.worldBounds; + for (int x = bounds.minX(); x <= bounds.maxX(); x++) { + for (int y = bounds.minY() - state.config.getBoreExtendMinY(); + y <= bounds.maxY() + state.config.getBoreExtendMaxY(); y++) { + for (int z = bounds.minZ(); z <= bounds.maxZ(); z++) { + state.placer.set(x, y, z, IrisObject.States.AIR); + } + } + } + }, PlacementModuleBounds.WORLD, PlacementModuleCollision.CHECK, PlacementModuleAnchor.FINAL_HEIGHT); + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleBounds.java b/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleBounds.java new file mode 100644 index 000000000..40ec17887 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleBounds.java @@ -0,0 +1,43 @@ +package art.arcane.iris.engine.object; + +/** Computes the shared world volume for collision checks and boring, only when needed. */ +final class PlacementModuleBounds implements PlacementModule { + static final PlacementLifecycleDependency WORLD = new PlacementLifecycleDependency("bounds.world"); + + @Override + public void install(PlacementLifecycleBuilder lifecycle) { + lifecycle.add(WORLD, PlacementStage.VALIDATE, (context, state, ignored) -> { + IrisObjectPlacement config = state.config; + if (config.isBore() || (!config.isForcePlace() && config.getMode() != ObjectPlaceMode.STRUCTURE_PIECE + && (!config.getAllowedCollisions().isEmpty() || !config.getForbiddenCollisions().isEmpty()))) { + state.worldBounds = resolve(context, state, context.yv < 0 && config.getMode() == ObjectPlaceMode.PAINT); + } + }, PlacementModuleNativeStructureProtection.CHECK); + } + + private static PlacementContext.WorldBounds resolve(PlacementContext context, PlacementState state, boolean paint) { + int x = context.x; + int z = context.z; + int y = state.y + state.yrand; + int minX = x + state.bounds.minX(); + int maxX = x + state.bounds.maxX(); + int minZ = z + state.bounds.minZ(); + int maxZ = z + state.bounds.maxZ(); + if (!paint) { + return new PlacementContext.WorldBounds(minX, maxX, y + state.bounds.minY(), y + state.bounds.maxY(), minZ, maxZ); + } + + int minimumSurface = Integer.MAX_VALUE; + int maximumSurface = Integer.MIN_VALUE; + for (int worldX = minX; worldX <= maxX; worldX++) { + for (int worldZ = minZ; worldZ <= maxZ; worldZ++) { + int surface = state.placer.getHighest(worldX, worldZ, context.self.getLoader(), state.config.isUnderwater()); + minimumSurface = Math.min(minimumSurface, surface); + maximumSurface = Math.max(maximumSurface, surface); + } + } + int paintOffset = Math.floorDiv(context.self.h, 2); + return new PlacementContext.WorldBounds(minX, maxX, minimumSurface + state.bounds.minY() + paintOffset, + maximumSurface + state.bounds.maxY() + paintOffset, minZ, maxZ); + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleCenterHeight.java b/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleCenterHeight.java index 56d22a198..1d1bb2958 100644 --- a/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleCenterHeight.java +++ b/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleCenterHeight.java @@ -1,13 +1,17 @@ package art.arcane.iris.engine.object; -public class PlacementModuleCenterHeight extends PlacementModule { +public final class PlacementModuleCenterHeight implements PlacementModule { @Override - public void setHeight() { - state.y = (context.caveResult != null ? context.caveResult.getSurface() : context.placer.getHighest(context.x, context.z, context.self.getLoader(), context.config.isUnderwater())) + context.rty; - if (!context.config.isForcePlace()) { - if (context.shouldBailForCarvingAnchor(context.x, state.y, context.z)) { - state.bail = true; + public void install(PlacementLifecycleBuilder lifecycle) { + PlacementModuleAnchor.install(lifecycle, PlacementModuleCenterHeight::sample); + } + + private static void sample(PlacementContext context, PlacementState state, Void ignored) { + state.y = (context.caveResult != null ? context.caveResult.getSurface() : state.placer.getHighest(context.x, context.z, context.self.getLoader(), state.config.isUnderwater())) + state.rty; + if (!state.config.isForcePlace()) { + if (PlacementModuleSurfaceSupport.rejectsAnchor(context, state, context.x, state.y, context.z)) { + state.reject("carving-anchor"); } } } diff --git a/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleCollision.java b/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleCollision.java new file mode 100644 index 000000000..9686ff3cd --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleCollision.java @@ -0,0 +1,41 @@ +package art.arcane.iris.engine.object; + +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.PlacedObject; + +/** Owns object collision policy and its data-engine requirement. */ +final class PlacementModuleCollision implements PlacementModule { + static final PlacementLifecycleDependency CHECK = new PlacementLifecycleDependency("validate.collisions"); + + @Override + public void install(PlacementLifecycleBuilder lifecycle) { + lifecycle.add(CHECK, PlacementStage.VALIDATE, (context, state, ignored) -> { + IrisObjectPlacement config = state.config; + if (config.isForcePlace() || config.getMode() == ObjectPlaceMode.STRUCTURE_PIECE + || (config.getAllowedCollisions().isEmpty() && config.getForbiddenCollisions().isEmpty())) { + return; + } + Engine engine = context.rdata.getEngine(); + if (engine == null) { + throw new IllegalStateException("Object placement requires active Iris data for collision settings."); + } + var bounds = state.worldBounds; + for (int x = bounds.minX(); x <= bounds.maxX(); x++) { + for (int y = bounds.minY(); y <= bounds.maxY(); y++) { + for (int z = bounds.minZ(); z <= bounds.maxZ(); z++) { + PlacedObject placed = engine.getObjectPlacement(x, y, z); + if (placed == null || placed.getObject() == null) { + continue; + } + String key = placed.getObject().getLoadKey(); + if (key != null && config.getForbiddenCollisions().contains(key) + && !config.getAllowedCollisions().contains(key)) { + state.reject("object-collision"); + return; + } + } + } + } + }, PlacementModuleBounds.WORLD); + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleFloating.java b/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleFloating.java index 8fe9a821e..022aefabf 100644 --- a/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleFloating.java +++ b/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleFloating.java @@ -1,10 +1,10 @@ package art.arcane.iris.engine.object; -public class PlacementModuleFloating extends PlacementModule { +public final class PlacementModuleFloating implements PlacementModule { @Override - public void setHeight() { - state.y = context.rty; + public void install(PlacementLifecycleBuilder lifecycle) { + PlacementModuleAnchor.install(lifecycle, (context, state, ignored) -> state.y = state.rty); } } diff --git a/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleHeight.java b/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleHeight.java index 96460a254..d88f1188f 100644 --- a/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleHeight.java +++ b/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleHeight.java @@ -1,16 +1,10 @@ package art.arcane.iris.engine.object; -public class PlacementModuleHeight extends PlacementModule { +public final class PlacementModuleHeight implements PlacementModule { + private final boolean fast; + private final Mode mode; - int minX; - int maxX; - int minZ; - int maxZ; - - private boolean fast; - private Mode mode; - - public enum Mode { + public enum Mode { MIN, MAX } @@ -21,45 +15,35 @@ public class PlacementModuleHeight extends PlacementModule { } @Override - public void setHeight() { - minX = context.x + state.bounds.minX(); - maxX = context.x + state.bounds.maxX(); - minZ = context.z + state.bounds.minZ(); - maxZ = context.z + state.bounds.maxZ(); + public void install(PlacementLifecycleBuilder lifecycle) { + PlacementModuleAnchor.install(lifecycle, this::sample); + } + + private void sample(PlacementContext context, PlacementState state, Void ignored) { + int minX = context.x + state.bounds.minX(); + int maxX = context.x + state.bounds.maxX(); + int minZ = context.z + state.bounds.minZ(); + int maxZ = context.z + state.bounds.maxZ(); if (Mode.MIN == mode) { - state.y = context.placer.getEngine().getHeight() + 1; + state.y = Integer.MAX_VALUE; } - if (fast) { - computeFastHeight(context); - } else { - computeHeight(context); - } - } - - private void computeFastHeight(PlacementContext context) { - int xRadius = Math.max(0, (maxX - minX) / 2); - int zRadius = Math.max(0, (maxZ - minZ) / 2); - - for (int i = minX; i <= maxX; i += Math.abs(xRadius) + 1) { - for (int ii = minZ; ii <= maxZ; ii += Math.abs(zRadius) + 1) { - columnHeight(context, i, ii); + int xStep = fast ? Math.max(0, (maxX - minX) / 2) + 1 : 1; + int zStep = fast ? Math.max(0, (maxZ - minZ) / 2) + 1 : 1; + for (int i = minX; i <= maxX; i += xStep) { + for (int ii = minZ; ii <= maxZ; ii += zStep) { + columnHeight(context, state, i, ii); + if (state.isRejected()) { + return; + } } } } - private void computeHeight(PlacementContext context) { - for (int i = minX; i <= maxX; i++) { - for (int ii = minZ; ii <= maxZ; ii++) { - columnHeight(context, i, ii); - } - } - } - - private void columnHeight(PlacementContext context, int i, int ii) { - int h = context.placer.getHighest(i, ii, context.self.getLoader(), context.config.isUnderwater()) + context.rty; - if (!context.config.isForcePlace()) { - if (context.shouldBailForCarvingAnchor(i, h, ii)) { - state.bail = true; + private void columnHeight(PlacementContext context, PlacementState state, int i, int ii) { + int h = state.placer.getHighest(i, ii, context.self.getLoader(), state.config.isUnderwater()) + state.rty; + if (!state.config.isForcePlace()) { + if (PlacementModuleSurfaceSupport.rejectsAnchor(context, state, i, h, ii)) { + state.reject("carving-anchor"); } } diff --git a/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleLimits.java b/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleLimits.java new file mode 100644 index 000000000..8f1482121 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleLimits.java @@ -0,0 +1,34 @@ +package art.arcane.iris.engine.object; + +/** Water, cave clearance and height-clamp eligibility. */ +final class PlacementModuleLimits implements PlacementModule { + static final PlacementLifecycleDependency CHECK = new PlacementLifecycleDependency("validate.limits"); + + @Override + public void install(PlacementLifecycleBuilder lifecycle) { + lifecycle.add(CHECK, PlacementStage.VALIDATE, (context, state, ignored) -> { + IrisObjectPlacement config = state.config; + if (config.isForcePlace() || config.getMode() == ObjectPlaceMode.STRUCTURE_PIECE) { + return; + } + if (context.yv < 0 && config.getMode() != ObjectPlaceMode.FLOATING + && !config.isUnderwater() && !config.isOnwater() + && state.placer.isUnderwater(context.x, context.z)) { + state.reject("underwater-anchor"); + return; + } + if (context.caveResult != null + && Math.max(0, context.self.h + state.yrand + state.ty) + 1 >= context.caveResult.getHeight()) { + state.reject("cave-clearance"); + return; + } + if (config.isUnderwater() && state.y + state.rty + state.ty >= state.placer.getFluidHeight()) { + state.reject("fluid-height"); + return; + } + if (!config.getClamp().canPlace(state.y + state.rty + state.ty, state.y - state.rty + state.ty)) { + state.reject("height-clamp"); + } + }, PlacementModuleSurfaceSupport.CHECK); + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleNativeStructureProtection.java b/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleNativeStructureProtection.java new file mode 100644 index 000000000..180f32de3 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleNativeStructureProtection.java @@ -0,0 +1,111 @@ +package art.arcane.iris.engine.object; + +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.NativeStructureVolume; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.VectorMap; +import art.arcane.iris.util.common.math.IrisBlockVector; +import art.arcane.volmlib.util.collection.KList; + +/** Native structures remain protected even when forcePlace bypasses optional placement checks. */ +final class PlacementModuleNativeStructureProtection implements PlacementModule { + static final PlacementLifecycleDependency CHECK = new PlacementLifecycleDependency("validate.native-structures"); + + @Override + public void install(PlacementLifecycleBuilder lifecycle) { + lifecycle.add(CHECK, PlacementStage.VALIDATE, (context, state, ignored) -> { + if (state.config.getMode() != ObjectPlaceMode.STRUCTURE_PIECE && vetoes(context, state)) { + state.reject("native-structure"); + } + }, PlacementModuleLimits.CHECK); + } + + private static boolean vetoes(PlacementContext context, PlacementState state) { + IrisObject self = context.self; + IObjectPlacer placer = state.placer; + IrisObjectPlacement config = state.config; + ObjectSpinKernel spin = state.spin; + IrisBlockVector translateOffset = state.translateOffset; + boolean translating = translateOffset != null; + boolean ceilingHang = config.getMode() == ObjectPlaceMode.CEILING_HANG; + boolean paint = context.yv < 0 && config.getMode() == ObjectPlaceMode.PAINT; + int warpMargin = state.warpMargin; + int x = context.x; + int y = state.y + state.yrand; + int z = context.z; + Engine engine = placer.getEngine(); + if (engine == null) { + return false; + } + + int margin = (Math.max(self.getW(), Math.max(self.getH(), self.getD())) / 2) + 1 + warpMargin; + if (translating) { + margin += Math.max(Math.abs(translateOffset.getBlockX()), + Math.max(Math.abs(translateOffset.getBlockY()), Math.abs(translateOffset.getBlockZ()))); + } + + KList volumes = engine.getNativeStructureVolumes(x - margin, z - margin, x + margin, z + margin); + if (volumes == null || volumes.isEmpty()) { + return false; + } + + int worldY = y + engine.getMinHeight(); + int envelopeMinY = paint ? Integer.MIN_VALUE : worldY - margin; + int envelopeMaxY = paint ? Integer.MAX_VALUE : worldY + margin; + boolean envelopeMeetsPiece = false; + for (NativeStructureVolume volume : volumes) { + if (volume.intersects(x - margin, envelopeMinY, z - margin, x + margin, envelopeMaxY, z + margin)) { + envelopeMeetsPiece = true; + break; + } + } + + if (!envelopeMeetsPiece) { + return false; + } + + self.readLock.lock(); + try { + VectorMap.Cursor cursor = self.blocks.cursor(); + while (cursor.next()) { + PlatformBlockState source = cursor.value(); + if (source == null || isAirBlock(source)) { + continue; + } + + IrisBlockVector i = cursor.key().clone(); + spin.rotate(i); + if (ceilingHang) { + i.setY(-i.getBlockY()); + } + if (translating) { + i.add(translateOffset); + } + + int xx = x + (int) Math.round(i.getX()); + int zz = z + (int) Math.round(i.getZ()); + int yy = paint + ? (int) Math.round(i.getY()) + Math.floorDiv(self.h, 2) + + placer.getHighest(xx, zz, self.getLoader(), config.isUnderwater()) + : y + (int) Math.round(i.getY()); + int worldBlockY = yy + engine.getMinHeight(); + + for (NativeStructureVolume volume : volumes) { + if (volume.containsWithin(xx, worldBlockY, zz, warpMargin)) { + return true; + } + } + } + } finally { + self.readLock.unlock(); + } + + return false; + } + + private static boolean isAirBlock(PlatformBlockState state) { + String material = IrisObjectShaping.materialKey(state); + return material.equals("minecraft:air") || material.equals("minecraft:cave_air"); + } + +} diff --git a/core/src/main/java/art/arcane/iris/engine/object/PlacementModulePaint.java b/core/src/main/java/art/arcane/iris/engine/object/PlacementModulePaint.java index 18ee99aff..64fef1f10 100644 --- a/core/src/main/java/art/arcane/iris/engine/object/PlacementModulePaint.java +++ b/core/src/main/java/art/arcane/iris/engine/object/PlacementModulePaint.java @@ -1,13 +1,17 @@ package art.arcane.iris.engine.object; -public class PlacementModulePaint extends PlacementModule { +public final class PlacementModulePaint implements PlacementModule { @Override - public void setHeight() { - state.y = context.placer.getHighest(context.x, context.z, context.self.getLoader(), context.config.isUnderwater()) + context.rty; - if (!context.config.isForcePlace()) { - if (context.shouldBailForCarvingAnchor(context.x, state.y, context.z)) { - state.bail = true; + public void install(PlacementLifecycleBuilder lifecycle) { + PlacementModuleAnchor.install(lifecycle, PlacementModulePaint::sample); + } + + private static void sample(PlacementContext context, PlacementState state, Void ignored) { + state.y = state.placer.getHighest(context.x, context.z, context.self.getLoader(), state.config.isUnderwater()) + state.rty; + if (!state.config.isForcePlace()) { + if (PlacementModuleSurfaceSupport.rejectsAnchor(context, state, context.x, state.y, context.z)) { + state.reject("carving-anchor"); } } } diff --git a/core/src/main/java/art/arcane/iris/engine/object/PlacementModulePreparation.java b/core/src/main/java/art/arcane/iris/engine/object/PlacementModulePreparation.java new file mode 100644 index 000000000..a66fd33fe --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/object/PlacementModulePreparation.java @@ -0,0 +1,95 @@ +package art.arcane.iris.engine.object; + +import art.arcane.iris.engine.framework.placer.HeightmapObjectPlacer; +import art.arcane.iris.util.common.math.IrisBlockVector; + +/** Resolves the placer and transforms once, preserving the caller's RNG draw order. */ +final class PlacementModulePreparation implements PlacementModule { + static final PlacementLifecycleDependency PLACER = new PlacementLifecycleDependency("prepare.placer"); + static final PlacementLifecycleDependency TRANSFORMS = new PlacementLifecycleDependency("prepare.transforms"); + + @Override + public void install(PlacementLifecycleBuilder lifecycle) { + 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); + } + }); + lifecycle.add(TRANSFORMS, PlacementStage.PREPARE, PlacementModulePreparation::prepare, + PlacementModuleSlope.SLOPE); + } + + private static void prepare(PlacementContext context, PlacementState state, Void ignored) { + IrisObjectPlacement config = state.config; + IrisObject self = context.self; + if (config.isSmartBore()) { + IrisObjectShaping.ensureSmartBored(self); + } + int spinx = context.rng.imax() / 1000; + int spiny = context.rng.imax() / 1000; + int spinz = context.rng.imax() / 1000; + state.spinX = spinx; + state.spinY = spiny; + state.spinZ = spinz; + state.rty = config.getRotation().rotate(new IrisBlockVector(0, self.getCenter().getBlockY(), 0), spinx, spiny, spinz).getBlockY(); + state.ty = config.getTranslate().translate(new IrisBlockVector(0, self.getCenter().getBlockY(), 0), config.getRotation(), spinx, spiny, spinz).getBlockY(); + state.spin = new ObjectSpinKernel(config.getRotation(), spinx, spiny, spinz); + IrisObjectTranslate translate = config.getTranslate(); + if (translate.canTranslate()) { + state.translateOffset = config.getRotation().rotate( + new IrisBlockVector(translate.getX(), translate.getY(), translate.getZ()), spinx, spiny, spinz); + } + int yrand = translate.getYRandom(); + state.yrand = yrand > 0 ? context.rng.i(0, yrand) : yrand < 0 ? context.rng.i(yrand, 0) : yrand; + state.warpMargin = !config.getWarp().isFlat() ? (int) Math.ceil(Math.abs(config.getWarp().getMultiplier()) / 2D) : 0; + state.bounds = transformedBounds(self, state.spin, state.translateOffset != null, state.translateOffset, + config.getMode() == ObjectPlaceMode.CEILING_HANG, state.warpMargin); + } + + private static PlacementContext.TransformedBounds transformedBounds(IrisObject self, ObjectSpinKernel spin, boolean translating, IrisBlockVector translateOffset, + boolean ceilingHang, int margin) { + int sourceMinX = -self.getCenter().getBlockX(); + int sourceMaxX = self.getW() - self.getCenter().getBlockX() - 1; + int sourceMinY = -self.getCenter().getBlockY(); + int sourceMaxY = self.getH() - self.getCenter().getBlockY() - 1; + int sourceMinZ = -self.getCenter().getBlockZ(); + int sourceMaxZ = self.getD() - self.getCenter().getBlockZ() - 1; + int minX = Integer.MAX_VALUE; + int maxX = Integer.MIN_VALUE; + int minY = Integer.MAX_VALUE; + int maxY = Integer.MIN_VALUE; + int minZ = Integer.MAX_VALUE; + int maxZ = Integer.MIN_VALUE; + + for (int xCorner = 0; xCorner < 2; xCorner++) { + int sourceX = xCorner == 0 ? sourceMinX : sourceMaxX; + for (int yCorner = 0; yCorner < 2; yCorner++) { + int sourceY = yCorner == 0 ? sourceMinY : sourceMaxY; + for (int zCorner = 0; zCorner < 2; zCorner++) { + int sourceZ = zCorner == 0 ? sourceMinZ : sourceMaxZ; + IrisBlockVector corner = new IrisBlockVector(sourceX, sourceY, sourceZ); + spin.rotate(corner); + if (ceilingHang) { + corner.setY(-corner.getBlockY()); + } + if (translating) { + corner.add(translateOffset); + } + int transformedX = (int) Math.round(corner.getX()); + int transformedY = (int) Math.round(corner.getY()); + int transformedZ = (int) Math.round(corner.getZ()); + minX = Math.min(minX, transformedX); + maxX = Math.max(maxX, transformedX); + minY = Math.min(minY, transformedY); + maxY = Math.max(maxY, transformedY); + minZ = Math.min(minZ, transformedZ); + maxZ = Math.max(maxZ, transformedZ); + } + } + } + + return new PlacementContext.TransformedBounds(minX - margin, maxX + margin, minY, maxY, minZ - margin, maxZ + margin); + } + +} diff --git a/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleSlope.java b/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleSlope.java new file mode 100644 index 000000000..5db40a5a1 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleSlope.java @@ -0,0 +1,69 @@ +package art.arcane.iris.engine.object; + +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.util.project.stream.ProceduralStream; + +/** Slope checks precede random rotation and leave the caller's configuration intact. */ +final class PlacementModuleSlope implements PlacementModule { + static final PlacementLifecycleDependency SLOPE = new PlacementLifecycleDependency("prepare.slope"); + + @Override + public void install(PlacementLifecycleBuilder lifecycle) { + lifecycle.add(SLOPE, PlacementStage.PREPARE, (context, state, ignored) -> { + IrisObjectPlacement config = state.config; + boolean evaluate = !config.isForcePlace() && !config.getSlopeCondition().isDefault(); + if (!evaluate && !config.isRotateTowardsSlope()) { + return; + } + Engine engine = state.placer.getEngine(); + if (engine == null) { + throw new IllegalStateException("Object placement requires an active Iris engine for slope settings."); + } + if (evaluate && !config.getSlopeCondition().isValid( + engine.getComplex().getSlopeStream().get(context.x, context.z))) { + state.reject("slope"); + return; + } + if (config.isRotateTowardsSlope()) { + state.config = rotate(context.self, config, engine, context.x, context.z); + } + }, PlacementModulePreparation.PLACER); + } + + private static IrisObjectPlacement rotate(IrisObject self, IrisObjectPlacement config, Engine engine, int x, int z) { + int slopeRotationY = 0; + ProceduralStream heightStream = engine.getComplex().getHeightStream(); + // Whichever side of the rectangle that bounds the object is lowest is the 'direction' of the slope (simply said). + double hNorth = heightStream.get(x, z + ((float) self.d) / 2); + double hEast = heightStream.get(x + ((float) self.w) / 2, z); + double hSouth = heightStream.get(x, z - ((float) self.d) / 2); + double hWest = heightStream.get(x - ((float) self.w) / 2, z); + double min = Math.min(Math.min(hNorth, hEast), Math.min(hSouth, hWest)); + if (min == hNorth) { + slopeRotationY = 0; + } else if (min == hEast) { + slopeRotationY = 90; + } else if (min == hSouth) { + slopeRotationY = 180; + } else if (min == hWest) { + slopeRotationY = 270; + } + + double newRotation = config.getRotation().getYAxis().getMin() + slopeRotationY; + IrisObjectRotation originalRotation = config.getRotation(); + IrisObjectRotation slopeRotation = new IrisObjectRotation(); + slopeRotation.setXAxis(originalRotation.getXAxis()); + slopeRotation.setZAxis(originalRotation.getZAxis()); + if (newRotation == 0) { + slopeRotation.setYAxis(new IrisAxisRotationClamp(false, false, 0, 0, 90)); + slopeRotation.setEnabled(originalRotation.canRotateX() || originalRotation.canRotateZ()); + } else { + slopeRotation.setYAxis(new IrisAxisRotationClamp(true, false, newRotation, newRotation, 90)); + slopeRotation.setEnabled(true); + } + config = config.toPlacement(config.getPlace().toArray(new String[0])); + config.setRotation(slopeRotation); + return config; + } + +} diff --git a/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleSnow.java b/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleSnow.java new file mode 100644 index 000000000..73ef9904e --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleSnow.java @@ -0,0 +1,44 @@ +package art.arcane.iris.engine.object; + +import art.arcane.volmlib.util.collection.KMap; +import art.arcane.volmlib.util.math.Position2; +import art.arcane.volmlib.util.math.RNG; + +/** Snow uses only successful object writes, and follows stilt or vacuum work. */ +final class PlacementModuleSnow implements PlacementModule { + static final PlacementLifecycleDependency COLLECT = new PlacementLifecycleDependency("snow.collect"); + static final PlacementLifecycleDependency FINISH = new PlacementLifecycleDependency("snow.finish"); + private final PlacementLifecycleDependency after; + + PlacementModuleSnow(PlacementLifecycleDependency after) { + this.after = after; + } + + @Override + public void install(PlacementLifecycleBuilder lifecycle) { + lifecycle.add(COLLECT, PlacementStage.BLOCK_WRITTEN, (context, state, block) -> { + if (!(state.config.getSnow() > 0)) { + return; + } + if (state.snowHeights == null) { + state.snowHeights = new KMap<>(); + } + Position2 position = new Position2(block.x(), block.z()); + Integer current = state.snowHeights.get(position); + if (current == null || current < block.y()) { + state.snowHeights.put(position, block.y()); + } + }); + lifecycle.add(FINISH, PlacementStage.AFTER_BLOCKS, (context, state, ignored) -> { + if (state.snowHeights == null) { + return; + } + RNG rng = context.rng.nextParallelRNG(3468854); + for (Position2 position : state.snowHeights.k()) { + int height = rng.i(0, (int) (state.config.getSnow() * 7)); + state.placer.set(position.getX(), state.snowHeights.get(position) + 1, position.getZ(), + IrisObject.States.SNOW_LAYERS[Math.max(Math.min(height, 7), 0)]); + } + }, COLLECT, after); + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleStilt.java b/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleStilt.java index f7fbd6778..62227326f 100644 --- a/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleStilt.java +++ b/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleStilt.java @@ -1,23 +1,24 @@ package art.arcane.iris.engine.object; +import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.common.data.B; import art.arcane.iris.util.common.data.VectorMap; import art.arcane.iris.util.common.math.IrisBlockVector; import art.arcane.iris.util.project.noise.CNG; +import art.arcane.volmlib.util.math.RNG; -public class PlacementModuleStilt extends PlacementModule { +/** Stilt preparation observes all transformed blocks before the fill step runs. */ +public final class PlacementModuleStilt implements PlacementModule { + static final PlacementLifecycleDependency BOUNDS = new PlacementLifecycleDependency("stilt.bounds"); + static final PlacementLifecycleDependency FILL = new PlacementLifecycleDependency("stilt.fill"); + + private final boolean fast; + private final Mode mode; - private boolean fast; - private boolean erode; - private Mode mode; public enum Mode { - DEFAULT, - CENTER, - MIN, - ERODE, - ORGANIC + DEFAULT, CENTER, MIN, ERODE, ORGANIC, CEILING } public PlacementModuleStilt(Mode mode, boolean fast) { @@ -26,155 +27,105 @@ public class PlacementModuleStilt extends PlacementModule { } @Override - public void setHeight() { - switch (mode) { - case CENTER, ORGANIC -> ObjectPlaceMode.CENTER_HEIGHT.createBehavior(context, state).setHeight(); - case ERODE -> { - // Only handled in post - } - case MIN -> { - if (fast) { - ObjectPlaceMode.FAST_MIN_HEIGHT.createBehavior(context, state).setHeight(); - } else { - ObjectPlaceMode.MIN_HEIGHT.createBehavior(context, state).setHeight(); - } - } - case DEFAULT -> { - if (fast) { - ObjectPlaceMode.FAST_MAX_HEIGHT.createBehavior(context, state).setHeight(); - } else { - ObjectPlaceMode.MAX_HEIGHT.createBehavior(context, state).setHeight(); - } - } + public void install(PlacementLifecycleBuilder lifecycle) { + PlacementModule height = switch (mode) { + case CENTER, ORGANIC, CEILING -> new PlacementModuleCenterHeight(); + case MIN -> new PlacementModuleHeight(PlacementModuleHeight.Mode.MIN, fast); + case DEFAULT, ERODE -> new PlacementModuleHeight(PlacementModuleHeight.Mode.MAX, fast); + }; + height.install(lifecycle); + if (mode == Mode.CEILING) { + new ObjectModuleCeilingHang().install(lifecycle); } + PlacementLifecycleDependency[] prerequisites = mode == Mode.CEILING + ? new PlacementLifecycleDependency[]{PlacementModuleAnchor.HEIGHT, ObjectModuleCeilingHang.FLIP} + : new PlacementLifecycleDependency[]{PlacementModuleAnchor.HEIGHT}; + lifecycle.add(BOUNDS, PlacementStage.COLLECT_BLOCK, (context, state, block) -> { + if (IrisObjectShaping.shouldStilt(block.data())) { + state.stiltLowest = Math.min(state.stiltLowest, block.vector().getBlockY()); + state.stiltHighest = Math.max(state.stiltHighest, block.vector().getBlockY()); + } + }, prerequisites); + lifecycle.add(FILL, PlacementStage.AFTER_BLOCKS, this::fill, PlacementModuleAnchor.HEIGHT, BOUNDS, PlacementModuleBlocks.COMPLETE); } - @Override - public void postHeight() { - - } - - - private void erodeStilt() { - int centroidCount = 0; - VectorMap.Cursor centroidCursor = blocks.cursor(); - while (centroidCursor.next()) { - IrisBlockVector rot = centroidCursor.key().clone(); - context.spin.rotate(rot); - if (context.config.getTranslate().canTranslate()) { - rot.add(translateOffset); - } - if (rot.getBlockY() == lowest) { - PlatformBlockState bd = centroidCursor.value(); - if (bd != null && IrisObjectShaping.shouldStilt(bd)) { - erodeCentroidX += rot.getX(); - erodeCentroidZ += rot.getZ(); - centroidCount++; - } - } - } - if (centroidCount > 0) { - erodeCentroidX /= centroidCount; - erodeCentroidZ /= centroidCount; - } - VectorMap.Cursor spreadCursor = blocks.cursor(); - while (spreadCursor.next()) { - IrisBlockVector rot = spreadCursor.key().clone(); - spin.rotate(rot); - if (context.config.getTranslate().canTranslate()) { - rot.add(translateOffset); - } - if (rot.getBlockY() == lowest) { - PlatformBlockState bd = spreadCursor.value(); - if (bd != null && IrisObjectShaping.shouldStilt(bd)) { - double dx = rot.getX() - erodeCentroidX; - double dz = rot.getZ() - erodeCentroidZ; - double dist = Math.sqrt(dx * dx + dz * dz); - if (dist > erodeMaxDist) { - erodeMaxDist = dist; - } - } - } - } - } - - private void applyOrganic(int targetLayer, boolean ceilingHang) { - var settings = context.config.getStiltSettings(); - - int startY = targetLayer + state.y; - int maxScan = settings != null ? Math.max(1, settings.getOrganicMaxScan()) : 48; - int jitterMax = settings != null ? Math.max(0, settings.getOrganicJitter()) : 3; - double scratch = settings != null ? Math.max(0, Math.min(1, settings.getOrganicScratch())) : 0.55; - long colHash = ((long) xx * 341873128712L) ^ ((long) zz * 132897987541L); - int jitter = jitterMax > 0 ? (int) (Math.abs(colHash) % (jitterMax + 1)) : 0; - - if (ceilingHang) { - int scan = 0; - int solidY = startY + 1; - while (scan < maxScan && !context.placer.isSolid(xx, solidY, zz)) { - solidY++; - scan++; - } - int topBound = (scan < maxScan ? solidY - 1 : startY + Math.min(maxScan, 8)) - jitter; - int total = topBound - startY; - for (int j = startY; j <= topBound; j++) { - if (scratch > 0 && total > 0) { - double ratio = (double) (j - startY) / total; - if (ratio > (1.0 - scratch)) { - long sh = ((long) xx * 341873128712L) ^ ((long) j * 132897987541L) ^ ((long) zz * 735791245321L); - double skipChance = (ratio - (1.0 - scratch)) / scratch; - if ((Math.abs(sh) % 1000) / 1000.0 < skipChance * 0.7) { - continue; - } - } - } - context.placer.set(xx, j, zz, d); - } - } else { - int scan = 0; - int solidY = startY - 1; - while (scan < maxScan && !context.placer.isSolid(xx, solidY, zz)) { - solidY--; - scan++; - } - int bottomBound = (scan < maxScan ? solidY + 1 : startY - Math.min(maxScan, 8)) + jitter; - int total = startY - bottomBound; - for (int j = startY; j >= bottomBound; j--) { - if (scratch > 0 && total > 0) { - double ratio = (double) (startY - j) / total; - if (ratio > (1.0 - scratch)) { - long sh = ((long) xx * 341873128712L) ^ ((long) j * 132897987541L) ^ ((long) zz * 735791245321L); - double skipChance = (ratio - (1.0 - scratch)) / scratch; - if ((Math.abs(sh) % 1000) / 1000.0 < skipChance * 0.7) { - continue; - } - } - } - context.placer.set(xx, j, zz, d); - } + private void fill(PlacementContext context, PlacementState state, Void ignored) { + if (state.stiltLowest == Integer.MAX_VALUE) { + return; } - } - - private void stilt(PlacementContext context) { - context.self.readLock.lock(); + IrisObject self = context.self; + IrisObjectPlacement config = state.config; + IObjectPlacer placer = state.placer; + IrisData rdata = context.rdata; + RNG rng = context.rng; + ObjectSpinKernel spin = state.spin; + IrisBlockVector translateOffset = state.translateOffset; + boolean translating = translateOffset != null; + boolean ceilingHang = mode == Mode.CEILING; + boolean organic = mode == Mode.ORGANIC || ceilingHang; + boolean eroding = mode == Mode.ERODE; + boolean hasEdits = !config.getEdit().isEmpty(); + boolean warped = !config.getWarp().isFlat(); + CNG surfaceWarp = warped ? config.getSurfaceWarp(rng, self.getLoader()) : null; + double warpHalf = warped ? config.getWarp().getMultiplier() / 2D : 0D; + int x = context.x; + int z = context.z; + int y = state.y; + int lowest = state.stiltLowest; + int topLayer = state.stiltHighest; + int xx, zz; + self.readLock.lock(); try { - VectorMap blocks = context.self.blocks; - - boolean ceilingHang = context.config.getMode() == ObjectPlaceMode.CEILING_HANG; - IrisStiltSettings settings = context.config.getStiltSettings(); + VectorMap blocks = self.blocks; + IrisStiltSettings settings = config.getStiltSettings(); double erodeCentroidX = 0; double erodeCentroidZ = 0; double erodeMaxDist = 1; - - if (context.config.getMode() == ObjectPlaceMode.ERODE_STILT) { - erodeStilt(context); + if (eroding) { + int centroidCount = 0; + VectorMap.Cursor centroidCursor = blocks.cursor(); + while (centroidCursor.next()) { + IrisBlockVector rot = centroidCursor.key().clone(); + spin.rotate(rot); + if (translating) { + rot.add(translateOffset); + } + if (rot.getBlockY() == lowest) { + PlatformBlockState bd = centroidCursor.value(); + if (bd != null && IrisObjectShaping.shouldStilt(bd)) { + erodeCentroidX += rot.getX(); + erodeCentroidZ += rot.getZ(); + centroidCount++; + } + } + } + if (centroidCount > 0) { + erodeCentroidX /= centroidCount; + erodeCentroidZ /= centroidCount; + } + VectorMap.Cursor spreadCursor = blocks.cursor(); + while (spreadCursor.next()) { + IrisBlockVector rot = spreadCursor.key().clone(); + spin.rotate(rot); + if (translating) { + rot.add(translateOffset); + } + if (rot.getBlockY() == lowest) { + PlatformBlockState bd = spreadCursor.value(); + if (bd != null && IrisObjectShaping.shouldStilt(bd)) { + double dx = rot.getX() - erodeCentroidX; + double dz = rot.getZ() - erodeCentroidZ; + double dist = Math.sqrt(dx * dx + dz * dz); + if (dist > erodeMaxDist) { + erodeMaxDist = dist; + } + } + } + } } VectorMap.Cursor stiltCursor = blocks.cursor(); - boolean warped = !context.config.getWarp().isFlat(); - CNG surfaceWarp = warped ? context.config.getSurfaceWarp(context.rng, context.self.getLoader()) : null; - while (stiltCursor.next()) { IrisBlockVector g = stiltCursor.key(); PlatformBlockState sourceData; @@ -182,12 +133,12 @@ public class PlacementModuleStilt extends PlacementModule { sourceData = stiltCursor.value(); } catch (Throwable e) { IrisLogging.reportError(e); - IrisLogging.warn("Failed to read block node " + g.getBlockX() + "," + g.getBlockY() + "," + g.getBlockZ() + " in object " + context.self.getLoadKey() + " (stilt cme)"); + IrisLogging.warn("Failed to read block node " + g.getBlockX() + "," + g.getBlockY() + "," + g.getBlockZ() + " in object " + self.getLoadKey() + " (stilt cme)"); sourceData = IrisObject.States.AIR; } if (sourceData == null) { - IrisLogging.warn("Failed to read block node " + g.getBlockX() + "," + g.getBlockY() + "," + g.getBlockZ() + " in object " + context.self.getLoadKey() + " (stilt null)"); + IrisLogging.warn("Failed to read block node " + g.getBlockX() + "," + g.getBlockY() + "," + g.getBlockZ() + " in object " + self.getLoadKey() + " (stilt null)"); sourceData = IrisObject.States.AIR; } @@ -197,7 +148,7 @@ public class PlacementModuleStilt extends PlacementModule { PlatformBlockState d = sourceData; if (settings != null && settings.getPalette() != null) { - d = context.config.getStiltSettings().getPalette().get(rng, context.x, state.y, context.z, context.rdata); + d = config.getStiltSettings().getPalette().get(rng, x, y, z, rdata); } else { String mat = IrisObjectShaping.materialKey(d); if (mat.equals("minecraft:grass_block") || mat.equals("minecraft:mycelium") || mat.equals("minecraft:podzol") || mat.equals("minecraft:dirt_path")) { @@ -210,24 +161,24 @@ public class PlacementModuleStilt extends PlacementModule { if (ceilingHang) { i.setY(-i.getBlockY()); } - if (context.config.getTranslate().canTranslate()) { + if (translating) { i.add(translateOffset); } - d = context.config.getRotation().rotate(d, spinx, spiny, spinz); + d = spin.rotate(d); - int targetLayer = context.config.getMode() == ObjectPlaceMode.CEILING_HANG ? topLayer : lowest; + int targetLayer = ceilingHang ? topLayer : lowest; if (i.getBlockY() != targetLayer) continue; - if (!context.config.getEdit().isEmpty()) { - for (IrisObjectReplace j : context.config.getEdit()) { - if (context.rng.chance(j.getChance())) { - for (PlatformBlockState k : j.getFind(context.rdata)) { + if (hasEdits) { + for (IrisObjectReplace j : config.getEdit()) { + if (rng.chance(j.getChance())) { + for (PlatformBlockState k : j.getFind(rdata)) { if (d == null) { continue; } if (j.isExact() ? k.matches(d) : IrisObjectShaping.materialKey(k).equals(IrisObjectShaping.materialKey(d))) { - PlatformBlockState newData = j.getReplace(context.rng, i.getX() + context.x, i.getY() + y, i.getZ() + context.z, context.rdata); + PlatformBlockState newData = j.getReplace(rng, i.getX() + x, i.getY() + y, i.getZ() + z, rdata); if (IrisObjectShaping.materialKey(newData).equals(IrisObjectShaping.materialKey(d))) { d = BlockDataMergeSupport.merge(d, newData); @@ -243,33 +194,84 @@ public class PlacementModuleStilt extends PlacementModule { if (d == null || !d.isOccluding()) continue; - xx = context.x + (int) Math.round(i.getX()); - zz = context.z + (int) Math.round(i.getZ()); + xx = x + (int) Math.round(i.getX()); + zz = z + (int) Math.round(i.getZ()); if (warped) { - xx += surfaceWarp.fitDouble(-warpHalf, warpHalf, i.getX() + context.x, i.getY() + state.y, i.getZ() + context.z); - zz += surfaceWarp.fitDouble(-warpHalf, warpHalf, i.getZ() + context.z, i.getY() + state.y, i.getX() + context.x); + xx += surfaceWarp.fitDouble(-warpHalf, warpHalf, i.getX() + x, i.getY() + y, i.getZ() + z); + zz += surfaceWarp.fitDouble(-warpHalf, warpHalf, i.getZ() + z, i.getY() + y, i.getX() + x); } if (organic) { + int startY = targetLayer + y; + int maxScan = settings != null ? Math.max(1, settings.getOrganicMaxScan()) : 48; + int jitterMax = settings != null ? Math.max(0, settings.getOrganicJitter()) : 3; + double scratch = settings != null ? Math.max(0, Math.min(1, settings.getOrganicScratch())) : 0.55; + long colHash = ((long) xx * 341873128712L) ^ ((long) zz * 132897987541L); + int jitter = jitterMax > 0 ? (int) (Math.abs(colHash) % (jitterMax + 1)) : 0; + if (ceilingHang) { + int scan = 0; + int solidY = startY + 1; + while (scan < maxScan && !placer.isSolid(xx, solidY, zz)) { + solidY++; + scan++; + } + int topBound = (scan < maxScan ? solidY - 1 : startY + Math.min(maxScan, 8)) - jitter; + int total = topBound - startY; + for (int j = startY; j <= topBound; j++) { + if (scratch > 0 && total > 0) { + double ratio = (double) (j - startY) / total; + if (ratio > (1.0 - scratch)) { + long sh = ((long) xx * 341873128712L) ^ ((long) j * 132897987541L) ^ ((long) zz * 735791245321L); + double skipChance = (ratio - (1.0 - scratch)) / scratch; + if ((Math.abs(sh) % 1000) / 1000.0 < skipChance * 0.7) { + continue; + } + } + } + placer.set(xx, j, zz, d); + } + } else { + int scan = 0; + int solidY = startY - 1; + while (scan < maxScan && !placer.isSolid(xx, solidY, zz)) { + solidY--; + scan++; + } + int bottomBound = (scan < maxScan ? solidY + 1 : startY - Math.min(maxScan, 8)) + jitter; + int total = startY - bottomBound; + for (int j = startY; j >= bottomBound; j--) { + if (scratch > 0 && total > 0) { + double ratio = (double) (startY - j) / total; + if (ratio > (1.0 - scratch)) { + long sh = ((long) xx * 341873128712L) ^ ((long) j * 132897987541L) ^ ((long) zz * 735791245321L); + double skipChance = (ratio - (1.0 - scratch)) / scratch; + if ((Math.abs(sh) % 1000) / 1000.0 < skipChance * 0.7) { + continue; + } + } + } + placer.set(xx, j, zz, d); + } + } continue; } - int highest = context.placer.getHighest(xx, zz, self.getLoader(), true); + int highest = placer.getHighest(xx, zz, self.getLoader(), true); - if (IrisProceduralBlocks.hasProperty(d, "waterlogged") && shouldAutoWaterlogBlock(yv, xx, highest, zz)) { + if (IrisProceduralBlocks.hasProperty(d, "waterlogged") && ObjectBlockPass.shouldAutoWaterlogBlock(context, state, xx, highest, zz)) { d = d.withProperty("waterlogged", "true"); } int lowerBound = highest - 1; if (settings != null) { - lowerBound -= context.config.getStiltSettings().getOverStilt() - rng.i(0, context.config.getStiltSettings().getYRand()); + lowerBound -= config.getStiltSettings().getOverStilt() - rng.i(0, config.getStiltSettings().getYRand()); if (settings.getYMax() != 0) - lowerBound -= Math.min(context.config.getStiltSettings().getYMax() - (lowest + y - highest), 0); + lowerBound -= Math.min(config.getStiltSettings().getYMax() - (lowest + y - highest), 0); } - if (context.config.getMode() == ObjectPlaceMode.ERODE_STILT) { + if (eroding) { double dx = i.getX() - erodeCentroidX; double dz = i.getZ() - erodeCentroidZ; double normalizedDist = Math.sqrt(dx * dx + dz * dz) / erodeMaxDist; @@ -280,13 +282,13 @@ public class PlacementModuleStilt extends PlacementModule { } for (int j = lowest + y; j > lowerBound; j--) { - PlatformBlockState fluidState = context.placer.get(xx, j, zz); + PlatformBlockState fluidState = placer.get(xx, j, zz); if (B.isFluid(fluidState)) { break; } - if (context.config.getMode() == ObjectPlaceMode.ERODE_STILT) { - int depth = (lowest + state.y) - j; - int totalDepth = (lowest + state.y) - lowerBound; + if (eroding) { + int depth = (lowest + y) - j; + int totalDepth = (lowest + y) - lowerBound; double depthRatio = totalDepth > 0 ? (double) depth / totalDepth : 0; if (depthRatio > 0.4) { long hash = ((long) (xx * 341873128712L) ^ ((long) j * 132897987541L) ^ ((long) zz * 735791245321L)); @@ -298,17 +300,14 @@ public class PlacementModuleStilt extends PlacementModule { } if (B.isVineBlock(d)) { - d = attachVineFaces(placer, d, xx, j, zz); + d = ObjectBlockPass.attachVineFaces(placer, d, xx, j, zz); } - context.placer.set(xx, j, zz, d); + placer.set(xx, j, zz, d); } } } finally { - context.self.readLock.unlock(); + self.readLock.unlock(); } - } - - } diff --git a/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleSurfaceSupport.java b/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleSurfaceSupport.java new file mode 100644 index 000000000..bd7e83afa --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleSurfaceSupport.java @@ -0,0 +1,65 @@ +package art.arcane.iris.engine.object; + +import art.arcane.iris.spi.IrisLogging; +import java.util.concurrent.ConcurrentHashMap; + +/** Carving and surface support rules, including the bedrock diagnostic. */ +final class PlacementModuleSurfaceSupport implements PlacementModule { + static final PlacementLifecycleDependency CHECK = new PlacementLifecycleDependency("validate.surface"); + private static final long IMPLAUSIBLE_BEDROCK_WARN_THROTTLE_MS = 5000L; + private static final ConcurrentHashMap IMPLAUSIBLE_BEDROCK_WARNS = new ConcurrentHashMap<>(); + + @Override + public void install(PlacementLifecycleBuilder lifecycle) { + lifecycle.add(CHECK, PlacementStage.VALIDATE, (context, state, ignored) -> { + IrisObjectPlacement config = state.config; + boolean rawStructurePiece = config.getMode() == ObjectPlaceMode.STRUCTURE_PIECE; + if (context.yv < 0 && !config.isForcePlace() && !config.isFromBottom() + && config.getMode() != ObjectPlaceMode.FLOATING && !rawStructurePiece + && config.getCarvingSupport().supportsSurface() && state.placer.getEngine() != null + && state.placer.getEngine().getDimension().isBedrock() && state.y <= 1) { + warnImplausibleBedrockPlacement(context.self, state.placer, config, context.x, state.y, context.z); + state.reject("bedrock-anchor"); + return; + } + boolean surfaceAnchored = context.yv < 0 ? config.getCarvingSupport().supportsSurface() + : config.getCarvingSupport() == CarvingMode.SURFACE_ONLY; + if (surfaceAnchored && !config.isForcePlace() && !config.isFromBottom() + && config.getMode() != ObjectPlaceMode.FLOATING && !rawStructurePiece + && !config.isUnderwater() && !config.isOnwater() && config.isRequireSurfaceSupport() + && IrisSurfaceSupport.isUnsupported(context.placer, context.self.getLoader(), context.x, context.z, + config.getTranslate(), config.getRotation(), state.spinX, state.spinY, state.spinZ, + context.self.getSurfaceSupportOffsets(), config.getSurfaceSupportBuffer(), config.getSurfaceSupportDepth())) { + state.reject("surface-support"); + } + }, PlacementModuleAnchor.POSITIONED); + } + + static boolean rejectsAnchor(PlacementContext context, PlacementState state, int x, int y, int z) { + return switch (state.config.getCarvingSupport()) { + case SURFACE_ONLY -> state.placer.isCarved(x, y, z); + case CARVING_ONLY -> !(state.placer.isCarved(x, y, z) || state.placer.isCarved(x, y - 1, z) + || state.placer.isCarved(x, y - 2, z) || state.placer.isCarved(x, y - 3, z)); + case ANYWHERE -> false; + }; + } + + private static void warnImplausibleBedrockPlacement(IrisObject self, IObjectPlacer placer, IrisObjectPlacement config, int x, int y, int z) { + String key = self.getLoadKey(); + String fingerprint = (key == null ? "" : key) + "|" + config.getMode(); + long now = System.currentTimeMillis(); + Long last = IMPLAUSIBLE_BEDROCK_WARNS.get(fingerprint); + if (last != null && now - last < IMPLAUSIBLE_BEDROCK_WARN_THROTTLE_MS) { + return; + } + IMPLAUSIBLE_BEDROCK_WARNS.put(fingerprint, now); + IrisLogging.warn("Implausible object placement rejected: " + + (key == null ? "" : key) + + " resolved anchorY=" + y + " at (" + x + "," + z + ") mode=" + config.getMode() + + " carving=" + config.getCarvingSupport() + + ". Surface-anchored placement should never land on the bedrock row. " + + "Height sampling returned a bogus value — not configured for floor placement " + + "(forcePlace=false, fromBottom=false, mode!=FLOATING). Skipping to protect bedrock."); + } + +} diff --git a/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleVacuum.java b/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleVacuum.java new file mode 100644 index 000000000..344b7417a --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/object/PlacementModuleVacuum.java @@ -0,0 +1,89 @@ +package art.arcane.iris.engine.object; + +import art.arcane.iris.engine.IrisComplex; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import art.arcane.iris.util.project.noise.SimplexNoise; + +/** Collects written object bounds, then bends terrain to meet them. Installed for vacuum modes. */ +final class PlacementModuleVacuum implements PlacementModule { + static final PlacementLifecycleDependency COLLECT = new PlacementLifecycleDependency("vacuum.collect"); + static final PlacementLifecycleDependency FINISH = new PlacementLifecycleDependency("vacuum.finish"); + private static final long VACUUM_WAVE_SEED = 7392113L; + + @Override + public void install(PlacementLifecycleBuilder lifecycle) { + lifecycle.add(COLLECT, PlacementStage.BLOCK_WRITTEN, (context, state, block) -> { + state.vacuumLowest = Math.min(state.vacuumLowest, block.y()); + state.vacuumHighest = Math.max(state.vacuumHighest, block.y()); + }); + lifecycle.add(FINISH, PlacementStage.AFTER_BLOCKS, (context, state, ignored) -> { + if (state.vacuumLowest == Integer.MAX_VALUE || state.placer.getEngine() == null) { + return; + } + vacuumTerrain(context.self, state.placer, state.config, context.x, context.z, + state.bounds.minX(), state.bounds.maxX(), state.bounds.minZ(), state.bounds.maxZ(), + state.vacuumLowest, state.vacuumHighest); + }, COLLECT, PlacementModuleBlocks.COMPLETE); + } + + private static void vacuumTerrain(IrisObject self, IObjectPlacer placer, IrisObjectPlacement config, int centerX, int centerZ, int lowX, int highX, int lowZ, int highZ, int baseY, int topY) { + ObjectPlaceMode mode = config.getMode(); + IrisVacuumSettings settings = config.getVacuumSettings(); + int radius = IrisObjectVacuum.resolveRadius(mode, settings); + int step = IrisObjectVacuum.resolveStep(mode); + double falloff = IrisObjectVacuum.resolveFalloff(settings); + int jitter = settings != null ? Math.max(0, settings.getOrganicJitter()) : 4; + boolean organicEdge = mode == ObjectPlaceMode.VACUUM_ORGANIC; + boolean wavyEdge = mode == ObjectPlaceMode.VACUUM_WAVY; + double waveAmplitude = IrisObjectVacuum.resolveWaveAmplitude(settings); + double waveScale = IrisObjectVacuum.resolveWaveScale(settings); + SimplexNoise waveNoise = (wavyEdge && waveAmplitude > 0) ? new SimplexNoise(VACUUM_WAVE_SEED) : null; + int meetY = baseY - 1; + + IrisComplex complex = placer.getEngine().getComplex(); + int worldMin = placer.getEngine().getMinHeight(); + int worldMax = worldMin + placer.getEngine().getHeight() - 1; + + for (int dx = lowX - radius; dx <= highX + radius; dx += step) { + for (int dz = lowZ - radius; dz <= highZ + radius; dz += step) { + int cx = centerX + dx; + int cz = centerZ + dz; + double effRadius = radius; + if (organicEdge && jitter > 0) { + long h = ((long) cx * 341873128712L) ^ ((long) cz * 132897987541L); + double n = ((Math.abs(h) % 1000) / 1000.0) - 0.5; + effRadius = Math.max(1.0, radius + (n * 2.0 * jitter)); + } + int origY = placer.getHighest(cx, cz, self.getLoader(), true); + int targetY = IrisObjectVacuum.columnTargetY(dx, dz, lowX, highX, lowZ, highZ, effRadius, falloff, origY, meetY); + if (waveNoise != null) { + int outX = IrisObjectVacuum.outset(dx, lowX, highX); + int outZ = IrisObjectVacuum.outset(dz, lowZ, highZ); + double waveDistance = Math.sqrt((double) (outX * outX) + (double) (outZ * outZ)); + double sample = waveNoise.noiseSigned(cx * waveScale, cz * waveScale); + targetY += IrisObjectVacuum.waveOffset(waveDistance, effRadius, sample, waveAmplitude); + } + if (targetY == origY) { + continue; + } + targetY = Math.max(worldMin + 1, Math.min(worldMax, targetY)); + if (targetY > origY) { + PlatformBlockState fill = complex != null ? complex.getRockStream().get(cx, cz) : null; + if (B.isAir(fill)) { + fill = IrisObject.States.STONE; + } + for (int yy = origY + 1; yy <= targetY; yy++) { + placer.set(cx, yy, cz, fill); + } + } else if (targetY < origY) { + boolean inside = IrisObjectVacuum.outset(dx, lowX, highX) == 0 && IrisObjectVacuum.outset(dz, lowZ, highZ) == 0; + int carveFloor = IrisObjectVacuum.carveFloorY(targetY, topY, inside); + for (int yy = origY; yy >= carveFloor; yy--) { + placer.set(cx, yy, cz, IrisObject.States.AIR); + } + } + } + } + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/object/PlacementStage.java b/core/src/main/java/art/arcane/iris/engine/object/PlacementStage.java new file mode 100644 index 000000000..cccb62d09 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/object/PlacementStage.java @@ -0,0 +1,38 @@ +package art.arcane.iris.engine.object; + +import java.util.List; + +/** + * Whole-placement phases surround a nested block pass. TRANSFORM_BLOCK runs after rotation and + * before translation; COLLECT_BLOCK runs before edits; BLOCK_WRITTEN runs only for successful + * object writes. Block prerequisites refer to the current block. AFTER_BLOCKS waits for the + * entire block pass, including markers. All whole-placement validation precedes world writes. + */ +public final class PlacementStage { + public static final PlacementStage PREPARE = new PlacementStage<>("prepare", 0); + public static final PlacementStage HEIGHT = new PlacementStage<>("height", 1); + public static final PlacementStage VALIDATE = new PlacementStage<>("validate", 2); + public static final PlacementStage BEFORE_BLOCKS = new PlacementStage<>("before-blocks", 3); + public static final PlacementStage TRANSFORM_BLOCK = new PlacementStage<>("transform-block", 4); + public static final PlacementStage COLLECT_BLOCK = new PlacementStage<>("collect-block", 5); + public static final PlacementStage BLOCK_WRITTEN = new PlacementStage<>("block-written", 6); + // BLOCKS denotes completion of the whole pass, so later steps can depend on all block work. + public static final PlacementStage BLOCKS = new PlacementStage<>("blocks", 7); + public static final PlacementStage AFTER_BLOCKS = new PlacementStage<>("after-blocks", 8); + static final List> ALL = List.of(PREPARE, HEIGHT, VALIDATE, BEFORE_BLOCKS, + TRANSFORM_BLOCK, COLLECT_BLOCK, BLOCK_WRITTEN, BLOCKS, AFTER_BLOCKS); + static final List> BEFORE_PASS = List.of(PREPARE, HEIGHT, VALIDATE, BEFORE_BLOCKS); + + private final String name; + final int order; + + private PlacementStage(String name, int order) { + this.name = name; + this.order = order; + } + + @Override + public String toString() { + return name; + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/object/PlacementState.java b/core/src/main/java/art/arcane/iris/engine/object/PlacementState.java index 99f78f718..2597f1bea 100644 --- a/core/src/main/java/art/arcane/iris/engine/object/PlacementState.java +++ b/core/src/main/java/art/arcane/iris/engine/object/PlacementState.java @@ -1,14 +1,67 @@ package art.arcane.iris.engine.object; import art.arcane.iris.engine.object.PlacementContext.TransformedBounds; +import art.arcane.iris.engine.object.PlacementContext.WorldBounds; +import art.arcane.iris.util.common.math.IrisBlockVector; +import art.arcane.volmlib.util.collection.KMap; +import art.arcane.volmlib.util.math.Position2; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.Setter; -final class PlacementState { +import java.util.Objects; + +/** Results and accumulators owned by one placement, never by a shared module or plan. */ +@Getter +@Setter +public final class PlacementState { + IrisObjectPlacement config; + IObjectPlacer placer; + ObjectSpinKernel spin; + int spinX; + int spinY; + int spinZ; + IrisBlockVector translateOffset; + int rty; + int ty; + int yrand; + int warpMargin; int y; TransformedBounds bounds; - boolean bail; + WorldBounds worldBounds; + int stiltLowest = Integer.MAX_VALUE; + int stiltHighest = Integer.MIN_VALUE; + int vacuumLowest = Integer.MAX_VALUE; + int vacuumHighest = Integer.MIN_VALUE; + KMap snowHeights; + + @Setter(AccessLevel.NONE) + private String rejection; + + PlacementState(PlacementContext context) { + this(-1, null); + config = context.config; + placer = context.placer; + } PlacementState(int y, TransformedBounds bounds) { this.y = y; this.bounds = bounds; } + + /** The first rejection is terminal. Each guard decides whether forcePlace exempts its rule. */ + public void reject(String reason) { + Objects.requireNonNull(reason, "Rejection reason"); + if (rejection == null) { + rejection = reason; + } + } + + public boolean isRejected() { + return rejection != null; + } + + public int heightOrRejected() { + return isRejected() ? -1 : y; + } } diff --git a/core/src/test/java/art/arcane/iris/engine/EnginePlacementLifecycleTest.java b/core/src/test/java/art/arcane/iris/engine/EnginePlacementLifecycleTest.java new file mode 100644 index 000000000..7127843f9 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/EnginePlacementLifecycleTest.java @@ -0,0 +1,55 @@ +package art.arcane.iris.engine; + +import art.arcane.iris.engine.framework.EngineEffects; +import art.arcane.iris.engine.framework.EngineMode; +import art.arcane.iris.engine.framework.EngineTarget; +import art.arcane.iris.engine.framework.EngineWorldManager; +import art.arcane.iris.engine.object.ObjectPlaceMode; +import org.junit.Test; + +import java.util.concurrent.CompletableFuture; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.mock; + +public class EnginePlacementLifecycleTest { + @Test + public void runtimeAssemblyResolvesBeforePublicationAndKeepsOldPlansIntact() { + var initial = assembly(1); + EngineRuntime previous = initial.freeze(new EngineRuntime.BiomeMaxes(0, 0, 0)); + var replacement = assembly(2); + EngineRuntime next = replacement.freeze(new EngineRuntime.BiomeMaxes(0, 0, 0)); + + assertSame(initial.placementLifecycles, previous.placementLifecycles()); + assertSame(replacement.placementLifecycles, next.placementLifecycles()); + for (ObjectPlaceMode mode : ObjectPlaceMode.values()) { + assertNotNull(next.placementLifecycles().get(mode)); + assertNotSame(previous.placementLifecycles().get(mode), next.placementLifecycles().get(mode)); + } + assertSame(initial.placementLifecycles, previous.placementLifecycles()); + } + + @Test + public void complexReplacementCarriesNewPlansAlongsideTheNewComplex() { + var initial = assembly(1); + EngineRuntime previous = initial.freeze(new EngineRuntime.BiomeMaxes(0, 0, 0)); + var replacement = assembly(2); + EngineRuntime next = previous.withComplex(2, replacement.complex, null, + new EngineRuntime.BiomeMaxes(1, 1, 1), replacement.placementLifecycles); + + assertSame(replacement.placementLifecycles, next.placementLifecycles()); + assertSame(replacement.complex, next.complex()); + assertSame(previous.worldManager(), next.worldManager()); + assertSame(initial.placementLifecycles, previous.placementLifecycles()); + } + + private EngineRuntimeBuilder.RuntimeAssembly assembly(int id) { + var assembly = new EngineRuntimeBuilder.RuntimeAssembly(id, mock(EngineTarget.class)); + assembly.complex = mock(IrisComplex.class); + assembly.effects = mock(EngineEffects.class); + assembly.mode = mock(EngineMode.class); + assembly.worldManager = mock(EngineWorldManager.class); + assembly.hash32 = CompletableFuture.completedFuture(0L); + return assembly; + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/mantle/components/MantleFloatingObjectComponentBoundaryRadiusTest.java b/core/src/test/java/art/arcane/iris/engine/mantle/components/MantleFloatingObjectComponentBoundaryRadiusTest.java index ec6b92503..0e5d244aa 100644 --- a/core/src/test/java/art/arcane/iris/engine/mantle/components/MantleFloatingObjectComponentBoundaryRadiusTest.java +++ b/core/src/test/java/art/arcane/iris/engine/mantle/components/MantleFloatingObjectComponentBoundaryRadiusTest.java @@ -42,6 +42,8 @@ import org.junit.rules.TemporaryFolder; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; +import java.util.HashMap; +import java.util.Map; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.anyString; @@ -55,9 +57,20 @@ public class MantleFloatingObjectComponentBoundaryRadiusTest { @Before public void bindPlatform() { IrisPlatforms.unbind(); - PlatformBlockState block = mock(PlatformBlockState.class); PlatformRegistries registries = mock(PlatformRegistries.class); - when(registries.block(anyString())).thenReturn(block); + // IrisObject retains these built-in states after this fixture unbinds its platform. + Map registryStates = new HashMap<>(); + when(registries.block(anyString())).thenAnswer(invocation -> { + String key = invocation.getArgument(0).toLowerCase(java.util.Locale.ROOT); + return registryStates.computeIfAbsent(key, value -> { + PlatformBlockState block = mock(PlatformBlockState.class); + when(block.key()).thenReturn(value); + when(block.materialKey()).thenReturn(value.split("\\[", 2)[0]); + when(block.isSolid()).thenReturn(!value.contains("air")); + when(block.isOccluding()).thenReturn(!value.contains("air")); + return block; + }); + }); IrisPlatform platform = mock(IrisPlatform.class); when(platform.registries()).thenReturn(registries); IrisPlatforms.bind(platform); diff --git a/core/src/test/java/art/arcane/iris/engine/mantle/components/MantleObjectComponentBoundaryRadiusTest.java b/core/src/test/java/art/arcane/iris/engine/mantle/components/MantleObjectComponentBoundaryRadiusTest.java index ab41d7edc..503e37837 100644 --- a/core/src/test/java/art/arcane/iris/engine/mantle/components/MantleObjectComponentBoundaryRadiusTest.java +++ b/core/src/test/java/art/arcane/iris/engine/mantle/components/MantleObjectComponentBoundaryRadiusTest.java @@ -40,6 +40,8 @@ import org.junit.rules.TemporaryFolder; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; +import java.util.HashMap; +import java.util.Map; import java.util.ArrayList; import java.util.List; @@ -60,9 +62,20 @@ public class MantleObjectComponentBoundaryRadiusTest { @Before public void bindPlatform() { IrisPlatforms.unbind(); - PlatformBlockState block = mock(PlatformBlockState.class); PlatformRegistries registries = mock(PlatformRegistries.class); - when(registries.block(anyString())).thenReturn(block); + // IrisObject retains these built-in states after this fixture unbinds its platform. + Map registryStates = new HashMap<>(); + when(registries.block(anyString())).thenAnswer(invocation -> { + String key = invocation.getArgument(0).toLowerCase(java.util.Locale.ROOT); + return registryStates.computeIfAbsent(key, value -> { + PlatformBlockState block = mock(PlatformBlockState.class); + when(block.key()).thenReturn(value); + when(block.materialKey()).thenReturn(value.split("\\[", 2)[0]); + when(block.isSolid()).thenReturn(!value.contains("air")); + when(block.isOccluding()).thenReturn(!value.contains("air")); + return block; + }); + }); IrisPlatform platform = mock(IrisPlatform.class); when(platform.registries()).thenReturn(registries); IrisPlatforms.bind(platform); diff --git a/core/src/test/java/art/arcane/iris/engine/object/IrisObjectPlacementRunnerRegressionTest.java b/core/src/test/java/art/arcane/iris/engine/object/IrisObjectPlacementRunnerRegressionTest.java index 6d061132f..2b8d74c05 100644 --- a/core/src/test/java/art/arcane/iris/engine/object/IrisObjectPlacementRunnerRegressionTest.java +++ b/core/src/test/java/art/arcane/iris/engine/object/IrisObjectPlacementRunnerRegressionTest.java @@ -1,12 +1,16 @@ package art.arcane.iris.engine.object; import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.IrisComplex; import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.NativeStructureVolume; import art.arcane.iris.engine.framework.PlacedObject; import art.arcane.iris.spi.IrisPlatform; import art.arcane.iris.spi.IrisPlatforms; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.spi.PlatformRegistries; +import art.arcane.iris.util.project.stream.ProceduralStream; +import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; import org.junit.After; import org.junit.Before; @@ -23,6 +27,7 @@ import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyDouble; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -178,6 +183,282 @@ public class IrisObjectPlacementRunnerRegressionTest { return placement; } + @Test + public void stiltWaitsForTheWholeTransformedFootprint() { + RecordingPlacer placer = new RecordingPlacer(null); + IrisObjectPlacement config = placement(); + config.setMode(ObjectPlaceMode.STILT); + config.setRotation(IrisObjectRotation.of(0, 90, 0)); + config.setTranslate(new IrisObjectTranslate().setX(4)); + + lineObject(3).place(0, ANCHOR_Y + 4, 0, placer, config, new RNG(2L), data); + + // Every bottom column reaches the ground after rotation and translation. + for (int z = -5; z <= -3; z++) { + assertSame(solid, placer.get(0, ANCHOR_Y, z)); + assertSame(solid, placer.get(0, ANCHOR_Y + 3, z)); + } + assertTrue(placer.writes().stream().allMatch(write -> write.x() == 0)); + } + + @Test + public void ceilingFlipsBeforeTranslationAndFillsUpward() { + RecordingPlacer placer = new RecordingPlacer(null); + placer.world.put("0:90:0", solid); + IrisObjectPlacement config = placement(); + config.setMode(ObjectPlaceMode.CEILING_HANG); + config.setTranslate(new IrisObjectTranslate().setY(3)); + config.setStiltSettings(new IrisStiltSettings().setOrganicJitter(0).setOrganicScratch(0)); + + boxObject(1, 3, 1).place(0, ANCHOR_Y, 0, placer, config, new RNG(2L), data); + + assertSame(solid, placer.get(0, 82, 0)); + assertSame(solid, placer.get(0, 89, 0)); + assertTrue(placer.writes().stream().noneMatch(write -> write.y() < 82 || write.y() >= 90)); + } + + @Test + public void organicStiltStopsAtTheFloor() { + RecordingPlacer placer = new RecordingPlacer(null); + placer.world.put("0:75:0", solid); + IrisObjectPlacement config = placement(); + config.setMode(ObjectPlaceMode.ORGANIC_STILT); + config.setStiltSettings(new IrisStiltSettings().setOrganicJitter(0).setOrganicScratch(0)); + + lineObject(1).place(0, ANCHOR_Y, 0, placer, config, new RNG(2L), data); + + for (int y = 76; y <= ANCHOR_Y; y++) { + assertSame(solid, placer.get(0, y, 0)); + } + assertTrue(placer.writes().stream().noneMatch(write -> write.y() <= 75)); + } + + @Test + public void erodeStiltResolvesItsOwnSampledAnchor() { + RecordingPlacer placer = new RecordingPlacer(null); + IrisObjectPlacement config = placement(); + config.setMode(ObjectPlaceMode.ERODE_STILT); + assertEquals(ANCHOR_Y, lineObject(1).place(0, -1, 0, placer, config, new RNG(2L), data)); + assertFalse(placer.writes().isEmpty()); + } + + @Test + public void explicitMinimumHeightAndFloatingDoNotNeedTerrainSampling() { + for (ObjectPlaceMode mode : List.of(ObjectPlaceMode.MIN_HEIGHT, ObjectPlaceMode.FAST_MIN_HEIGHT, + ObjectPlaceMode.FLOATING, ObjectPlaceMode.STRUCTURE_PIECE)) { + RecordingPlacer placer = new RecordingPlacer(null); + IrisObjectPlacement config = placement(); + config.setMode(mode); + assertEquals(ANCHOR_Y, lineObject(1).place(0, ANCHOR_Y, 0, placer, config, new RNG(2L), data)); + assertTrue(mode.toString(), placer.sampledColumns().isEmpty()); + } + } + + @Test + public void runnerUsesTheEnginePlanAndCompletesTheBlockPassBeforeAfterBlocks() { + RecordingPlacer placer = new RecordingPlacer(engine); + PlacementLifecycleBuilder builder = new PlacementLifecycleBuilder(); + ObjectPlaceMode.CENTER_HEIGHT.install(builder); + builder.add(new PlacementLifecycleDependency("test.offset"), PlacementStage.HEIGHT, + (context, state, ignored) -> state.y += 5, PlacementModuleAnchor.HEIGHT); + List finishedSizes = new ArrayList<>(); + builder.add(new PlacementLifecycleDependency("test.finished"), PlacementStage.AFTER_BLOCKS, + (context, state, ignored) -> finishedSizes.add(placer.writes().size())); + PlacementLifecycles plans = mock(PlacementLifecycles.class); + when(plans.get(ObjectPlaceMode.CENTER_HEIGHT)).thenReturn(builder.build()); + when(engine.getPlacementLifecycles()).thenReturn(plans); + + assertEquals(ANCHOR_Y + 5, lineObject(3).place(0, ANCHOR_Y, 0, placer, placement(), new RNG(2L), data)); + assertEquals(List.of(3), finishedSizes); + assertTrue(placer.writes().stream().allMatch(write -> write.y() == ANCHOR_Y + 5)); + } + + @Test + public void fromBottomKeepsItsAnchorWithoutSamplingTerrain() { + RecordingPlacer placer = new RecordingPlacer(null); + IrisObjectPlacement config = placement(); + config.setFromBottom(true); + assertEquals(2, lineObject(1).place(0, -1, 0, placer, config, new RNG(2L), data)); + assertTrue(placer.sampledColumns().isEmpty()); + } + + @Test + public void eligibilityGuardsRejectBeforeBoreAndOwnTheirForcePlaceExemptions() { + for (String reason : List.of("carving-anchor", "underwater-anchor", "cave-clearance", "fluid-height", "height-clamp")) { + RecordingPlacer placer = new RecordingPlacer(null); + IrisObjectPlacement config = placement().setBore(true).setSnow(0.1); + CarveResult cave = null; + int anchor = ANCHOR_Y; + switch (reason) { + case "carving-anchor" -> { + placer.carved = true; + config.setCarvingSupport(CarvingMode.SURFACE_ONLY); + } + case "underwater-anchor" -> { + placer.underwater = true; + anchor = -1; + } + case "cave-clearance" -> cave = new CarveResult(ANCHOR_Y, ANCHOR_Y + 1); + case "fluid-height" -> { + config.setUnderwater(true); + placer.fluidHeight = ANCHOR_Y; + } + case "height-clamp" -> config.getClamp().setMaximumHeight(ANCHOR_Y - 1); + } + PlacementState result = execute(config, anchor, placer, cave); + assertEquals(reason, result.getRejection()); + assertEquals(-1, result.heightOrRejected()); + assertTrue(reason, placer.writes().isEmpty()); + + config.setForcePlace(true); + assertFalse(reason, execute(config, anchor, placer, cave).isRejected()); + assertFalse(reason, placer.writes().isEmpty()); + } + } + + @Test + public void forcePlaceCannotBypassNativeProtectionButStructurePiecesCan() { + when(engine.getNativeStructureVolumes(anyInt(), anyInt(), anyInt(), anyInt())).thenReturn( + new KList<>(NativeStructureVolume.of("minecraft:village", 0, ANCHOR_Y, 0, 0, ANCHOR_Y, 0))); + RecordingPlacer placer = new RecordingPlacer(engine); + IrisObjectPlacement config = placement().setForcePlace(true).setBore(true).setSnow(0.1); + + assertEquals("native-structure", execute(config, ANCHOR_Y, placer, null).getRejection()); + assertTrue(placer.writes().isEmpty()); + + config.setMode(ObjectPlaceMode.STRUCTURE_PIECE); + assertEquals(ANCHOR_Y, execute(config, ANCHOR_Y, placer, null).heightOrRejected()); + assertFalse(placer.writes().isEmpty()); + } + + @Test + public void collisionRejectionPrecedesBoreAndAllowedObjectsOverrideForbiddenOnes() { + PlacedObject forbidden = new PlacedObject(null, object("forbidden"), 1, 0, 0); + when(engine.getObjectPlacement(anyInt(), anyInt(), anyInt())).thenReturn(forbidden); + RecordingPlacer placer = new RecordingPlacer(engine); + IrisObjectPlacement config = placement().setBore(true); + config.getForbiddenCollisions().add("forbidden"); + + assertEquals("object-collision", execute(config, ANCHOR_Y, placer, null).getRejection()); + assertTrue(placer.writes().isEmpty()); + + config.getAllowedCollisions().add("forbidden"); + assertFalse(execute(config, ANCHOR_Y, placer, null).isRejected()); + assertFalse(placer.writes().isEmpty()); + + config.getAllowedCollisions().clear(); + config.setForcePlace(true); + assertFalse(execute(config, ANCHOR_Y, new RecordingPlacer(engine), null).isRejected()); + } + + @Test + public void missingCollisionEngineFailsBeforeWrites() { + when(data.getEngine()).thenReturn(null); + RecordingPlacer placer = new RecordingPlacer(null); + IrisObjectPlacement config = placement().setBore(true); + config.getForbiddenCollisions().add("forbidden"); + assertEquals("Object placement requires active Iris data for collision settings.", + assertThrows(IllegalStateException.class, + () -> execute(config, ANCHOR_Y, placer, null)).getMessage()); + assertTrue(placer.writes().isEmpty()); + } + + @Test + public void vacuumAndSnowObserveOnlyWrittenBlocksAndFinishInOrder() { + RecordingPlacer placer = new RecordingPlacer(engine); + IrisObject object = new IrisObject(1, 3, 1); + object.setUnsigned(0, 0, 0, solid); + object.setUnsigned(0, 2, 0, schematicAir); + IrisObjectPlacement config = placement().setMode(ObjectPlaceMode.VACUUM).setSnow(0.1); + config.setTranslate(new IrisObjectTranslate().setY(3)); + config.setVacuumSettings(new IrisVacuumSettings().setRadius(1)); + + object.place(0, ANCHOR_Y, 0, placer, config, new RNG(2L), data); + + List center = placer.writes().stream().filter(write -> write.x() == 0 && write.z() == 0).toList(); + assertEquals(List.of(82, 81, 83), center.stream().map(BlockWrite::y).toList()); + assertSame(solid, center.get(0).state()); + assertSame(IrisObject.States.SNOW_LAYERS[0], center.get(2).state()); + } + + @Test + public void preparationPreservesRandomDrawsForPlacementAndLaterCallers() { + for (int range : List.of(-3, 0, 3)) { + RNG rng = new RNG(91); + RNG expected = new RNG(91); + expected.imax(); + expected.imax(); + expected.imax(); + int offset = range > 0 ? expected.i(0, range) : range < 0 ? expected.i(range, 0) : 0; + IrisObjectPlacement config = placement().setBore(true); + config.setTranslate(new IrisObjectTranslate().setYRandom(range)); + assertEquals(ANCHOR_Y + offset, + lineObject(1).place(0, ANCHOR_Y, 0, new RecordingPlacer(null), config, rng, data)); + assertEquals(expected.nextLong(), rng.nextLong()); + } + } + + @Test + public void heightmapPreparationKeepsItsSeedDrawBeforeRotation() { + RNG rng = new RNG(91); + RNG expected = new RNG(91); + expected.nextLong(); + expected.imax(); + expected.imax(); + expected.imax(); + RecordingPlacer placer = new RecordingPlacer(null); + IrisObjectPlacement config = placement(); + config.setHeightmap(new IrisNoiseGenerator(false).setOffsetY(93)); + + assertEquals(93, lineObject(1).place(0, -1, 0, placer, config, rng, data)); + assertTrue(placer.sampledColumns().isEmpty()); + assertEquals(expected.nextLong(), rng.nextLong()); + } + + @Test + @SuppressWarnings("unchecked") + public void slopeRejectionConsumesNoTransformRandomness() { + IrisComplex complex = mock(IrisComplex.class); + ProceduralStream slopes = mock(ProceduralStream.class); + when(engine.getComplex()).thenReturn(complex); + when(complex.getSlopeStream()).thenReturn(slopes); + when(slopes.get(anyDouble(), anyDouble())).thenReturn(0.5); + IrisObjectPlacement config = placement().setBore(true); + config.setSlopeCondition(new IrisSlopeClip(1, 2)); + RNG rng = new RNG(91); + RecordingPlacer placer = new RecordingPlacer(engine); + + assertEquals(-1, lineObject(1).place(0, ANCHOR_Y, 0, placer, config, rng, data)); + assertEquals(new RNG(91).nextLong(), rng.nextLong()); + assertTrue(placer.writes().isEmpty()); + } + + @Test + @SuppressWarnings("unchecked") + public void slopeRotationUsesAPerPlacementCopy() { + IrisComplex complex = mock(IrisComplex.class); + ProceduralStream heights = mock(ProceduralStream.class); + when(engine.getComplex()).thenReturn(complex); + when(complex.getHeightStream()).thenReturn(heights); + when(heights.get(anyDouble(), anyDouble())).thenAnswer(call -> call.getArgument(0) > 0 ? 70D : 80D); + IrisObjectPlacement config = placement().setRotateTowardsSlope(true); + IrisObjectRotation original = config.getRotation(); + RecordingPlacer placer = new RecordingPlacer(engine); + + lineObject(3).place(0, ANCHOR_Y, 0, placer, config, new RNG(2L), data); + + assertSame(original, config.getRotation()); + assertEquals(0, original.getYAxis().getMin(), 0); + assertEquals(3, placer.writes().size()); + assertTrue(placer.writes().stream().allMatch(write -> write.x() == 0)); + assertEquals(List.of(-1, 0, 1), placer.writes().stream().map(BlockWrite::z).sorted().toList()); + } + + private PlacementState execute(IrisObjectPlacement config, int y, RecordingPlacer placer, CarveResult cave) { + return PlacementLifecycles.defaults().get(config.getMode()).execute( + new PlacementContext(config, data, placer, cave, new RNG(2L), lineObject(1), 0, 0, y, null)); + } + private IrisObject lineObject(int width) { IrisObject object = new IrisObject(width, 1, 1); for (int x = 0; x < width; x++) { @@ -220,6 +501,9 @@ public class IrisObjectPlacementRunnerRegressionTest { private final Engine engine; private int failAfterWrites = Integer.MAX_VALUE; private boolean debugSmartBore; + private boolean carved; + private boolean underwater; + private int fluidHeight; private RecordingPlacer(Engine engine) { this.engine = engine; @@ -278,7 +562,7 @@ public class IrisObjectPlacementRunnerRegressionTest { @Override public boolean isCarved(int x, int y, int z) { - return false; + return carved; } @Override @@ -289,12 +573,12 @@ public class IrisObjectPlacementRunnerRegressionTest { @Override public boolean isUnderwater(int x, int z) { - return false; + return underwater; } @Override public int getFluidHeight() { - return 0; + return fluidHeight; } @Override diff --git a/core/src/test/java/art/arcane/iris/engine/object/IrisObjectStructurePieceAirTest.java b/core/src/test/java/art/arcane/iris/engine/object/IrisObjectStructurePieceAirTest.java index 0bb7242b4..4d2924922 100644 --- a/core/src/test/java/art/arcane/iris/engine/object/IrisObjectStructurePieceAirTest.java +++ b/core/src/test/java/art/arcane/iris/engine/object/IrisObjectStructurePieceAirTest.java @@ -8,20 +8,20 @@ import static org.junit.Assert.assertTrue; public class IrisObjectStructurePieceAirTest { @Test public void explicitAirPlacesOnlyForRawStructurePieces() { - assertTrue(IrisObjectPlacementRunner.shouldPlaceObjectBlock(true, true, false)); - assertFalse(IrisObjectPlacementRunner.shouldPlaceObjectBlock(false, true, false)); + assertTrue(ObjectBlockPass.shouldPlaceObjectBlock(true, true, false)); + assertFalse(ObjectBlockPass.shouldPlaceObjectBlock(false, true, false)); } @Test public void ordinaryObjectAirRemainsNondestructive() { - assertFalse(IrisObjectPlacementRunner.shouldPlaceObjectBlock(false, true, false)); - assertTrue(IrisObjectPlacementRunner.shouldPlaceObjectBlock(false, false, false)); + assertFalse(ObjectBlockPass.shouldPlaceObjectBlock(false, true, false)); + assertTrue(ObjectBlockPass.shouldPlaceObjectBlock(false, false, false)); } @Test public void vineReplacementRemainsRejectedForEveryPlacementMode() { - assertFalse(IrisObjectPlacementRunner.shouldPlaceObjectBlock(false, false, true)); - assertFalse(IrisObjectPlacementRunner.shouldPlaceObjectBlock(true, false, true)); - assertFalse(IrisObjectPlacementRunner.shouldPlaceObjectBlock(true, true, true)); + assertFalse(ObjectBlockPass.shouldPlaceObjectBlock(false, false, true)); + assertFalse(ObjectBlockPass.shouldPlaceObjectBlock(true, false, true)); + assertFalse(ObjectBlockPass.shouldPlaceObjectBlock(true, true, true)); } } diff --git a/core/src/test/java/art/arcane/iris/engine/object/IrisObjectSurfaceSupportPlacementTest.java b/core/src/test/java/art/arcane/iris/engine/object/IrisObjectSurfaceSupportPlacementTest.java index 08e8050c6..5a226d733 100644 --- a/core/src/test/java/art/arcane/iris/engine/object/IrisObjectSurfaceSupportPlacementTest.java +++ b/core/src/test/java/art/arcane/iris/engine/object/IrisObjectSurfaceSupportPlacementTest.java @@ -38,9 +38,20 @@ public class IrisObjectSurfaceSupportPlacementTest { @Before public void bindPlatform() { IrisPlatforms.unbind(); - PlatformBlockState block = mock(PlatformBlockState.class); PlatformRegistries registries = mock(PlatformRegistries.class); - when(registries.block(anyString())).thenReturn(block); + // IrisObject caches built-in states across test fixtures; every registry answer must be usable. + Map registryStates = new HashMap<>(); + when(registries.block(anyString())).thenAnswer(invocation -> { + String key = invocation.getArgument(0).toLowerCase(java.util.Locale.ROOT); + return registryStates.computeIfAbsent(key, value -> { + PlatformBlockState block = mock(PlatformBlockState.class); + when(block.key()).thenReturn(value); + when(block.materialKey()).thenReturn(value.split("\\[", 2)[0]); + when(block.isSolid()).thenReturn(!value.contains("air")); + when(block.isOccluding()).thenReturn(!value.contains("air")); + return block; + }); + }); IrisPlatform platform = mock(IrisPlatform.class); when(platform.registries()).thenReturn(registries); IrisPlatforms.bind(platform); diff --git a/core/src/test/java/art/arcane/iris/engine/object/NativeStructureObjectVetoTest.java b/core/src/test/java/art/arcane/iris/engine/object/NativeStructureObjectVetoTest.java index f3f94280b..4fb4dd4b2 100644 --- a/core/src/test/java/art/arcane/iris/engine/object/NativeStructureObjectVetoTest.java +++ b/core/src/test/java/art/arcane/iris/engine/object/NativeStructureObjectVetoTest.java @@ -16,7 +16,9 @@ import org.junit.Before; import org.junit.Test; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -36,9 +38,20 @@ public class NativeStructureObjectVetoTest { @Before public void bindPlatform() { IrisPlatforms.unbind(); - PlatformBlockState block = mock(PlatformBlockState.class); PlatformRegistries registries = mock(PlatformRegistries.class); - when(registries.block(anyString())).thenReturn(block); + // IrisObject caches built-in states across test fixtures; every registry answer must be usable. + Map registryStates = new HashMap<>(); + when(registries.block(anyString())).thenAnswer(invocation -> { + String key = invocation.getArgument(0).toLowerCase(java.util.Locale.ROOT); + return registryStates.computeIfAbsent(key, value -> { + PlatformBlockState block = mock(PlatformBlockState.class); + when(block.key()).thenReturn(value); + when(block.materialKey()).thenReturn(value.split("\\[", 2)[0]); + when(block.isSolid()).thenReturn(!value.contains("air")); + when(block.isOccluding()).thenReturn(!value.contains("air")); + return block; + }); + }); IrisPlatform platform = mock(IrisPlatform.class); when(platform.registries()).thenReturn(registries); IrisPlatforms.bind(platform); diff --git a/core/src/test/java/art/arcane/iris/engine/object/PlacementLifecycleTest.java b/core/src/test/java/art/arcane/iris/engine/object/PlacementLifecycleTest.java new file mode 100644 index 000000000..f39d05b15 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/object/PlacementLifecycleTest.java @@ -0,0 +1,200 @@ +package art.arcane.iris.engine.object; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.util.common.math.Vector3i; +import art.arcane.volmlib.util.math.RNG; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +public class PlacementLifecycleTest { + private static PlacementLifecycleDependency id(String name) { + return new PlacementLifecycleDependency(name); + } + + @Test + public void resolvesDependenciesAcrossModulesRegardlessOfInstallOrder() { + List calls = new ArrayList<>(); + PlacementModule consumer = builder -> builder.add(id("consumer"), PlacementStage.HEIGHT, + (context, state, ignored) -> calls.add("consumer"), id("provider")); + PlacementModule provider = builder -> builder.add(id("provider"), PlacementStage.HEIGHT, + (context, state, ignored) -> calls.add("provider")); + PlacementLifecycleBuilder builder = new PlacementLifecycleBuilder(); + consumer.install(builder); + provider.install(builder); + builder.add(id("independent"), PlacementStage.HEIGHT, + (context, state, ignored) -> calls.add("independent")); + + PlacementLifecycle plan = builder.build(); + assertTrue(calls.isEmpty()); + plan.run(PlacementStage.HEIGHT, null, new PlacementState(0, null), null); + assertEquals(List.of("provider", "consumer", "independent"), calls); + } + + @Test + public void rejectsMissingDuplicateCyclicAndBackwardDependencies() { + PlacementLifecycleBuilder missing = new PlacementLifecycleBuilder(); + missing.add(id("stilt"), PlacementStage.AFTER_BLOCKS, (c, s, v) -> {}, id("bounds")); + String message = assertThrows(IllegalArgumentException.class, missing::build).getMessage(); + assertTrue(message.contains("stilt")); + assertTrue(message.contains("bounds")); + + PlacementLifecycleBuilder duplicate = new PlacementLifecycleBuilder(); + duplicate.add(id("a"), PlacementStage.HEIGHT, (c, s, v) -> {}); + assertThrows(IllegalArgumentException.class, + () -> duplicate.add(id("a"), PlacementStage.HEIGHT, (c, s, v) -> {})); + + PlacementLifecycleBuilder cyclic = new PlacementLifecycleBuilder(); + cyclic.add(id("a"), PlacementStage.HEIGHT, (c, s, v) -> {}, id("b")); + cyclic.add(id("b"), PlacementStage.HEIGHT, (c, s, v) -> {}, id("a")); + message = assertThrows(IllegalArgumentException.class, cyclic::build).getMessage(); + assertTrue(message.contains("cycle")); + assertTrue(message.contains("a")); + assertTrue(message.contains("b")); + + PlacementLifecycleBuilder backward = new PlacementLifecycleBuilder(); + backward.add(id("height"), PlacementStage.HEIGHT, (c, s, v) -> {}, id("fill")); + backward.add(id("fill"), PlacementStage.AFTER_BLOCKS, (c, s, v) -> {}); + assertTrue(assertThrows(IllegalArgumentException.class, backward::build) + .getMessage().contains("later step")); + } + + @Test + public void rejectsSelfDependencyAndAcceptsRepeatedPrerequisite() { + PlacementLifecycleBuilder self = new PlacementLifecycleBuilder(); + self.add(id("self"), PlacementStage.HEIGHT, (c, s, v) -> {}, id("self")); + assertThrows(IllegalArgumentException.class, self::build); + + PlacementLifecycleBuilder repeated = new PlacementLifecycleBuilder(); + repeated.add(id("a"), PlacementStage.HEIGHT, (c, s, v) -> s.y++); + repeated.add(id("b"), PlacementStage.HEIGHT, (c, s, v) -> s.y *= 2, id("a"), id("a")); + PlacementState state = new PlacementState(2, null); + repeated.build().run(PlacementStage.HEIGHT, null, state, null); + assertEquals(6, state.y); + } + + @Test + public void plansAreSnapshotsAndFailuresPropagateWithoutRunningDependents() { + List calls = new ArrayList<>(); + PlacementLifecycleBuilder builder = new PlacementLifecycleBuilder(); + builder.add(id("first"), PlacementStage.HEIGHT, (c, s, v) -> calls.add("first")); + PlacementLifecycle original = builder.build(); + IllegalStateException failure = new IllegalStateException("failed placement"); + builder.add(id("failure"), PlacementStage.HEIGHT, (c, s, v) -> { throw failure; }, id("first")); + builder.add(id("dependent"), PlacementStage.HEIGHT, (c, s, v) -> calls.add("dependent"), id("failure")); + original.run(PlacementStage.HEIGHT, null, new PlacementState(0, null), null); + assertEquals(List.of("first"), calls); + assertSame(failure, assertThrows(IllegalStateException.class, + () -> builder.build().run(PlacementStage.HEIGHT, null, new PlacementState(0, null), null))); + assertEquals(List.of("first", "first"), calls); + } + + @Test + public void everyModeResolvesAndRuntimePlansAreIndependent() { + PlacementLifecycles first = PlacementLifecycles.resolve(); + PlacementLifecycles second = PlacementLifecycles.resolve(); + for (ObjectPlaceMode mode : ObjectPlaceMode.values()) { + assertNotNull(first.get(mode)); + assertNotSame(first.get(mode), second.get(mode)); + } + } + + @Test + public void resolvesLongDependencyChainsWithoutRecursiveTraversal() { + PlacementLifecycleBuilder builder = new PlacementLifecycleBuilder(); + for (int i = 9999; i >= 0; i--) { + builder.add(id("step-" + i), PlacementStage.HEIGHT, (c, s, v) -> s.y++, + i == 0 ? new PlacementLifecycleDependency[0] + : new PlacementLifecycleDependency[]{id("step-" + (i - 1))}); + } + PlacementState state = new PlacementState(0, null); + builder.build().run(PlacementStage.HEIGHT, null, state, null); + assertEquals(10000, state.y); + } + + @Test + public void sharedHeightPlanKeepsConcurrentPlacementStateSeparate() throws Exception { + PlacementLifecycleBuilder builder = new PlacementLifecycleBuilder(); + new PlacementModulePreparation().install(builder); + new PlacementModuleSlope().install(builder); + new PlacementModuleHeight(PlacementModuleHeight.Mode.MAX, false).install(builder); + PlacementLifecycle plan = builder.build(); + CountDownLatch sampled = new CountDownLatch(2); + try (var executor = Executors.newFixedThreadPool(2)) { + var first = executor.submit(() -> sample(plan, 10, sampled)); + var second = executor.submit(() -> sample(plan, 100, sampled)); + assertEquals(11, (int) first.get(10, TimeUnit.SECONDS)); + assertEquals(101, (int) second.get(10, TimeUnit.SECONDS)); + } + } + + private int sample(PlacementLifecycle plan, int x, CountDownLatch sampled) throws Exception { + IObjectPlacer placer = mock(IObjectPlacer.class); + when(placer.getHighest(anyInt(), anyInt(), any(), anyBoolean())).thenAnswer(call -> { + sampled.countDown(); + assertTrue(sampled.await(5, TimeUnit.SECONDS)); + return call.getArgument(0); + }); + IrisObjectPlacement config = new IrisObjectPlacement().setForcePlace(true); + IrisObject object = mock(IrisObject.class); + when(object.getCenter()).thenReturn(new Vector3i(1, 0, 0)); + when(object.getW()).thenReturn(3); + when(object.getH()).thenReturn(1); + when(object.getD()).thenReturn(1); + PlacementContext context = new PlacementContext(config, mock(IrisData.class), placer, null, + new RNG(1), object, x, 0, -1, null); + PlacementState state = new PlacementState(context); + plan.run(PlacementStage.PREPARE, context, state, null); + plan.run(PlacementStage.HEIGHT, context, state, null); + return state.y; + } + + @Test + public void guardOwnsTheForcePlaceExemption() { + PlacementLifecycleBuilder builder = new PlacementLifecycleBuilder(); + builder.add(id("guard"), PlacementStage.HEIGHT, (c, s, v) -> { + if (!s.config.isForcePlace()) { + s.reject("guard"); + } + }); + builder.add(id("dependent"), PlacementStage.HEIGHT, (c, s, v) -> s.y = 99, id("guard")); + PlacementLifecycle plan = builder.build(); + IrisObjectPlacement config = new IrisObjectPlacement(); + PlacementContext context = new PlacementContext(config, mock(IrisData.class), mock(IObjectPlacer.class), + null, new RNG(1), mock(IrisObject.class), 0, 0, -1, null); + PlacementState rejected = new PlacementState(context); + plan.run(PlacementStage.HEIGHT, context, rejected, null); + assertEquals(-1, rejected.heightOrRejected()); + assertEquals("guard", rejected.getRejection()); + config.setForcePlace(true); + PlacementState forced = new PlacementState(context); + plan.run(PlacementStage.HEIGHT, context, forced, null); + assertEquals(99, forced.y); + } + + @Test + public void rejectionIsTerminalAcrossPhasesEvenWithForcePlace() { + PlacementLifecycleBuilder builder = new PlacementLifecycleBuilder(); + List calls = new ArrayList<>(); + builder.add(id("reject"), PlacementStage.VALIDATE, (c, s, v) -> s.reject("protected")); + builder.add(id("bore"), PlacementStage.BEFORE_BLOCKS, (c, s, v) -> calls.add("bore")); + builder.add(id("blocks"), PlacementStage.BLOCKS, (c, s, v) -> calls.add("blocks")); + builder.add(id("finish"), PlacementStage.AFTER_BLOCKS, (c, s, v) -> calls.add("finish")); + PlacementContext context = new PlacementContext(new IrisObjectPlacement().setForcePlace(true), + mock(IrisData.class), mock(IObjectPlacer.class), null, new RNG(1), + mock(IrisObject.class), 0, 0, 80, null); + PlacementState result = builder.build().execute(context); + assertEquals(-1, result.heightOrRejected()); + result.reject("later reason"); + assertEquals("protected", result.getRejection()); + assertTrue(calls.isEmpty()); + } +}