diff --git a/builtin-modules.txt b/builtin-modules.txt index 824782905..41cb85591 100644 --- a/builtin-modules.txt +++ b/builtin-modules.txt @@ -18,3 +18,14 @@ module art.arcane.iris.engine.modifier.PostModule include art/arcane/iris/engine/modifier/SurfaceSmoothing*.class module art.arcane.iris.engine.modifier.PerfectionModule module art.arcane.iris.engine.modifier.MatterModule +module art.arcane.iris.engine.mantle.components.ObjectModule +include art/arcane/iris/engine/mantle/components/ObjectPlacing*.class +include art/arcane/iris/engine/mantle/components/ChunkObjectPlacing*.class +include art/arcane/iris/engine/mantle/components/CaveAnchors*.class +include art/arcane/iris/engine/mantle/components/CaveSettings*.class +include art/arcane/iris/engine/mantle/components/CaveRejects*.class +include art/arcane/iris/engine/mantle/components/EffectivePlacements*.class +include art/arcane/iris/engine/mantle/components/PlacementReach*.class +include art/arcane/iris/engine/mantle/components/ObjectWarmUp*.class +include art/arcane/iris/engine/mantle/components/ObjectLocating*.class +include art/arcane/iris/engine/mantle/components/TreeGrowing*.class diff --git a/src/main/java/art/arcane/iris/builtin/objects/CarvedSpace.java b/src/main/java/art/arcane/iris/builtin/objects/CarvedSpace.java new file mode 100644 index 000000000..6ee201b23 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/CarvedSpace.java @@ -0,0 +1,33 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.objects; + +import java.util.Optional; + +/** The voids the cave carver planned in the mantle around the chunk being placed, which cave objects anchor in. */ +public interface CarvedSpace { + /** Whether the position is carved. */ + boolean isCarved(int x, int y, int z); + + /** Whether each height from 0 up to {@code height} is carved at the column, 1 for carved and 0 for not. */ + byte[] column(int x, int z, int height); + + /** The void at the position; empty where nothing was carved. */ + Optional cavernAt(int x, int y, int z); +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/CavePlacement.java b/src/main/java/art/arcane/iris/builtin/objects/CavePlacement.java new file mode 100644 index 000000000..221ba5b30 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/CavePlacement.java @@ -0,0 +1,40 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.objects; + +/** + * The outcome of placing an object in a cave. + * + * @param resultY the height the object was placed at, negative when the placement rejected it + * @param commit what became of the blocks the object wrote + */ +public record CavePlacement(int resultY, Commit commit) { + public enum Commit { + /** The blocks were written. */ + COMMITTED, + /** The object wrote no blocks, or the placement was rejected. */ + EMPTY, + /** Some block lay outside the cave, so nothing was written. */ + REJECTED_BOUNDS + } + + public boolean wroteBlocks() { + return commit == Commit.COMMITTED; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/Cavern.java b/src/main/java/art/arcane/iris/builtin/objects/Cavern.java new file mode 100644 index 000000000..8a524fea3 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/Cavern.java @@ -0,0 +1,29 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.objects; + +/** + * A carved void of the mantle, as the cave carver left it. + * + * @param air whether the void holds air + * @param liquid the carver's liquid code for the void; {@link #FORCED_AIR_LIQUID} means air that stays air + */ +public record Cavern(boolean air, byte liquid) { + public static final byte FORCED_AIR_LIQUID = 3; +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectChunk.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectChunk.java new file mode 100644 index 000000000..822163a0f --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectChunk.java @@ -0,0 +1,56 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.objects; + +import art.arcane.volmlib.util.math.RNG; + +/** + * The chunk whose mantle {@code iris:objects} is placing into: the one place objects are written. Every placement here + * runs Iris's placement stages, so it is what a pack's {@code objects} get when they are placed anywhere. Reached through + * {@link ObjectHost#chunk()} from a mantle stage. + */ +public interface ObjectChunk { + /** The voids the cave carver planned around the chunk. */ + CarvedSpace carved(); + + /** Whether the golden-debug switch is on for the chunk, which logs every decision of its placements. */ + boolean goldenDebug(int chunkX, int chunkZ); + + /** + * Places an object on the terrain, where it sits at the height its place mode finds. + * + * @param goldenTag logs the placer's questions under this tag, or null to leave them + * @return the height the object was placed at, negative when the placement rejected it + */ + int placeOnSurface(PlaceableObject object, int x, int z, PlacementSource placement, PlacementChanges changes, + PlacementTags tags, RNG rng, String goldenTag); + + /** + * Places an object in a cave, anchored at {@code anchorY}, and writes it only when all of it lies inside the cave and + * no deeper than {@code minDepthBelowSurface} under the surface. + * + * @param goldenTag logs the placer's questions under this tag, or null to leave them + */ + CavePlacement placeInCave(PlaceableObject object, int x, int anchorY, int z, PlacementSource placement, PlacementChanges changes, + int minDepthBelowSurface, PlacementTags tags, RNG rng, String goldenTag); + + /** Places an object at a given height, which the terrain stacked above uses for the objects hung from it. */ + int placeUpper(PlaceableObject object, int x, int anchorY, int z, ObjectPlacement placement, PlacementChanges changes, + PlacementTags tags, RNG rng); +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectHost.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectHost.java new file mode 100644 index 000000000..ef42019eb --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectHost.java @@ -0,0 +1,125 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.objects; + +import art.arcane.volmlib.util.math.RNG; +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.FeatureSettings; +import com.volmit.config.PackSettings; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; + +import java.util.List; +import java.util.Optional; + +/** + * What {@code iris:objects} asks of Iris: the objects of the pack, how Iris scales and places them, and the layout around + * a world position. Iris's worlds implement it; a module reaches it with {@link #of}. Nothing here hands out the engine. + */ +public interface ObjectHost { + /** The host of the world {@code settings} are the pack's of, which must be a world Iris generates. */ + static ObjectHost of(PackSettings settings) { + if (settings instanceof Source source) { + return source.objects(); + } + throw new IllegalArgumentException("Built-in modules generate Iris's own worlds, not " + settings); + } + + /** The host of {@code world}, which must be a world Iris generates. */ + static ObjectHost of(PackWorld world) { + if (world instanceof Source source) { + return source.objects(); + } + throw new IllegalArgumentException("Built-in modules generate Iris's own worlds, not " + world); + } + + /** Whether Iris's debug setting is on. */ + boolean debugging(); + + /** The height, above the dimension's bottom, up to which caves are filled with lava. */ + int caveLavaHeight(); + + /** The height of the dimension's fluid. */ + int fluidHeight(); + + /** The settings that apply at a world column, for work outside a chunk's generation. */ + FeatureSettings columnSettings(); + + /** The random a chunk's objects are placed with: the same for the same chunk of the same world. */ + RNG chunkRandom(int chunkX, int chunkZ); + + /** The chunk whose objects are being placed on this thread. */ + ObjectChunk chunk(); + + /** The object of the pack that {@code key} names. */ + Optional object(String key); + + /** An object of the placement, picked with {@code rng} and scaled the way the placement scales it; empty when it has none. */ + Optional pickScaled(ObjectPlacement placement, RNG rng); + + /** How many objects the placement places at the column, when its chance check passes. */ + int density(ObjectPlacement placement, RNG rng, double x, double z); + + /** The size of the pack's object, read without loading its blocks; empty when the pack has no such object. */ + Optional sizeOf(String objectKey); + + /** Builds what placing the placement would build on first use, so the first chunk to place it does not wait. */ + void warm(ObjectPlacement placement, RNG rng); + + /** The procedural objects {@code settings} declare, made placeable once. */ + List procedural(ProceduralObjectSettings settings); + + /** The object settings of the biome and the region of the dimension stacked above, at the column; none where nothing sits above. */ + Optional upperObjects(int worldX, int worldZ); + + /** Places the object into {@code sink}, which is outside any chunk's generation, such as a growing sapling's tree. */ + int placeInto(PlaceableObject object, int x, int y, int z, ObjectPlacement placement, ObjectSink sink, RNG rng); + + /** The region at the column. */ + ResourceId regionAt(int worldX, int worldZ); + + /** The surface biome at the column. */ + ResourceId surfaceBiomeAt(int worldX, int worldZ); + + /** The biome at the position, which is the cave biome underground. */ + ResourceId biomeAt(int worldX, int y, int worldZ); + + /** The settings the biome declares itself, whichever column it is found at; empty when it declares none. */ + Optional biomeDeclaration(ResourceId biome, Class type); + + /** The settings the region declares itself; empty when it declares none. */ + Optional regionDeclaration(ResourceId region, Class type); + + /** Every region and every reachable biome that declares the settings, by the key the pack knows it by, regions first. */ + List> declarations(Class type); + + /** What the dimension stacked above declares to place at a column, where each is null when its level declares none. */ + record UpperObjects(ObjectSettings biome, ObjectSettings region, String biomeKey, String regionKey) { + } + + /** Iris's worlds answer for their objects. */ + interface Source { + ObjectHost objects(); + } + + /** One region's or biome's declaration of settings. */ + record Declaration(Target level, String key, F settings) { + } +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java index d0fc5c6e4..04479458a 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java @@ -65,7 +65,7 @@ import java.util.Optional; @Snippet("object-placer") @Desc("Represents an iris object placer. It places objects.") @JsonAdapter(ObjectPlacement.KeepingItsJson.class) -public final class ObjectPlacement { +public final class ObjectPlacement implements PlacementSource { private static final int DEFAULT_SURFACE_SUPPORT_BUFFER = 2; private static final int DEFAULT_SURFACE_SUPPORT_DEPTH = 2; @@ -190,6 +190,7 @@ public final class ObjectPlacement { return place == null ? List.of() : Collections.unmodifiableList(place); } + @Override public double chance() { return chance; } @@ -227,6 +228,7 @@ public final class ObjectPlacement { return warp; } + @Override public ObjectPlaceMode mode() { return mode; } @@ -235,18 +237,22 @@ public final class ObjectPlacement { return Optional.ofNullable(vacuumSettings); } + @Override public CarvingMode carvingSupport() { return carvingSupport; } + @Override public CaveAnchorMode caveAnchorMode() { return caveAnchorMode; } + @Override public boolean underwater() { return underwater; } + @Override public boolean isDolphinTarget() { return isDolphinTarget; } @@ -255,10 +261,12 @@ public final class ObjectPlacement { return forcePlace; } + @Override public boolean requireSurfaceSupport() { return requireSurfaceSupport; } + @Override public int surfaceSupportBuffer() { return surfaceSupportBuffer; } diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectSink.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectSink.java new file mode 100644 index 000000000..777ef63e4 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectSink.java @@ -0,0 +1,34 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.objects; + +import com.volmit.block.BlockState; + +/** Where an object placed through {@link ObjectHost#placeInto} reads the world around it and writes its blocks. */ +public interface ObjectSink { + /** The height of the highest block at the column; {@code ignoreFluid} leaves out the fluid above the ground. */ + int highest(int x, int z, boolean ignoreFluid); + + BlockState get(int x, int y, int z); + + void set(int x, int y, int z, BlockState state); + + /** The height of the dimension's fluid. */ + int fluidHeight(); +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectSize.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectSize.java new file mode 100644 index 000000000..62a0119dc --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectSize.java @@ -0,0 +1,23 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.objects; + +/** The size of an object, in blocks. */ +public record ObjectSize(int width, int height, int depth) { +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/PlaceableObject.java b/src/main/java/art/arcane/iris/builtin/objects/PlaceableObject.java new file mode 100644 index 000000000..8aafb4eab --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/PlaceableObject.java @@ -0,0 +1,34 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.objects; + +/** An object of the pack, or one made for a placement, that {@link ObjectHost} can place; Iris's own object class is one. */ +public interface PlaceableObject { + /** The key the pack loads the object by, or the key a procedural object is given; null for an object made in code. */ + String key(); + + /** How wide the object is, in blocks. */ + int width(); + + /** How tall the object is, in blocks. */ + int height(); + + /** How deep the object is, in blocks. */ + int depth(); +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/PlacementChanges.java b/src/main/java/art/arcane/iris/builtin/objects/PlacementChanges.java new file mode 100644 index 000000000..38348fa33 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/PlacementChanges.java @@ -0,0 +1,69 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.objects; + +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.carve.CarvingMode; + +import java.util.List; + +/** + * How a placement differs from the settings it was read from, when {@code iris:objects} places it: a field that is + * null is left as the settings have it. + * + * @param place the objects the placement names, replacing the settings' + * @param mode the place mode + * @param upsideDown whether the object is turned over, for the objects hung from the terrain stacked above + * @param carvingSupport where the placement may place + * @param requireSurfaceSupport whether a surface placement needs solid ground under it + * @param surfaceSupportBuffer the buffer of solid ground around the object's base + * @param forcePlace whether the placement ignores the placement restrictions + */ +public record PlacementChanges(List place, ObjectPlaceMode mode, Boolean upsideDown, CarvingMode carvingSupport, + Boolean requireSurfaceSupport, Integer surfaceSupportBuffer, Boolean forcePlace) { + public static final PlacementChanges NONE = new PlacementChanges(null, null, null, null, null, null, null); + + public boolean isNone() { + return this.equals(NONE); + } + + public PlacementChanges withPlace(List place) { + return new PlacementChanges(place, mode, upsideDown, carvingSupport, requireSurfaceSupport, surfaceSupportBuffer, forcePlace); + } + + public PlacementChanges withMode(ObjectPlaceMode mode) { + return new PlacementChanges(place, mode, upsideDown, carvingSupport, requireSurfaceSupport, surfaceSupportBuffer, forcePlace); + } + + public PlacementChanges withUpsideDown(boolean upsideDown) { + return new PlacementChanges(place, mode, upsideDown, carvingSupport, requireSurfaceSupport, surfaceSupportBuffer, forcePlace); + } + + public PlacementChanges withCarvingSupport(CarvingMode carvingSupport) { + return new PlacementChanges(place, mode, upsideDown, carvingSupport, requireSurfaceSupport, surfaceSupportBuffer, forcePlace); + } + + public PlacementChanges withSurfaceSupport(boolean required, int buffer) { + return new PlacementChanges(place, mode, upsideDown, carvingSupport, required, buffer, forcePlace); + } + + public PlacementChanges withForcePlace(boolean forcePlace) { + return new PlacementChanges(place, mode, upsideDown, carvingSupport, requireSurfaceSupport, surfaceSupportBuffer, forcePlace); + } +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/PlacementSource.java b/src/main/java/art/arcane/iris/builtin/objects/PlacementSource.java new file mode 100644 index 000000000..96a33efd0 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/PlacementSource.java @@ -0,0 +1,42 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.objects; + +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.carve.CarvingMode; +import art.arcane.iris.builtin.carve.CaveAnchorMode; + +/** What a placement is read from: an object placement of a biome or region, or a procedural object. */ +public interface PlacementSource { + double chance(); + + ObjectPlaceMode mode(); + + CarvingMode carvingSupport(); + + CaveAnchorMode caveAnchorMode(); + + boolean underwater(); + + boolean requireSurfaceSupport(); + + int surfaceSupportBuffer(); + + boolean isDolphinTarget(); +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/PlacementTags.java b/src/main/java/art/arcane/iris/builtin/objects/PlacementTags.java new file mode 100644 index 000000000..cefef139c --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/PlacementTags.java @@ -0,0 +1,29 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.objects; + +/** + * What a placement writes into the mantle besides the blocks, beside each block of the object. + * + * @param marker the placement marker to write beside every block the object places, or null for none + * @param treeMaterial whether the block is also written as the tree material the mantle keeps for felling and growth + * @param buriedTreasure whether storage chests among the blocks are marked as buried treasure + */ +public record PlacementTags(String marker, boolean treeMaterial, boolean buriedTreasure) { +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/ProceduralPlacement.java b/src/main/java/art/arcane/iris/builtin/objects/ProceduralPlacement.java new file mode 100644 index 000000000..ee0e55fab --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/ProceduralPlacement.java @@ -0,0 +1,88 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.builtin.objects; + +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.carve.CarvingMode; +import art.arcane.iris.builtin.carve.CaveAnchorMode; +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.iris.builtin.prepare.ObjectTranslate; +import art.arcane.iris.builtin.vacuum.VacuumSettings; +import art.arcane.volmlib.util.math.RNG; + +import java.util.List; +import java.util.Optional; + +/** + * A procedural object of a region or biome made placeable: a pool of variants Iris bakes once from its settings, and + * the options it is scattered with, like an object placement. + */ +public interface ProceduralPlacement extends PlacementSource { + String name(); + + @Override + double chance(); + + int density(); + + /** Whether the variants are meant to look like the real thing, so leaves decay. */ + boolean plausible(); + + /** Whether the variants are trees. */ + boolean tree(); + + @Override + ObjectPlaceMode mode(); + + @Override + CarvingMode carvingSupport(); + + @Override + CaveAnchorMode caveAnchorMode(); + + @Override + boolean underwater(); + + @Override + default boolean requireSurfaceSupport() { + return true; + } + + @Override + default int surfaceSupportBuffer() { + return 2; + } + + @Override + default boolean isDolphinTarget() { + return false; + } + + ObjectRotation rotation(); + + ObjectTranslate translate(); + + Optional vacuumSettings(); + + /** One of the variants, picked with {@code rng}; empty when none baked. */ + Optional variant(RNG rng); + + /** Every variant, baked on first use. */ + List variants(); +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/tree/Tree.java b/src/main/java/art/arcane/iris/builtin/objects/tree/Tree.java index bc3fdbdab..49ff9b31b 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/tree/Tree.java +++ b/src/main/java/art/arcane/iris/builtin/objects/tree/Tree.java @@ -257,6 +257,14 @@ public final class Tree { public Tree() { } + /** The key the variant {@code index} of the tree named {@code name} is loaded under, which placement markers and the sapling tree list name. */ + public static String variantLoadKey(String name, int index) { + if (index < 0) { + throw new IllegalArgumentException("index must not be negative"); + } + return "procedural/tree/" + name + "#" + index; + } + public String name() { return name; } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveAnchors.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveAnchors.java new file mode 100644 index 000000000..71cabe0de --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveAnchors.java @@ -0,0 +1,228 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.builtin.carve.CaveAnchorMode; +import art.arcane.iris.builtin.objects.CarvedSpace; +import art.arcane.iris.builtin.objects.Cavern; +import art.arcane.volmlib.util.cache.CacheKey; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.resource.ResourceId; +import com.volmit.world.BiomeSample; +import com.volmit.world.TerrainSampler; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** Finds the places in the carved caves of a chunk where a cave object may be anchored, remembering what it scanned. */ +final class CaveAnchors { + private static final int BEDROCK_CLEARANCE = 6; + private static final int SOLID_NEIGHBOR_REACH_BLOCKS = 3; + private static final int MAX_PACKED_SETTING = 65535; + + private final CarvedSpace carved; + private final TerrainSampler terrain; + private final int worldHeight; + private final int caveLavaHeight; + private final Map>> anchorsBySetting = new HashMap<>(); + private final Map carvedColumns = new HashMap<>(); + private final Map surfaceHeights = new HashMap<>(); + + CaveAnchors(CarvedSpace carved, TerrainSampler terrain, int worldHeight, int caveLavaHeight) { + this.carved = carved; + this.terrain = terrain; + this.worldHeight = worldHeight; + this.caveLavaHeight = caveLavaHeight; + } + + /** A position to anchor a cave object at. */ + record Anchor(int x, int y, int z) { + } + + /** How a cave placement looks for its anchor. */ + record Search(CaveAnchorMode mode, int scanStep, int minDepthBelowSurface, int attempts) { + } + + /** + * Looks for an anchor in the chunk whose first block is {@code minX}, {@code minZ}: a column picked at random, a height in + * it picked among those the mode accepts, tried up to the search's attempts. + * + * @param expectedCaveBiome the cave biome the anchor has to be in, or null for any + * @return the anchor, or null when no attempt found one + */ + Anchor find(RNG rng, int minX, int minZ, Search search, ResourceId expectedCaveBiome, boolean underwater) { + for (int attempt = 0; attempt < search.attempts(); attempt++) { + int candidateX = rng.i(minX, minX + 16); + int candidateZ = rng.i(minZ, minZ + 16); + int candidateY = anchorY(rng, candidateX, candidateZ, search); + if (candidateY < 0 + || biomeConflicts(candidateX, candidateY, candidateZ, expectedCaveBiome) + || !acceptsFluid(underwater, carved.cavernAt(candidateX, candidateY, candidateZ), candidateY, caveLavaHeight)) { + continue; + } + return new Anchor(candidateX, candidateY, candidateZ); + } + return null; + } + + static boolean acceptsFluid(boolean underwater, Optional cavern, int y, int lavaHeight) { + if (cavern.isEmpty()) { + return false; + } + if (underwater || cavern.get().liquid() == Cavern.FORCED_AIR_LIQUID) { + return true; + } + return cavern.get().air() && y > lavaHeight; + } + + /** One above the highest height an anchor may sit at, or 0 when none may. */ + static int scanUpperBound(int worldHeight, int surfaceY, int minDepthBelowSurface) { + int maxAnchorY = maxBuriedY(worldHeight, surfaceY, minDepthBelowSurface); + if (maxAnchorY <= 1) { + return 0; + } + return maxAnchorY + 1; + } + + /** The highest height a cave object may reach: no deeper than {@code minDepthBelowSurface} under the surface. */ + static int maxBuriedY(int worldHeight, int surfaceY, int minDepthBelowSurface) { + return Math.min(worldHeight - 1, surfaceY - Math.max(0, minDepthBelowSurface)); + } + + /** Whether the cave biome at the position is not the one expected, nor the surface biome the cave sits under. */ + private boolean biomeConflicts(int x, int y, int z, ResourceId expectedCaveBiome) { + if (expectedCaveBiome == null) { + return false; + } + BiomeSample sample = terrain.biome(x, y, z); + return biomeConflicts(sample.caveBiome().orElse(null), sample.surfaceBiome(), expectedCaveBiome); + } + + static boolean biomeConflicts(ResourceId at, ResourceId surface, ResourceId expectedCaveBiome) { + if (expectedCaveBiome == null || at == null) { + return false; + } + if (at.equals(expectedCaveBiome)) { + return false; + } + return surface == null || !at.equals(surface); + } + + private int anchorY(RNG rng, int x, int z, Search search) { + List anchors = anchorsAt(x, z, search); + if (anchors.isEmpty()) { + return -1; + } + if (anchors.size() == 1) { + return anchors.get(0); + } + return anchors.get(rng.i(anchors.size())); + } + + private List anchorsAt(int x, int z, Search search) { + if (search.scanStep() > MAX_PACKED_SETTING || search.minDepthBelowSurface() > MAX_PACKED_SETTING) { + return scanColumn(x, z, search); + } + long settingKey = ((long) search.mode().ordinal() << 32) | ((long) search.scanStep() << 16) | search.minDepthBelowSurface(); + Map> columns = anchorsBySetting.computeIfAbsent(settingKey, key -> new HashMap<>()); + long columnKey = CacheKey.key(x, z); + List anchors = columns.get(columnKey); + if (anchors != null) { + return anchors; + } + anchors = scanColumn(x, z, search); + columns.put(columnKey, anchors); + return anchors; + } + + private List scanColumn(int x, int z, Search search) { + int step = Math.max(1, search.scanStep()); + int surfaceY = surfaceHeight(x, z); + int maxAnchorExclusive = scanUpperBound(worldHeight, surfaceY, search.minDepthBelowSurface()); + if (maxAnchorExclusive == 0) { + return new ArrayList<>(); + } + int carvedHeight = Math.min(worldHeight, maxAnchorExclusive + 3); + byte[] carvedColumn = carvedColumn(x, z, carvedHeight); + return scanRange(search.mode(), step, carvedHeight, maxAnchorExclusive, carvedColumn); + } + + private List scanRange(CaveAnchorMode mode, int step, int height, int maxAnchorY, byte[] carvedColumn) { + List anchors = new ArrayList<>(); + for (int y = BEDROCK_CLEARANCE; y < maxAnchorY; y += step) { + if (!isCarved(carvedColumn, y)) { + continue; + } + boolean solidBelow = hasSolidNeighbor(carvedColumn, y, height, -1); + boolean solidAbove = hasSolidNeighbor(carvedColumn, y, height, 1); + if (matches(mode, solidBelow, solidAbove)) { + anchors.add(y); + } + } + return anchors; + } + + private static boolean isCarved(byte[] carvedColumn, int y) { + return y >= 0 && y < carvedColumn.length && carvedColumn[y] == 1; + } + + private static boolean hasSolidNeighbor(byte[] carvedColumn, int y, int height, int direction) { + for (int distance = 1; distance <= SOLID_NEIGHBOR_REACH_BLOCKS; distance++) { + int neighbor = y + (direction * distance); + if (neighbor < 0 || neighbor >= height || !isCarved(carvedColumn, neighbor)) { + return true; + } + } + return false; + } + + private static boolean matches(CaveAnchorMode mode, boolean solidBelow, boolean solidAbove) { + return switch (mode) { + case PROFILE_DEFAULT, FLOOR -> solidBelow; + case CEILING -> solidAbove; + case CENTER -> !solidBelow && !solidAbove; + case ANY -> true; + }; + } + + private byte[] carvedColumn(int x, int z, int height) { + long columnKey = CacheKey.key(x, z); + byte[] column = carvedColumns.get(columnKey); + if (column != null && column.length == height) { + return column; + } + column = carved.column(x, z, height); + carvedColumns.put(columnKey, column); + return column; + } + + private int surfaceHeight(int x, int z) { + long columnKey = CacheKey.key(x, z); + Integer known = surfaceHeights.get(columnKey); + if (known != null) { + return known; + } + int surfaceY = (int) Math.round(terrain.surfaceY(x, z)); + surfaceHeights.put(columnKey, surfaceY); + return surfaceY; + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveObjectPlacementTransaction.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveObjectPlacementTransaction.java index c29157880..b8af13f46 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/CaveObjectPlacementTransaction.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveObjectPlacementTransaction.java @@ -32,7 +32,7 @@ import org.jetbrains.annotations.Nullable; import java.util.HashMap; import java.util.Map; -final class CaveObjectPlacementTransaction implements IObjectPlacer { +public final class CaveObjectPlacementTransaction implements IObjectPlacer { private static final int CACHE_MISS = Integer.MIN_VALUE; private final IObjectPlacer delegate; @@ -46,7 +46,7 @@ final class CaveObjectPlacementTransaction implements IObjectPlacer { private final Long2IntOpenHashMap caveCeilings; private int blockWrites; - CaveObjectPlacementTransaction(IObjectPlacer delegate, int anchorY, int minDepthBelowSurface) { + public CaveObjectPlacementTransaction(IObjectPlacer delegate, int anchorY, int minDepthBelowSurface) { this.delegate = delegate; this.engine = delegate.getEngine(); this.anchorY = anchorY; @@ -60,7 +60,7 @@ final class CaveObjectPlacementTransaction implements IObjectPlacer { this.caveCeilings.defaultReturnValue(CACHE_MISS); } - CommitResult commit() { + public CommitResult commit() { if (blockWrites == 0) { discard(); return CommitResult.EMPTY; @@ -80,13 +80,13 @@ final class CaveObjectPlacementTransaction implements IObjectPlacer { return CommitResult.COMMITTED; } - void discard() { + public void discard() { mutations.clear(); bufferedBlocks.clear(); blockWrites = 0; } - int getCaveCeiling(int x, int z) { + public int getCaveCeiling(int x, int z) { long key = CacheKey.key(x, z); int cached = caveCeilings.get(key); if (cached != CACHE_MISS) { @@ -242,7 +242,7 @@ final class CaveObjectPlacementTransaction implements IObjectPlacer { return Math.min(worldHeight, scanLimit + 1); } - enum CommitResult { + public enum CommitResult { COMMITTED, EMPTY, REJECTED_BOUNDS diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveRejects.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveRejects.java new file mode 100644 index 000000000..0dd2f8ff6 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveRejects.java @@ -0,0 +1,69 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.builtin.objects.ObjectHost; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.PlaceableObject; +import com.volmit.ModuleLog; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + +/** Debug lines for cave objects that were not placed, at most one per kind of rejection every few seconds. */ +final class CaveRejects { + private static final long THROTTLE_MILLIS = 5000L; + private static final Map STATES = new ConcurrentHashMap<>(); + + private CaveRejects() { + } + + static void log(ObjectHost host, ModuleLog log, String scope, String reason, int chunkX, int chunkZ, ObjectPlacement placement, + PlaceableObject object, int densityIndex, int density, CaveAnchors.Search search, Integer anchorY, Throwable error) { + if (!host.debugging()) { + return; + } + String placementKeys = placement == null ? "none" : String.join(",", placement.place()); + String objectKey = object == null ? "null" : object.key(); + String throttleKey = scope + "|" + reason + "|" + placementKeys + "|" + objectKey; + State state = STATES.computeIfAbsent(throttleKey, key -> new State()); + long now = System.currentTimeMillis(); + long last = state.lastLogMillis.get(); + if ((now - last) < THROTTLE_MILLIS || !state.lastLogMillis.compareAndSet(last, now)) { + state.suppressed.incrementAndGet(); + return; + } + int suppressed = state.suppressed.getAndSet(0); + String errorText = error == null ? "none" : error.getClass().getSimpleName() + ":" + error.getMessage(); + log.debug("Cave object reject: scope=" + scope + " reason=" + reason + " chunk=" + chunkX + "," + chunkZ + " object=" + objectKey + + " placements=" + placementKeys + " densityIndex=" + densityIndex + " density=" + density + + " anchorMode=" + search.mode() + " anchorSearchAttempts=" + search.attempts() + " anchorScanStep=" + search.scanStep() + + " minDepthBelowSurface=" + search.minDepthBelowSurface() + " anchorY=" + (anchorY == null ? "none" : anchorY) + + " forcePlace=" + (placement != null && placement.forcePlace()) + + " carvingSupport=" + (placement == null ? "none" : placement.carvingSupport()) + + " suppressed=" + suppressed + " error=" + errorText); + } + + private static final class State { + private final AtomicLong lastLogMillis = new AtomicLong(0L); + private final AtomicInteger suppressed = new AtomicInteger(0); + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveSettings.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveSettings.java new file mode 100644 index 000000000..cff789b80 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveSettings.java @@ -0,0 +1,88 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.builtin.anchor.PlaceTrait; +import art.arcane.iris.builtin.carve.CaveAnchorMode; +import art.arcane.iris.builtin.carve.CaveProfile; +import art.arcane.iris.builtin.objects.PlacementSource; + +/** What a cave object placement takes from the cave profile that applies to it. */ +final class CaveSettings { + private static final CaveProfile DEFAULT_PROFILE = new CaveProfile(); + private static final int DEFAULT_SCAN_STEP = 1; + private static final int DEFAULT_MIN_DEPTH_BELOW_SURFACE = 6; + private static final int DEFAULT_SEARCH_ATTEMPTS = 6; + + private final CaveProfile dimensionProfile; + + CaveSettings(CaveProfile dimensionProfile) { + this.dimensionProfile = dimensionProfile; + } + + /** The profile of the first of {@code preferred} and {@code secondary} that is enabled, else the dimension's, else the default one. */ + CaveProfile resolve(CaveProfile preferred, CaveProfile secondary) { + if (preferred != null && preferred.enabled()) { + return preferred; + } + if (secondary != null && secondary.enabled()) { + return secondary; + } + if (dimensionProfile != null) { + return dimensionProfile; + } + return DEFAULT_PROFILE; + } + + /** How the placement looks for its anchor in caves: its own mode, else the profile's, else the floor; turned upside down, the ceiling. */ + CaveAnchors.Search searchFor(PlacementSource placement, CaveProfile profile) { + CaveAnchorMode mode = anchorMode(placement, profile); + if (placement.mode().placeMode().has(PlaceTrait.UPSIDE_DOWN)) { + mode = CaveAnchorMode.CEILING; + } + return new CaveAnchors.Search(mode, scanStep(profile), minDepthBelowSurface(profile), searchAttempts(profile)); + } + + private static CaveAnchorMode anchorMode(PlacementSource placement, CaveProfile profile) { + CaveAnchorMode placementMode = placement.caveAnchorMode(); + if (placementMode != null && !placementMode.equals(CaveAnchorMode.PROFILE_DEFAULT)) { + return placementMode; + } + if (profile == null) { + return CaveAnchorMode.FLOOR; + } + CaveAnchorMode profileMode = profile.defaultObjectAnchor(); + if (profileMode == null || profileMode.equals(CaveAnchorMode.PROFILE_DEFAULT)) { + return CaveAnchorMode.FLOOR; + } + return profileMode; + } + + private static int scanStep(CaveProfile profile) { + return profile == null ? DEFAULT_SCAN_STEP : Math.max(1, profile.anchorScanStep()); + } + + private static int minDepthBelowSurface(CaveProfile profile) { + return profile == null ? DEFAULT_MIN_DEPTH_BELOW_SURFACE : Math.max(0, profile.objectMinDepthBelowSurface()); + } + + private static int searchAttempts(CaveProfile profile) { + return profile == null ? DEFAULT_SEARCH_ATTEMPTS : Math.max(1, profile.anchorSearchAttempts()); + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java new file mode 100644 index 000000000..677f0aba4 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java @@ -0,0 +1,680 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.carve.CarvingMode; +import art.arcane.iris.builtin.carve.CaveProfile; +import art.arcane.iris.builtin.objects.CavePlacement; +import art.arcane.iris.builtin.objects.ObjectChunk; +import art.arcane.iris.builtin.objects.ObjectHost; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectSettings; +import art.arcane.iris.builtin.objects.PlaceableObject; +import art.arcane.iris.builtin.objects.PlacementChanges; +import art.arcane.iris.builtin.objects.PlacementSource; +import art.arcane.iris.builtin.objects.PlacementTags; +import art.arcane.iris.builtin.objects.ProceduralObjectSettings; +import art.arcane.iris.builtin.objects.ProceduralPlacement; +import art.arcane.iris.builtin.objects.RequireSurfaceSupportSettings; +import art.arcane.iris.builtin.objects.SurfaceSupportBufferSettings; +import art.arcane.iris.builtin.objects.UpperObjectsForceSettings; +import art.arcane.iris.builtin.objects.UpperObjectsSettings; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.ModuleLog; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.resource.ResourceId; +import com.volmit.stage.MantleStageContext; +import com.volmit.world.TerrainSampler; + +import java.util.List; +import java.util.Optional; +import java.util.OptionalInt; + +/** + * Places what the objects of one chunk's region and biomes say: the objects of its surface, caves and the terrain stacked above, + * and its procedural objects, in that order, all drawing from the one random of the chunk. + */ +final class ChunkObjectPlacing { + private static final int CENTER_OFFSET_BLOCKS = 8; + private static final int CHUNK_SHIFT = 4; + private static final int CHUNK_WIDTH_BLOCKS = 16; + private static final double CHANCE_JITTER = 0.005; + private static final int[] CAVE_BIOME_SAMPLE_DEPTHS = {48, 80, 112}; + private static final int LEGACY_CAVE_SAMPLE_DEPTH = 48; + private static final int UPPER_SURFACE_MARGIN_BLOCKS = 2; + private static final int MINIMUM_UPPER_ANCHOR_Y = 1; + private static final int DIAGNOSTIC_CHUNK_MASK = 31; + private static final int DIAGNOSTIC_SURFACE_MARGIN = 14; + private static final String TREE_FOLDER = "trees/"; + private static final String REGEN_THREAD_PREFIX = "Iris-Regen-"; + + private final ObjectHost host; + private final ModuleLog log; + private final MantleStageContext context; + private final ObjectChunk chunk; + private final TerrainSampler terrain; + private final int chunkX; + private final int chunkZ; + private final int centerX; + private final int centerZ; + private final RNG rng; + private final boolean traceRegen; + private final boolean golden; + private final EffectivePlacements effective; + private final CaveSettings caves; + private final int worldHeight; + private final int caveLavaHeight; + + ChunkObjectPlacing(ObjectHost host, ModuleLog log, MantleStageContext context) { + this.host = host; + this.log = log; + this.context = context; + this.chunk = host.chunk(); + this.terrain = context.terrain(); + this.chunkX = context.originX() >> CHUNK_SHIFT; + this.chunkZ = context.originZ() >> CHUNK_SHIFT; + this.centerX = CENTER_OFFSET_BLOCKS + (chunkX << CHUNK_SHIFT); + this.centerZ = CENTER_OFFSET_BLOCKS + (chunkZ << CHUNK_SHIFT); + this.rng = host.chunkRandom(chunkX, chunkZ); + this.traceRegen = Thread.currentThread().getName().startsWith(REGEN_THREAD_PREFIX) && host.debugging(); + this.golden = chunk.goldenDebug(chunkX, chunkZ); + this.worldHeight = context.mantle().bounds().maxY(); + this.caveLavaHeight = host.caveLavaHeight(); + this.effective = new EffectivePlacements(dimensionRequiresSurfaceSupport(), dimensionSurfaceSupportBuffer()); + this.caves = new CaveSettings(dimensionLevel(CaveProfile.class)); + } + + /** Places what originates in this chunk. */ + void place() { + Column column = readColumn(); + if (host.debugging() && (chunkX & DIAGNOSTIC_CHUNK_MASK) == 0 && (chunkZ & DIAGNOSTIC_CHUNK_MASK) == 0) { + logCaveDiagnostics(column); + } + if (traceRegen) { + logLayerStart(column); + } + Tally tally = placeObjects(column); + placeProceduralObjects(column); + if (upperObjectsEnabled()) { + placeUpperObjects(column); + } + if (traceRegen) { + logLayerDone(tally); + } + } + + /** The region and biomes at the chunk's centre and what each declares. */ + private Column readColumn() { + ResourceId region = host.regionAt(centerX, centerZ); + ResourceId surface = host.surfaceBiomeAt(centerX, centerZ); + int surfaceY = surfaceY(centerX, centerZ); + ResourceId cave = resolveCaveObjectBiome(surfaceY, surface); + return new Column(region, surface, cave, surfaceY, objectsOf(cave, region, surface), proceduralOf(cave, region, surface), + profilesOf(cave, region, surface)); + } + + private int surfaceY(int x, int z) { + return (int) Math.round(terrain.surfaceY(x, z)); + } + + private ResourceId resolveCaveObjectBiome(int surfaceY, ResourceId surfaceBiome) { + ResourceId legacy = caveBiomeAt(Math.max(1, surfaceY - LEGACY_CAVE_SAMPLE_DEPTH)).orElse(surfaceBiome); + ResourceId ladderChoice = null; + for (int depth : CAVE_BIOME_SAMPLE_DEPTHS) { + Optional sampled = caveBiomeAt(Math.max(1, surfaceY - depth)); + if (sampled.isEmpty() || sampled.get().equals(surfaceBiome)) { + continue; + } + if (hasCarvingObjects(host.biomeDeclaration(sampled.get(), ObjectSettings.class))) { + ladderChoice = sampled.get(); + } + } + return ladderChoice != null ? ladderChoice : legacy; + } + + private Optional caveBiomeAt(int y) { + return terrain.biome(centerX, y, centerZ).caveBiome(); + } + + private static boolean hasCarvingObjects(Optional settings) { + return settings.isPresent() && !carvingObjects(settings.get()).isEmpty(); + } + + private ColumnObjects objectsOf(ResourceId cave, ResourceId region, ResourceId surface) { + List> entries = context.settings().at(ObjectSettings.class, centerX, centerZ); + return new ColumnObjects(level(entries, Target.BIOME), caveSettings(cave, surface, entries, ObjectSettings.class), level(entries, Target.REGION)); + } + + private ColumnProcedural proceduralOf(ResourceId cave, ResourceId region, ResourceId surface) { + List> entries = context.settings().at(ProceduralObjectSettings.class, centerX, centerZ); + return new ColumnProcedural(level(entries, Target.BIOME), + caveSettings(cave, surface, entries, ProceduralObjectSettings.class), level(entries, Target.REGION)); + } + + private ColumnProfiles profilesOf(ResourceId cave, ResourceId region, ResourceId surface) { + List> entries = context.settings().at(CaveProfile.class, centerX, centerZ); + return new ColumnProfiles(level(entries, Target.BIOME), caveSettings(cave, surface, entries, CaveProfile.class), level(entries, Target.REGION)); + } + + private F caveSettings(ResourceId cave, ResourceId surface, List> entries, Class type) { + if (cave.equals(surface)) { + return level(entries, Target.BIOME); + } + return host.biomeDeclaration(cave, type).orElse(null); + } + + private F dimensionLevel(Class type) { + return level(context.settings().at(type, centerX, centerZ), Target.DIMENSION); + } + + private static F level(List> entries, Target level) { + for (Entry entry : entries) { + if (entry.level() == level) { + return entry.value(); + } + } + return null; + } + + private boolean dimensionRequiresSurfaceSupport() { + RequireSurfaceSupportSettings settings = dimensionLevel(RequireSurfaceSupportSettings.class); + return settings == null ? new RequireSurfaceSupportSettings().require() : settings.require(); + } + + private int dimensionSurfaceSupportBuffer() { + SurfaceSupportBufferSettings settings = dimensionLevel(SurfaceSupportBufferSettings.class); + return settings == null ? new SurfaceSupportBufferSettings().buffer() : settings.buffer(); + } + + private boolean upperObjectsEnabled() { + UpperObjectsSettings settings = dimensionLevel(UpperObjectsSettings.class); + return settings != null && settings.enabled() && terrain.upperDimensionY(centerX, centerZ).isPresent(); + } + + private boolean upperObjectsForced() { + UpperObjectsForceSettings settings = dimensionLevel(UpperObjectsForceSettings.class); + return settings != null && settings.force(); + } + + private static List surfaceObjects(ObjectSettings settings) { + return settings == null ? List.of() : settings.objects().stream().filter(p -> p.carvingSupport().supportsSurface()).toList(); + } + + private static List carvingObjects(ObjectSettings settings) { + return settings == null ? List.of() : settings.objects().stream().filter(p -> p.carvingSupport().supportsCarving()).toList(); + } + + private CaveAnchors newAnchors() { + return new CaveAnchors(chunk.carved(), terrain, worldHeight, caveLavaHeight); + } + + private Tally placeObjects(Column column) { + Tally tally = new Tally(); + CaveProfile biomeCaveProfile = caves.resolve(column.profiles().cave(), column.profiles().region()); + CaveProfile regionCaveProfile = caves.resolve(column.profiles().region(), column.profiles().cave()); + CaveAnchors anchors = newAnchors(); + placeSurfaceScope(tally, "biome-surface", surfaceObjects(column.objects().surface()), column.surface().toString()); + placeCaveScope(tally, "biome-cave", carvingObjects(column.objects().cave()), biomeCaveProfile, column.cave(), column.cave().toString(), anchors); + placeSurfaceScope(tally, "region-surface", surfaceObjects(column.objects().region()), column.region().toString()); + placeCaveScope(tally, "region-cave", carvingObjects(column.objects().region()), regionCaveProfile, null, column.region().toString(), anchors); + return tally; + } + + private void placeSurfaceScope(Tally tally, String scope, List placements, String ownerName) { + for (ObjectPlacement placement : placements) { + tally.checked(scope); + boolean passes = rng.chance(placement.chance() + rng.d(-CHANCE_JITTER, CHANCE_JITTER)); + traceChance(scope, passes, placement); + if (!passes) { + continue; + } + tally.triggered(scope); + try { + placeObject(tally, placement, scope); + } catch (Throwable failure) { + tally.errors++; + logPlacementFailure("Failed to place objects in the following " + ownerKind(scope) + ": " + ownerName, placement, failure); + } + } + } + + private void placeCaveScope(Tally tally, String scope, List placements, CaveProfile profile, + ResourceId expectedCaveBiome, String ownerName, CaveAnchors anchors) { + for (ObjectPlacement placement : placements) { + tally.checked(scope); + boolean passes = rng.chance(placement.chance()); + traceChance(scope, passes, placement); + if (!passes) { + continue; + } + tally.triggered(scope); + try { + placeCaveObject(tally, placement, profile, scope, expectedCaveBiome, anchors); + } catch (Throwable failure) { + tally.errors++; + logPlacementFailure("Failed to place cave objects in the following " + ownerKind(scope) + ": " + ownerName, placement, failure); + } + } + } + + private static String ownerKind(String scope) { + return scope.startsWith("biome") ? "biome" : "region"; + } + + private void logPlacementFailure(String message, ObjectPlacement placement, Throwable failure) { + log.error(message, failure); + log.error("Object(s) " + String.join(", ", placement.place()) + " (" + failure.getClass().getSimpleName() + ").", null); + log.error("Are these objects missing?", null); + } + + private void placeObject(Tally tally, ObjectPlacement placement, String scope) { + int blockX = chunkX << CHUNK_SHIFT; + int blockZ = chunkZ << CHUNK_SHIFT; + int density = host.density(placement, rng, blockX, blockZ); + for (int i = 0; i < density; i++) { + tally.attempts++; + Optional picked = host.pickScaled(placement, rng); + if (picked.isEmpty()) { + tally.nullObjects++; + traceNullObject(scope, i, density, placement); + continue; + } + PlaceableObject object = picked.get(); + int x = rng.i(blockX, blockX + CHUNK_WIDTH_BLOCKS); + int z = rng.i(blockZ, blockZ + CHUNK_WIDTH_BLOCKS); + PlacementChanges changes = effective.forSurface(placement, object); + boolean treePlacement = isTreePlacement(object, placement); + int id = rng.i(0, Integer.MAX_VALUE); + String goldenTag = golden ? scope + "/" + object.key() : null; + if (golden) { + log.debug("Goldendebug object attempt: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.key() + + " densityIndex=" + i + " xx=" + x + " zz=" + z + " mode=" + placement.mode()); + } + try { + PlacementTags tags = tags(object, id, "surface", treePlacement, placement); + int result = chunk.placeOnSurface(object, x, z, placement, changes, tags, rng, goldenTag); + if (result >= 0) { + tally.placed++; + } else { + tally.rejected++; + } + traceObjectResult(scope, object, result, x, z, i, density); + } catch (Throwable failure) { + tally.errors++; + log.error("Regen object placement exception: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.key() + + " densityIndex=" + i + " density=" + density + " error=" + failure.getClass().getSimpleName() + ":" + failure.getMessage(), failure); + } + } + } + + private void placeCaveObject(Tally tally, ObjectPlacement placement, CaveProfile profile, String scope, + ResourceId expectedCaveBiome, CaveAnchors anchors) { + int minX = chunkX << CHUNK_SHIFT; + int minZ = chunkZ << CHUNK_SHIFT; + int density = host.density(placement, rng, minX, minZ); + CaveAnchors.Search search = caves.searchFor(placement, profile); + for (int i = 0; i < density; i++) { + tally.attempts++; + Optional picked = host.pickScaled(placement, rng); + if (picked.isEmpty()) { + tally.nullObjects++; + traceNullObject(scope, i, density, placement); + CaveRejects.log(host, log, scope, "NULL_OBJECT", chunkX, chunkZ, placement, null, i, density, search, null, null); + continue; + } + PlaceableObject object = picked.get(); + CaveAnchors.Anchor anchor = anchors.find(rng, minX, minZ, search, expectedCaveBiome, placement.underwater()); + if (anchor == null) { + tally.rejected++; + CaveRejects.log(host, log, scope, "NO_ANCHOR", chunkX, chunkZ, placement, object, i, density, search, null, null); + continue; + } + int id = rng.i(0, Integer.MAX_VALUE); + PlacementChanges changes = effective.forCave(placement, object, profile); + try { + PlacementTags tags = tags(object, id, "cave", isTreePlacement(object, placement), placement); + CavePlacement contained = chunk.placeInCave(object, anchor.x(), anchor.y(), anchor.z(), placement, changes, + search.minDepthBelowSurface(), tags, rng, null); + tallyCave(tally, contained, scope, object, placement, i, density, search, anchor); + } catch (Throwable failure) { + tally.errors++; + log.error("Regen cave object placement exception: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.key() + + " densityIndex=" + i + " density=" + density + " error=" + failure.getClass().getSimpleName() + ":" + failure.getMessage(), failure); + CaveRejects.log(host, log, scope, "EXCEPTION", chunkX, chunkZ, placement, object, i, density, search, anchor.y(), failure); + } + } + } + + private void tallyCave(Tally tally, CavePlacement contained, String scope, PlaceableObject object, ObjectPlacement placement, + int index, int density, CaveAnchors.Search search, CaveAnchors.Anchor anchor) { + if (contained.wroteBlocks()) { + tally.placed++; + } else { + tally.rejected++; + CaveRejects.log(host, log, scope, rejectReason(contained), chunkX, chunkZ, placement, object, index, density, search, anchor.y(), null); + } + if (traceRegen) { + log.debug("Regen cave object placement result: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.key() + + " resultY=" + contained.resultY() + " anchorY=" + anchor.y() + " px=" + anchor.x() + " pz=" + anchor.z() + + " wroteBlocks=" + contained.wroteBlocks() + " densityIndex=" + index + " density=" + density); + } + } + + private static String rejectReason(CavePlacement contained) { + if (contained.resultY() < 0) { + return "PLACE_NEGATIVE"; + } + return contained.commit() == CavePlacement.Commit.REJECTED_BOUNDS ? "CONTAINMENT" : "NO_WRITES"; + } + + private void placeProceduralObjects(Column column) { + List surface = proceduralPlacements(column.procedural().surface()); + List region = proceduralPlacements(column.procedural().region()); + CaveProfile surfaceProfile = caves.resolve(column.profiles().surface(), column.profiles().region()); + CaveProfile regionProfile = caves.resolve(column.profiles().region(), column.profiles().cave()); + placeProceduralFrom(surface, column.surface().toString(), surfaceProfile, column.surface()); + placeProceduralFrom(region, column.region().toString(), regionProfile, null); + if (!column.cave().equals(column.surface())) { + CaveProfile caveProfile = caves.resolve(column.profiles().cave(), column.profiles().region()); + placeProceduralFrom(proceduralPlacements(column.procedural().cave()), column.cave().toString(), caveProfile, column.cave()); + } + } + + private List proceduralPlacements(ProceduralObjectSettings settings) { + return settings == null ? List.of() : host.procedural(settings); + } + + private void placeProceduralFrom(List placements, String scope, CaveProfile caveProfile, ResourceId expectedCaveBiome) { + if (placements.isEmpty()) { + return; + } + int blockX = chunkX << CHUNK_SHIFT; + int blockZ = chunkZ << CHUNK_SHIFT; + CaveAnchors anchors = newAnchors(); + for (ProceduralPlacement placement : placements) { + boolean chancePassed = passesProceduralChance(rng, placement.chance()); + if (golden) { + log.debug("Goldendebug procedural chance: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " placement=" + placement.name() + " passed=" + chancePassed); + } + if (!chancePassed) { + continue; + } + placeProcedural(placement, scope, caveProfile, expectedCaveBiome, anchors, blockX, blockZ); + } + } + + private void placeProcedural(ProceduralPlacement placement, String scope, CaveProfile caveProfile, ResourceId expectedCaveBiome, + CaveAnchors anchors, int blockX, int blockZ) { + boolean carving = placement.carvingSupport() == CarvingMode.CARVING_ONLY; + CaveAnchors.Search search = caves.searchFor(placement, caveProfile); + int density = Math.max(1, placement.density()); + for (int i = 0; i < density; i++) { + Optional picked = placement.variant(rng); + if (picked.isEmpty()) { + if (golden) { + log.debug("Goldendebug procedural pick: chunk=" + chunkX + "," + chunkZ + " placement=" + placement.name() + " densityIndex=" + i + " variant=null"); + } + continue; + } + PlaceableObject variant = picked.get(); + CaveAnchors.Anchor anchor = carving ? anchors.find(rng, blockX, blockZ, search, expectedCaveBiome, placement.underwater()) : null; + if (carving && anchor == null) { + if (golden) { + log.debug("Goldendebug procedural cave anchor rejected: chunk=" + chunkX + "," + chunkZ + " placement=" + placement.name() + + " minDepthBelowSurface=" + search.minDepthBelowSurface()); + } + continue; + } + int x = anchor == null ? rng.i(blockX, blockX + CHUNK_WIDTH_BLOCKS) : anchor.x(); + int z = anchor == null ? rng.i(blockZ, blockZ + CHUNK_WIDTH_BLOCKS) : anchor.z(); + int id = rng.i(0, Integer.MAX_VALUE); + if (golden) { + logProceduralPick(placement, variant, i, x, z, carving); + } + try { + placeProceduralVariant(placement, variant, scope, caveProfile, search, anchor, x, z, id); + } catch (Throwable failure) { + log.error("Failed to place procedural object '" + placement.name() + "' in " + scope, failure); + } + } + } + + private void placeProceduralVariant(ProceduralPlacement placement, PlaceableObject variant, String scope, CaveProfile caveProfile, + CaveAnchors.Search search, CaveAnchors.Anchor anchor, int x, int z, int id) { + String goldenTag = golden ? scope + "/" + placement.name() : null; + PlacementTags tags = tags(variant, id, "procedural", placement.tree(), placement, false); + int resultY; + String commit = "n/a"; + if (anchor != null) { + PlacementChanges changes = effective.forCave(placement, variant, caveProfile); + CavePlacement contained = chunk.placeInCave(variant, x, anchor.y(), z, placement, changes, search.minDepthBelowSurface(), tags, rng, goldenTag); + resultY = contained.resultY(); + commit = contained.commit().toString(); + } else { + resultY = chunk.placeOnSurface(variant, x, z, placement, PlacementChanges.NONE, tags, rng, goldenTag); + } + if (golden) { + log.debug("Goldendebug procedural result: chunk=" + chunkX + "," + chunkZ + " placement=" + placement.name() + + " variant=" + variant.key() + " xx=" + x + " zz=" + z + " resultY=" + resultY + " commit=" + commit); + } + } + + private void logProceduralPick(ProceduralPlacement placement, PlaceableObject variant, int index, int x, int z, boolean carving) { + List pool = placement.variants(); + log.debug("Goldendebug procedural pick: chunk=" + chunkX + "," + chunkZ + " placement=" + placement.name() + " densityIndex=" + index + + " variant=" + variant.key() + " variantIndex=" + pool.indexOf(variant) + "/" + pool.size() + " xx=" + x + " zz=" + z + + " mode=" + placement.mode() + " carving=" + carving); + } + + static boolean passesProceduralChance(RNG rng, double chance) { + if (chance <= 0.0) { + return false; + } + if (chance >= 1.0) { + return true; + } + return rng.chance(Math.max(0.0, Math.min(1.0, chance + rng.d(-CHANCE_JITTER, CHANCE_JITTER)))); + } + + private void placeUpperObjects(Column column) { + Optional upper = host.upperObjects(centerX, centerZ); + if (upper.isEmpty() || (upper.get().biome() == null && upper.get().region() == null)) { + return; + } + boolean forcePlace = upperObjectsForced(); + placeUpperScope(upper.get().biome(), upper.get().biomeKey(), "upper-biome-surface", "biome", forcePlace); + placeUpperScope(upper.get().region(), upper.get().regionKey(), "upper-region-surface", "region", forcePlace); + } + + private void placeUpperScope(ObjectSettings settings, String ownerKey, String scope, String kind, boolean forcePlace) { + for (ObjectPlacement placement : surfaceObjects(settings)) { + if (!rng.chance(placement.chance() + rng.d(-CHANCE_JITTER, CHANCE_JITTER))) { + continue; + } + try { + placeUpperObject(placement, forcePlace, scope); + } catch (Throwable failure) { + log.error("Failed to place upper-dimension objects in " + kind + " " + ownerKey + ": " + String.join(", ", placement.place()) + + " (" + failure.getClass().getSimpleName() + ")", failure); + } + } + } + + private void placeUpperObject(ObjectPlacement placement, boolean forcePlace, String scope) { + int minX = chunkX << CHUNK_SHIFT; + int minZ = chunkZ << CHUNK_SHIFT; + int density = host.density(placement, rng, minX, minZ); + for (int i = 0; i < density; i++) { + Optional picked = host.pickScaled(placement, rng); + if (picked.isEmpty()) { + continue; + } + PlaceableObject object = picked.get(); + int x = rng.i(minX, minX + CHUNK_WIDTH_BLOCKS); + int z = rng.i(minZ, minZ + CHUNK_WIDTH_BLOCKS); + OptionalInt upperSurface = terrain.upperDimensionY(x, z); + if (upperSurface.isEmpty() || upperSurface.getAsInt() >= worldHeight - UPPER_SURFACE_MARGIN_BLOCKS) { + continue; + } + int anchorY = upperSurface.getAsInt() - 1 - Math.floorDiv(object.height(), 2); + if (anchorY <= MINIMUM_UPPER_ANCHOR_Y) { + continue; + } + int id = rng.i(0, Integer.MAX_VALUE); + PlacementChanges changes = PlacementChanges.NONE.withPlace(List.of(String.valueOf(object.key()))) + .withMode(ObjectPlaceMode.CENTER_HEIGHT) + .withUpsideDown(true).withCarvingSupport(CarvingMode.ANYWHERE); + if (forcePlace) { + changes = changes.withForcePlace(true); + } + PlacementTags tags = tags(object, id, "upper", isTreePlacement(object, placement), placement); + int result = chunk.placeUpper(object, x, anchorY, z, placement, changes, tags, rng); + if (traceRegen) { + log.debug("Upper object placement: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.key() + " anchorY=" + + anchorY + " upperSurfaceY=" + upperSurface.getAsInt() + " resultY=" + result + " forcePlace=" + forcePlace); + } + } + } + + private PlacementTags tags(PlaceableObject object, int id, String context, boolean treePlacement, PlacementSource placement) { + return tags(object, id, context, treePlacement, placement, placement.isDolphinTarget() && placement.underwater()); + } + + private PlacementTags tags(PlaceableObject object, int id, String context, boolean treePlacement, PlacementSource placement, + boolean buriedTreasure) { + return new PlacementTags(placementMarker(object, id, context), treePlacement, buriedTreasure); + } + + private String placementMarker(PlaceableObject object, int id, String context) { + String key = object == null ? null : object.key(); + if (key == null || key.isEmpty() || key.equals("null")) { + String fingerprint = context + "|" + (object == null ? "" : object.getClass().getSimpleName()); + log.warnOnce(fingerprint, "Skipping placement marker write: the object has no loadKey (context=" + context + "). " + + "This would previously produce 'Couldn't find Object: null' warnings on chunk reload."); + return null; + } + return key + "@" + id; + } + + private static boolean isTreePlacement(PlaceableObject object, ObjectPlacement placement) { + String key = object == null ? null : object.key(); + return (key != null && key.startsWith(TREE_FOLDER)) || (placement != null && !placement.trees().isEmpty()); + } + + private void traceChance(String scope, boolean passes, ObjectPlacement placement) { + if (!traceRegen) { + return; + } + log.debug("Regen object placer chance: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " chanceResult=" + passes + + " chanceBase=" + placement.chance() + " densityMid=" + placement.middleDensity() + " objects=" + placement.place().size()); + } + + private void traceNullObject(String scope, int index, int density, ObjectPlacement placement) { + if (!traceRegen) { + return; + } + log.debug("Regen object placement null object: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " densityIndex=" + index + + " density=" + density + " placementKeys=" + String.join(",", placement.place())); + } + + private void traceObjectResult(String scope, PlaceableObject object, int result, int x, int z, int index, int density) { + if (golden) { + log.debug("Goldendebug object result: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.key() + + " resultY=" + result + " fallback=surface"); + } + if (traceRegen) { + log.debug("Regen object placement result: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.key() + + " resultY=" + result + " px=" + x + " pz=" + z + " fallback=surface densityIndex=" + index + " density=" + density); + } + } + + private void logCaveDiagnostics(Column column) { + CarvedCount carved = new CarvedCount(); + int maxY = Math.min(worldHeight - 1, column.surfaceY() - DIAGNOSTIC_SURFACE_MARGIN); + for (int y = 1; y < maxY; y++) { + if (chunk.carved().isCarved(centerX, y, centerZ)) { + carved.blocks++; + } + } + log.debug("Cave object diag: chunk=" + chunkX + "," + chunkZ + " surfaceBiome=" + column.surface() + " caveBiome=" + column.cave() + + " surfaceY=" + column.surfaceY() + " maxAnchorY=" + maxY + " carvedAtCenter=" + carved.blocks + + " biomeCarvingObjects=" + carvingObjects(column.objects().cave()).size() + + " regionCarvingObjects=" + carvingObjects(column.objects().region()).size() + + " sameBiome=" + column.cave().equals(column.surface())); + } + + private void logLayerStart(Column column) { + log.debug("Regen object layer start: chunk=" + chunkX + "," + chunkZ + " surfaceBiome=" + column.surface() + " caveBiome=" + column.cave() + + " region=" + column.region() + " biomeSurfacePlacers=" + surfaceObjects(column.objects().surface()).size() + + " biomeCavePlacers=" + carvingObjects(column.objects().cave()).size() + + " regionSurfacePlacers=" + surfaceObjects(column.objects().region()).size() + + " regionCavePlacers=" + carvingObjects(column.objects().region()).size()); + } + + private void logLayerDone(Tally tally) { + log.debug("Regen object layer done: chunk=" + chunkX + "," + chunkZ + " " + tally.describe() + + " objectAttempts=" + tally.attempts + " objectPlaced=" + tally.placed + " objectRejected=" + tally.rejected + + " objectNull=" + tally.nullObjects + " objectErrors=" + tally.errors); + } + + private record Column(ResourceId region, ResourceId surface, ResourceId cave, int surfaceY, ColumnObjects objects, + ColumnProcedural procedural, ColumnProfiles profiles) { + } + + private record ColumnObjects(ObjectSettings surface, ObjectSettings cave, ObjectSettings region) { + } + + private record ColumnProcedural(ProceduralObjectSettings surface, ProceduralObjectSettings cave, ProceduralObjectSettings region) { + } + + private record ColumnProfiles(CaveProfile surface, CaveProfile cave, CaveProfile region) { + } + + private static final class CarvedCount { + private int blocks; + } + + /** What placing the objects of a chunk came to. */ + private static final class Tally { + private final java.util.Map scopes = new java.util.LinkedHashMap<>(); + private int attempts; + private int placed; + private int rejected; + private int nullObjects; + private int errors; + + void checked(String scope) { + scopes.computeIfAbsent(scope, key -> new int[2])[0]++; + } + + void triggered(String scope) { + scopes.computeIfAbsent(scope, key -> new int[2])[1]++; + } + + String describe() { + StringBuilder text = new StringBuilder(); + scopes.forEach((scope, counts) -> text.append(scope).append("PlacersChecked=").append(counts[0]) + .append(' ').append(scope).append("PlacersTriggered=").append(counts[1]).append(' ')); + return text.toString(); + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/EffectivePlacements.java b/src/main/java/art/arcane/iris/engine/mantle/components/EffectivePlacements.java new file mode 100644 index 000000000..22315d331 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/EffectivePlacements.java @@ -0,0 +1,90 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.anchor.PlaceTrait; +import art.arcane.iris.builtin.carve.CaveProfile; +import art.arcane.iris.builtin.objects.PlaceableObject; +import art.arcane.iris.builtin.objects.PlacementChanges; +import art.arcane.iris.builtin.objects.PlacementSource; + +import java.util.List; +import java.util.Locale; + +/** How a dimension and a cave profile change the placement an object is placed with. */ +final class EffectivePlacements { + private static final String IMPORTS_FOLDER = "imports/"; + + private final boolean dimensionRequiresSurfaceSupport; + private final int dimensionSurfaceSupportBuffer; + + EffectivePlacements(boolean dimensionRequiresSurfaceSupport, int dimensionSurfaceSupportBuffer) { + this.dimensionRequiresSurfaceSupport = dimensionRequiresSurfaceSupport; + this.dimensionSurfaceSupportBuffer = dimensionSurfaceSupportBuffer; + } + + /** The changes to make to {@code placement} to place {@code object} on the surface. */ + PlacementChanges forSurface(PlacementSource placement, PlaceableObject object) { + return withDimensionSurfaceSupport(placement, withImportedMode(placement, object, PlacementChanges.NONE)); + } + + /** The changes to make to {@code placement} to place {@code object} in a cave with the cave profile {@code caveProfile}. */ + PlacementChanges forCave(PlacementSource placement, PlaceableObject object, CaveProfile caveProfile) { + PlacementChanges changes = forSurface(placement, object); + ObjectPlaceMode mode = changes.mode() != null ? changes.mode() : placement.mode(); + if (mode != ObjectPlaceMode.CENTER_HEIGHT || caveProfile == null) { + return changes; + } + ObjectPlaceMode profileMode = caveProfile.defaultObjectPlaceMode().orElse(null); + if (profileMode == null) { + return changes; + } + String key = object.key(); + List place = key == null || key.isBlank() ? List.of() : List.of(key); + return changes.withPlace(place).withMode(profileMode); + } + + /** Imported objects are placed with the fast minimal stilt unless their mode finds its own height. */ + private static PlacementChanges withImportedMode(PlacementSource placement, PlaceableObject object, PlacementChanges changes) { + String key = object.key(); + if (key == null || key.isBlank() || !isImported(key)) { + return changes; + } + ObjectPlaceMode mode = placement.mode(); + if (mode.placeMode().has(PlaceTrait.FREE_HEIGHT) || mode == ObjectPlaceMode.FAST_MIN_STILT) { + return changes; + } + return changes.withPlace(List.of(key)).withMode(ObjectPlaceMode.FAST_MIN_STILT); + } + + private static boolean isImported(String key) { + return key.toLowerCase(Locale.ROOT).contains(IMPORTS_FOLDER); + } + + /** The dimension acts as the floor: it can force support on and widen the buffer, never weaken either. */ + private PlacementChanges withDimensionSurfaceSupport(PlacementSource placement, PlacementChanges changes) { + boolean require = placement.requireSurfaceSupport() && dimensionRequiresSurfaceSupport; + int buffer = Math.max(placement.surfaceSupportBuffer(), dimensionSurfaceSupportBuffer); + if (require == placement.requireSurfaceSupport() && buffer == placement.surfaceSupportBuffer()) { + return changes; + } + return changes.withSurfaceSupport(require, buffer); + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java index b24ba27e0..4dbc0a9ad 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java @@ -29,6 +29,7 @@ import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.mantle.MantleWriter; import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample; import art.arcane.iris.engine.object.placement.FloatingObjectFootprint; +import art.arcane.iris.engine.object.placement.IrisObjectVacuum; import art.arcane.iris.engine.object.placement.IObjectPlacer; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.prefab.IrisObject; @@ -593,7 +594,7 @@ public class FloatingObjectPlacing { size = IrisObject.sampleSize(file); sizeCache.put(objectKey, size); } - int reach = ObjectPlacing.calculatePlacementReach(size, placement); + int reach = calculatePlacementReach(size, placement); if (reach > 128 && warnedLargeObjects.add(objectKey)) { log.warn("Floating object " + objectKey + " has a large placement reach (" + reach + " blocks) and may increase memory usage!"); } @@ -605,4 +606,53 @@ public class FloatingObjectPlacing { } return radius; } + + static int calculatePlacementReach(IrisBlockVector size, IrisObjectPlacement placement) { + if (size == null) { + return 0; + } + if (placement == null) { + return Math.max(Math.abs(size.getBlockX()), Math.abs(size.getBlockZ())); + } + + double scale = placement.getScale() != null ? Math.max(1D, placement.getScale().getMaxScale()) : 1D; + int width = scaledDimension(size.getBlockX(), scale); + int height = scaledDimension(size.getBlockY(), scale); + int depth = scaledDimension(size.getBlockZ(), scale); + IrisObjectRotation rotation = placement.getRotation(); + boolean rotateX = rotation != null && rotation.isEnabled() && rotation.getXAxis() != null && rotation.getXAxis().enabled(); + boolean rotateZ = rotation != null && rotation.isEnabled() && rotation.getZAxis() != null && rotation.getZAxis().enabled(); + int footprint = rotateX || rotateZ ? Math.max(width, Math.max(height, depth)) : Math.max(width, depth); + int translation = calculateTranslationReach(placement.getTranslate(), rotation, rotateX || rotateZ); + int warp = placement.getWarp() != null && !placement.getWarp().isFlat() + ? (int) Math.ceil(Math.abs(placement.getWarp().getMultiplier()) / 2D) + : 0; + int vacuum = placement.getMode().placeMode().bendsTerrain() + ? 2 * IrisObjectVacuum.resolveRadius(placement.getMode().placeMode().vacuum(), placement.getVacuumSettings()) + : 0; + long reach = (long) footprint + translation + warp + vacuum; + return reach > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) reach; + } + + private static int scaledDimension(int dimension, double scale) { + int absoluteDimension = Math.abs(dimension); + if (scale <= 1D) { + return absoluteDimension; + } + return (int) Math.ceil((absoluteDimension * scale) + (scale * 2D)); + } + + private static int calculateTranslationReach(IrisObjectTranslate translate, IrisObjectRotation rotation, boolean rotateVertically) { + if (translate == null || !translate.canTranslate()) { + return 0; + } + double x = translate.getX(); + double y = translate.getY(); + double z = translate.getZ(); + if (rotateVertically) { + return (int) Math.ceil(Math.sqrt((x * x) + (y * y) + (z * z))); + } + boolean rotateY = rotation != null && rotation.isEnabled() && rotation.getYAxis() != null && rotation.getYAxis().enabled(); + return rotateY ? (int) Math.ceil(Math.hypot(x, z)) : (int) Math.max(Math.abs(x), Math.abs(z)); + } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/GoldenDebugObjectPlacer.java b/src/main/java/art/arcane/iris/engine/mantle/components/GoldenDebugObjectPlacer.java index 4dd1c86ba..d2a958e68 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/GoldenDebugObjectPlacer.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/GoldenDebugObjectPlacer.java @@ -25,7 +25,7 @@ import art.arcane.iris.engine.object.prefab.TileData; import art.arcane.iris.spi.PlatformBlockState; import com.volmit.ModuleLog; -final class GoldenDebugObjectPlacer implements IObjectPlacer { +public final class GoldenDebugObjectPlacer implements IObjectPlacer { private static final int[] GOLDEN_DEBUG_TARGET = parseGoldenDebugTarget(resolveGoldenDebugSpec()); private static final boolean GOLDEN_DEBUG = GOLDEN_DEBUG_TARGET != null; @@ -33,7 +33,7 @@ final class GoldenDebugObjectPlacer implements IObjectPlacer { private final String tag; private final ModuleLog log; - GoldenDebugObjectPlacer(IObjectPlacer delegate, String tag, ModuleLog log) { + public GoldenDebugObjectPlacer(IObjectPlacer delegate, String tag, ModuleLog log) { this.delegate = delegate; this.tag = tag; this.log = log; @@ -70,7 +70,7 @@ final class GoldenDebugObjectPlacer implements IObjectPlacer { } } - static boolean isGoldenDebugChunk(int x, int z) { + public static boolean isGoldenDebugChunk(int x, int z) { return GOLDEN_DEBUG && Math.abs(GOLDEN_DEBUG_TARGET[0] - x) <= GOLDEN_DEBUG_TARGET[2] && Math.abs(GOLDEN_DEBUG_TARGET[1] - z) <= GOLDEN_DEBUG_TARGET[2]; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java index 98b448b57..144077e11 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java @@ -18,14 +18,14 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.engine.object.placement.ObjectPlacements; -import art.arcane.iris.core.modules.IrisPackWorld; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.region.IrisRegion; +import art.arcane.iris.builtin.objects.ObjectHost; +import art.arcane.iris.builtin.objects.ObjectHost.Declaration; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectSettings; +import com.volmit.FeatureAttachment.Target; import com.volmit.service.ObjectsAt; import com.volmit.world.PackWorld; + import java.util.LinkedHashSet; import java.util.List; import java.util.Set; @@ -37,38 +37,28 @@ import java.util.Set; public final class ObjectLocating implements ObjectsAt { @Override public Set objectsAt(PackWorld world, int chunkX, int chunkZ) { - return ObjectModule.placing(engine(world), world.log()).guess(chunkX, chunkZ); + return ObjectPlacing.of(world).guess(chunkX, chunkZ); } @Override public PlacedBy placedBy(PackWorld world, String objectKey) { - Engine engine = engine(world); Set biomes = new LinkedHashSet<>(); - for (IrisBiome biome : engine.getDimension().getReachableBiomes(engine)) { - if (biome != null && placesObject(ObjectPlacements.surface(biome), objectKey)) { - biomes.add(biome.getLoadKey()); - } - } - Set regions = new LinkedHashSet<>(); - for (IrisRegion region : engine.getDimension().getAllRegions(engine)) { - if (region != null && placesObject(ObjectPlacements.surface(region), objectKey)) { - regions.add(region.getLoadKey()); + for (Declaration declaration : ObjectHost.of(world).declarations(ObjectSettings.class)) { + if (!placesObject(declaration.settings().objects(), objectKey)) { + continue; } + (declaration.level() == Target.BIOME ? biomes : regions).add(declaration.key()); } return new PlacedBy(biomes, regions); } - private static boolean placesObject(List placements, String objectKey) { - for (IrisObjectPlacement placement : placements) { - if (placement != null && placement.getPlace().contains(objectKey)) { + private static boolean placesObject(List placements, String objectKey) { + for (ObjectPlacement placement : placements) { + if (placement != null && placement.carvingSupport().supportsSurface() && placement.place().contains(objectKey)) { return true; } } return false; } - - private static Engine engine(PackWorld world) { - return IrisPackWorld.of(world).engine(); - } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java index de1aa17d6..3e90a8e2e 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java @@ -19,6 +19,7 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.IrisStages; +import art.arcane.iris.builtin.objects.ObjectHost; import art.arcane.iris.builtin.objects.ObjectSettings; import art.arcane.iris.builtin.objects.ProceduralObjectSettings; import art.arcane.iris.builtin.objects.RequireSurfaceSupportSettings; @@ -26,10 +27,6 @@ import art.arcane.iris.builtin.objects.SurfaceSupportBufferSettings; import art.arcane.iris.builtin.objects.TreeGrowthSettings; import art.arcane.iris.builtin.objects.UpperObjectsForceSettings; import art.arcane.iris.builtin.objects.UpperObjectsSettings; -import art.arcane.iris.core.modules.IrisMantleChunk; -import art.arcane.iris.core.modules.IrisPackSettings; -import art.arcane.iris.core.modules.IrisPackWorld; -import art.arcane.iris.engine.framework.Engine; import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; @@ -82,20 +79,14 @@ public final class ObjectModule implements IrisModule, ModuleLifecycle { @Override public void warmUp(PackWorld world) { - new ObjectWarmUp(IrisPackWorld.of(world).engine()).warm(); + new ObjectWarmUp(world).warm(); } private static void place(MantleStageContext context) { - IrisMantleChunk chunk = IrisMantleChunk.current(); - placing(chunk.engine(), context.log()).place(chunk.writer(), chunk.chunkX(), chunk.chunkZ(), chunk.context()); + ObjectPlacing.of(context.world()).place(context); } private int reach(PackSettings settings) { - return placing(IrisPackSettings.of(settings).engine(), log).reach(); - } - - /** The engine runtime's object placing, which the module's {@link ObjectsAt} also asks; {@code log} is the module's. */ - public static ObjectPlacing placing(Engine engine, ModuleLog log) { - return engine.getGeneration().state(ObjectPlacing.class, generating -> new ObjectPlacing(generating, log)); + return new PlacementReach(ObjectHost.of(settings), log).ofPack(settings); } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java index 92ae78dc8..e07447045 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,1633 +18,87 @@ package art.arcane.iris.engine.mantle.components; - -import art.arcane.iris.builtin.anchor.PlaceTrait; -import art.arcane.iris.builtin.carve.CarvingMode; -import art.arcane.iris.builtin.carve.CaveAnchorMode; -import art.arcane.iris.builtin.carve.CaveProfile; -import art.arcane.iris.builtin.anchor.ObjectPlaceMode; -import art.arcane.iris.builtin.prepare.AxisRotationClamp; -import art.arcane.iris.engine.object.terrain.carving.CaveProfiles; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.placement.ObjectPlacements; -import art.arcane.iris.engine.object.placement.IrisObjectVacuum; -import art.arcane.iris.core.IrisSettings; -import art.arcane.iris.util.common.data.B; -import art.arcane.volmlib.util.cache.CacheKey; -import art.arcane.iris.engine.IrisComplex; -import art.arcane.iris.engine.UpperDimensionContext; -import art.arcane.iris.engine.mantle.MantleWriter; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.TreeBlockMaterial; -import art.arcane.iris.engine.object.placement.DecayControlPlacer; -import art.arcane.iris.engine.object.placement.IObjectPlacer; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.IrisObjectRotation; -import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; -import art.arcane.iris.engine.object.procedural.ResolvedProceduralObjects; -import art.arcane.iris.engine.object.procedural.IrisProceduralPlacement; -import art.arcane.iris.engine.object.procedural.tree.ResolvedTree; -import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.collection.KMap; -import art.arcane.volmlib.util.collection.KSet; -import art.arcane.iris.util.project.context.ChunkContext; -import art.arcane.volmlib.util.documentation.BlockCoordinates; -import art.arcane.volmlib.util.documentation.ChunkCoordinates; +import art.arcane.iris.builtin.objects.ObjectHost; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectSettings; +import art.arcane.iris.builtin.objects.PlaceableObject; import art.arcane.volmlib.util.math.RNG; -import art.arcane.volmlib.util.matter.MatterCavern; -import art.arcane.volmlib.util.matter.MatterStructurePOI; -import art.arcane.iris.util.project.noise.CNG; -import art.arcane.iris.util.project.noise.NoiseType; +import com.volmit.FeatureAttachment.Target; import com.volmit.ModuleLog; -import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; -import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.volmlib.util.math.IrisBlockVector; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.PackSettings; +import com.volmit.stage.MantleStageContext; +import com.volmit.world.PackWorld; -import java.io.IOException; -import java.util.Locale; -import java.util.Map; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; /** - * Places the objects of the dimension's regions and biomes into the mantle for - * {@link ObjectModule}: surface, cave and upper-dimension objects, and procedural objects, one chunk at a - * time after the caves they anchor in are planned. One per engine runtime. Its reach is the largest - * placement reach of any object the dimension can place. + * Places the objects the dimension's regions and biomes declare, one chunk at a time, into the mantle of a world: the worker + * of {@link ObjectModule}, one per world. It also works out which objects a chunk would get, without placing them, and how far + * the pack's objects reach. */ -public class ObjectPlacing { - private static final CaveProfile DEFAULT_CAVE_PROFILE = new CaveProfile(); - private static final long CAVE_REJECT_LOG_THROTTLE_MS = 5000L; - private static final int BEDROCK_CLEARANCE = 6; - private static final byte LIQUID_FORCED_AIR = 3; - private static final Map CAVE_REJECT_LOG_STATE = new ConcurrentHashMap<>(); - private static final Set MISSING_LOAD_KEY_WARNED = ConcurrentHashMap.newKeySet(); +public final class ObjectPlacing { + private static final int CHUNK_CENTER_OFFSET_BLOCKS = 8; + private static final int CHUNK_SHIFT = 4; + private static final double CHANCE_JITTER = 0.005; - private final Engine engine; + private final ObjectHost host; private final ModuleLog log; - public ObjectPlacing(Engine engine, ModuleLog log) { - this.engine = engine; + private ObjectPlacing(ObjectHost host, ModuleLog log) { + this.host = host; this.log = log; } - private String placementMarker(IrisObject object, int id, String context) { - String key = object == null ? null : object.getLoadKey(); - if (key == null || key.isEmpty() || key.equals("null")) { - String fingerprint = context + "|" + (object == null ? "" : object.getClass().getSimpleName()); - if (MISSING_LOAD_KEY_WARNED.add(fingerprint)) { - java.io.File file = object == null ? null : object.getLoadFile(); - log.warn("Skipping placement marker write: IrisObject has no loadKey (context=" + context - + ", file=" + (file == null ? "" : file.getPath()) + "). " - + "This would previously produce 'Couldn't find Object: null' warnings on chunk reload."); - } - return null; - } - return key + "@" + id; + /** The object placing of {@code world}. */ + public static ObjectPlacing of(PackWorld world) { + return world.state(ObjectPlacing.class, generating -> new ObjectPlacing(ObjectHost.of(generating), generating.log())); } - private static boolean isTreePlacement(IrisObject object, IrisObjectPlacement placement) { - String key = object == null ? null : object.getLoadKey(); - return (key != null && key.startsWith("trees/")) - || (placement != null && placement.getTrees() != null && placement.getTrees().isNotEmpty()); + /** Places what originates in the chunk {@code context} generates. */ + void place(MantleStageContext context) { + new ChunkObjectPlacing(host, log, context).place(); } - private static void writeTreeMaterial(IObjectPlacer placer, int x, int y, int z, PlatformBlockState data) { - placer.setData(x, y, z, TreeBlockMaterial.of(data)); - } - - /** Places what originates in the chunk at chunk coordinates {@code x}, {@code z} into {@code writer}. */ - public void place(MantleWriter writer, int x, int z, ChunkContext context) { - IrisComplex complex = context.getComplex(); - boolean traceRegen = isRegenTraceThread(); - RNG rng = applyNoise(x, z, CacheKey.key(x, z) + engine.getSeedManager().getMantle()); - int xxx = 8 + (x << 4); - int zzz = 8 + (z << 4); - IrisRegion region = complex.getRegionStream().get(xxx, zzz); - IrisBiome surfaceBiome = complex.getTrueBiomeStream().get(xxx, zzz); - int surfaceY = engine.getHeight(xxx, zzz, true); - IrisBiome caveBiome = resolveCaveObjectBiome(xxx, zzz, surfaceY, surfaceBiome); - if (IrisSettings.get().getGeneral().isDebug() && (x & 31) == 0 && (z & 31) == 0) { - int carvedBlocks = 0; - int minY = 1; - int maxY = Math.min(engine.getHeight() - 1, surfaceY - 14); - for (int sy = minY; sy < maxY; sy++) { - if (writer.isCarved(8 + (x << 4), sy, 8 + (z << 4))) { - carvedBlocks++; - } - } - log.debug("Cave object diag: chunk=" + x + "," + z - + " surfaceBiome=" + surfaceBiome.getLoadKey() - + " caveBiome=" + caveBiome.getLoadKey() - + " surfaceY=" + surfaceY - + " maxAnchorY=" + maxY - + " carvedAtCenter=" + carvedBlocks - + " biomeCarvingObjects=" + ObjectPlacements.carving(caveBiome).size() - + " regionCarvingObjects=" + ObjectPlacements.carving(region).size() - + " sameBiome=" + (caveBiome == surfaceBiome || java.util.Objects.equals(caveBiome.getLoadKey(), surfaceBiome.getLoadKey()))); - } - if (traceRegen) { - log.debug("Regen object layer start: chunk=" + x + "," + z - + " surfaceBiome=" + surfaceBiome.getLoadKey() - + " caveBiome=" + caveBiome.getLoadKey() - + " region=" + region.getLoadKey() - + " biomeSurfacePlacers=" + ObjectPlacements.surface(surfaceBiome).size() - + " biomeCavePlacers=" + ObjectPlacements.carving(caveBiome).size() - + " regionSurfacePlacers=" + ObjectPlacements.surface(region).size() - + " regionCavePlacers=" + ObjectPlacements.carving(region).size()); - } - ObjectPlacementSummary summary = placeObjects(writer, rng, x, z, surfaceBiome, caveBiome, region, complex, traceRegen); - placeProceduralObjects(writer, rng, x, z, surfaceBiome, caveBiome, region); - UpperDimensionContext upperCtx = engine.getUpperContext(); - IrisDimension dimension = engine.getDimension(); - if (upperCtx != null && ObjectPlacements.upperObjects(dimension)) { - placeUpperObjects(writer, rng, x, z, xxx, zzz, surfaceY, upperCtx, dimension, complex, traceRegen); - } - if (traceRegen) { - log.debug("Regen object layer done: chunk=" + x + "," + z - + " biomeSurfacePlacersChecked=" + summary.biomeSurfacePlacersChecked() - + " biomeSurfacePlacersTriggered=" + summary.biomeSurfacePlacersTriggered() - + " biomeCavePlacersChecked=" + summary.biomeCavePlacersChecked() - + " biomeCavePlacersTriggered=" + summary.biomeCavePlacersTriggered() - + " regionSurfacePlacersChecked=" + summary.regionSurfacePlacersChecked() - + " regionSurfacePlacersTriggered=" + summary.regionSurfacePlacersTriggered() - + " regionCavePlacersChecked=" + summary.regionCavePlacersChecked() - + " regionCavePlacersTriggered=" + summary.regionCavePlacersTriggered() - + " objectAttempts=" + summary.objectAttempts() - + " objectPlaced=" + summary.objectPlaced() - + " objectRejected=" + summary.objectRejected() - + " objectNull=" + summary.objectNull() - + " objectErrors=" + summary.objectErrors()); - } - } - - private RNG applyNoise(int x, int z, long seed) { - CNG noise = CNG.signatureFast(new RNG(seed), NoiseType.WHITE, NoiseType.GLOB); - return new RNG((long) (seed * noise.noise(x, z))); - } - - private IrisBiome resolveCaveObjectBiome(int x, int z, int surfaceY, IrisBiome surfaceBiome) { - int legacySampleY = Math.max(1, surfaceY - 48); - IrisBiome legacyCaveBiome = engine.getCaveBiome(x, legacySampleY, z); - if (legacyCaveBiome == null) { - legacyCaveBiome = surfaceBiome; - } - - int[] sampleDepths = new int[]{48, 80, 112}; - IrisBiome ladderChoice = null; - for (int sampleDepth : sampleDepths) { - int sampleY = Math.max(1, surfaceY - sampleDepth); - IrisBiome sampled = engine.getCaveBiome(x, sampleY, z); - boolean sameSurface = sampled == surfaceBiome; - if (!sameSurface && sampled != null && surfaceBiome != null) { - String sampledKey = sampled.getLoadKey(); - String surfaceKey = surfaceBiome.getLoadKey(); - sameSurface = sampledKey != null && sampledKey.equals(surfaceKey); - } - - if (sampled == null || sameSurface) { - continue; - } - - if (!ObjectPlacements.carving(sampled).isEmpty()) { - ladderChoice = sampled; - } - } - - if (ladderChoice != null) { - return ladderChoice; - } - - return legacyCaveBiome; - } - - @ChunkCoordinates - private ObjectPlacementSummary placeObjects(MantleWriter writer, RNG rng, int x, int z, IrisBiome surfaceBiome, IrisBiome caveBiome, IrisRegion region, IrisComplex complex, boolean traceRegen) { - int biomeSurfaceChecked = 0; - int biomeSurfaceTriggered = 0; - int biomeCaveChecked = 0; - int biomeCaveTriggered = 0; - int regionSurfaceChecked = 0; - int regionSurfaceTriggered = 0; - int regionCaveChecked = 0; - int regionCaveTriggered = 0; - int attempts = 0; - int placed = 0; - int rejected = 0; - int nullObjects = 0; - int errors = 0; - CaveProfile biomeCaveProfile = resolveCaveProfile(CaveProfiles.declaredBy(caveBiome), CaveProfiles.declaredBy(region)); - CaveProfile regionCaveProfile = resolveCaveProfile(CaveProfiles.declaredBy(region), CaveProfiles.declaredBy(caveBiome)); - CaveAnchorCache caveAnchorCache = new CaveAnchorCache(); - - for (IrisObjectPlacement i : ObjectPlacements.surface(surfaceBiome)) { - biomeSurfaceChecked++; - boolean chance = rng.chance(i.getChance() + rng.d(-0.005, 0.005)); - if (traceRegen) { - log.debug("Regen object placer chance: chunk=" + x + "," + z - + " scope=biome-surface" - + " chanceResult=" + chance - + " chanceBase=" + i.getChance() - + " densityMid=" + i.getDensity() - + " objects=" + i.getPlace().size()); - } - if (chance) { - biomeSurfaceTriggered++; - try { - ObjectPlacementResult result = placeObject(writer, rng, x << 4, z << 4, i, complex, traceRegen, x, z, "biome-surface"); - attempts += result.attempts(); - placed += result.placed(); - rejected += result.rejected(); - nullObjects += result.nullObjects(); - errors += result.errors(); - } catch (Throwable e) { - errors++; - log.error("Failed to place objects in the following biome: " + surfaceBiome.getName(), e); - log.error("Object(s) " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ").", null); - log.error("Are these objects missing?", null); + /** The keys of the objects the chunk would get, as far as the chunk's surface objects go. */ + public Set guess(int chunkX, int chunkZ) { + RNG rng = host.chunkRandom(chunkX, chunkZ); + int centerX = (chunkX << CHUNK_SHIFT) + CHUNK_CENTER_OFFSET_BLOCKS; + int centerZ = (chunkZ << CHUNK_SHIFT) + CHUNK_CENTER_OFFSET_BLOCKS; + List> entries = host.columnSettings().at(ObjectSettings.class, centerX, centerZ); + Set keys = new HashSet<>(); + for (Target level : new Target[]{Target.BIOME, Target.REGION}) { + for (Entry entry : entries) { + if (entry.level() == level) { + guessFrom(entry.value(), rng, chunkX, chunkZ, keys); } } } - - for (IrisObjectPlacement i : ObjectPlacements.carving(caveBiome)) { - if (!i.getCarvingSupport().supportsCarving()) { - continue; - } - biomeCaveChecked++; - boolean chance = rng.chance(i.getChance()); - if (traceRegen) { - log.debug("Regen object placer chance: chunk=" + x + "," + z - + " scope=biome-cave" - + " chanceResult=" + chance - + " chanceBase=" + i.getChance() - + " densityMid=" + i.getDensity() - + " objects=" + i.getPlace().size()); - } - if (chance) { - biomeCaveTriggered++; - try { - ObjectPlacementResult result = placeCaveObject(writer, rng, x, z, i, biomeCaveProfile, complex, traceRegen, x, z, "biome-cave", caveBiome.getLoadKey(), caveAnchorCache); - attempts += result.attempts(); - placed += result.placed(); - rejected += result.rejected(); - nullObjects += result.nullObjects(); - errors += result.errors(); - } catch (Throwable e) { - errors++; - log.error("Failed to place cave objects in the following biome: " + caveBiome.getName(), e); - log.error("Object(s) " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ").", null); - log.error("Are these objects missing?", null); - } - } - } - - for (IrisObjectPlacement i : ObjectPlacements.surface(region)) { - regionSurfaceChecked++; - boolean chance = rng.chance(i.getChance() + rng.d(-0.005, 0.005)); - if (traceRegen) { - log.debug("Regen object placer chance: chunk=" + x + "," + z - + " scope=region-surface" - + " chanceResult=" + chance - + " chanceBase=" + i.getChance() - + " densityMid=" + i.getDensity() - + " objects=" + i.getPlace().size()); - } - if (chance) { - regionSurfaceTriggered++; - try { - ObjectPlacementResult result = placeObject(writer, rng, x << 4, z << 4, i, complex, traceRegen, x, z, "region-surface"); - attempts += result.attempts(); - placed += result.placed(); - rejected += result.rejected(); - nullObjects += result.nullObjects(); - errors += result.errors(); - } catch (Throwable e) { - errors++; - log.error("Failed to place objects in the following region: " + region.getName(), e); - log.error("Object(s) " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ").", null); - log.error("Are these objects missing?", null); - } - } - } - - for (IrisObjectPlacement i : ObjectPlacements.carving(region)) { - if (!i.getCarvingSupport().supportsCarving()) { - continue; - } - regionCaveChecked++; - boolean chance = rng.chance(i.getChance()); - if (traceRegen) { - log.debug("Regen object placer chance: chunk=" + x + "," + z - + " scope=region-cave" - + " chanceResult=" + chance - + " chanceBase=" + i.getChance() - + " densityMid=" + i.getDensity() - + " objects=" + i.getPlace().size()); - } - if (chance) { - regionCaveTriggered++; - try { - ObjectPlacementResult result = placeCaveObject(writer, rng, x, z, i, regionCaveProfile, complex, traceRegen, x, z, "region-cave", null, caveAnchorCache); - attempts += result.attempts(); - placed += result.placed(); - rejected += result.rejected(); - nullObjects += result.nullObjects(); - errors += result.errors(); - } catch (Throwable e) { - errors++; - log.error("Failed to place cave objects in the following region: " + region.getName(), e); - log.error("Object(s) " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ").", null); - log.error("Are these objects missing?", null); - } - } - } - - return new ObjectPlacementSummary( - biomeSurfaceChecked, - biomeSurfaceTriggered, - biomeCaveChecked, - biomeCaveTriggered, - regionSurfaceChecked, - regionSurfaceTriggered, - regionCaveChecked, - regionCaveTriggered, - attempts, - placed, - rejected, - nullObjects, - errors - ); + return keys; } - @ChunkCoordinates - private void placeProceduralObjects(MantleWriter writer, RNG rng, int x, int z, IrisBiome surfaceBiome, IrisBiome caveBiome, IrisRegion region) { - CaveProfile surfaceCaveProfile = resolveCaveProfile(CaveProfiles.declaredBy(surfaceBiome), CaveProfiles.declaredBy(region)); - CaveProfile regionCaveProfile = resolveCaveProfile(CaveProfiles.declaredBy(region), caveBiome == null ? null : CaveProfiles.declaredBy(caveBiome)); - placeProceduralFrom(writer, rng, x, z, ObjectPlacements.procedural(surfaceBiome), surfaceBiome.getName(), surfaceCaveProfile, surfaceBiome.getLoadKey()); - placeProceduralFrom(writer, rng, x, z, ObjectPlacements.procedural(region), region.getName(), regionCaveProfile, null); - if (caveBiome != null && caveBiome != surfaceBiome) { - CaveProfile caveProfile = resolveCaveProfile(CaveProfiles.declaredBy(caveBiome), CaveProfiles.declaredBy(region)); - placeProceduralFrom(writer, rng, x, z, ObjectPlacements.procedural(caveBiome), caveBiome.getName(), caveProfile, caveBiome.getLoadKey()); - } - } - - @ChunkCoordinates - private void placeProceduralFrom( - MantleWriter writer, - RNG rng, - int x, - int z, - ResolvedProceduralObjects proceduralObjects, - String scope, - CaveProfile caveProfile, - String expectedCaveBiomeKey - ) { - if (proceduralObjects == null || proceduralObjects.isEmpty()) { - return; - } - - int blockX = x << 4; - int blockZ = z << 4; - boolean golden = GoldenDebugObjectPlacer.isGoldenDebugChunk(x, z); - CaveAnchorCache caveAnchorCache = new CaveAnchorCache(); - for (IrisProceduralPlacement p : proceduralObjects.getAllPlacements()) { - boolean treePlacement = p instanceof ResolvedTree; - boolean chancePassed = passesProceduralChance(rng, p.getChance()); - if (golden) { - log.debug("Goldendebug procedural chance: chunk=" + x + "," + z - + " scope=" + scope - + " placement=" + p.getName() - + " passed=" + chancePassed); - } - if (!chancePassed) { - continue; - } - - IrisObjectPlacement placement = p.asPlacement(); - boolean carving = placement.getCarvingSupport() == CarvingMode.CARVING_ONLY; - CaveAnchorMode anchorMode = resolveAnchorMode(placement, caveProfile); - if (placement.getMode().placeMode().has(PlaceTrait.UPSIDE_DOWN)) { - anchorMode = CaveAnchorMode.CEILING; - } - int anchorScanStep = resolveAnchorScanStep(caveProfile); - int minDepthBelowSurface = resolveObjectMinDepthBelowSurface(caveProfile); - int anchorSearchAttempts = resolveAnchorSearchAttempts(caveProfile); - IObjectPlacer basePlacer = p.isPlausible() ? new DecayControlPlacer(writer) : writer; - IObjectPlacer placer = golden ? new GoldenDebugObjectPlacer(basePlacer, scope + "/" + p.getName(), log) : basePlacer; - int density = Math.max(1, p.getDensity()); - for (int i = 0; i < density; i++) { - IrisObject variant = p.getVariantObject(engine.getData(), rng); - if (variant == null) { - if (golden) { - log.debug("Goldendebug procedural pick: chunk=" + x + "," + z - + " placement=" + p.getName() - + " densityIndex=" + i - + " variant=null"); - } - continue; - } - CavePlacementAnchor caveAnchor = null; - if (carving) { - caveAnchor = findCavePlacementAnchor( - writer, - rng, - blockX, - blockZ, - anchorMode, - anchorScanStep, - minDepthBelowSurface, - anchorSearchAttempts, - expectedCaveBiomeKey, - placement.isUnderwater(), - caveAnchorCache - ); - } - if (carving && caveAnchor == null) { - if (golden) { - log.debug("Goldendebug procedural cave anchor rejected: chunk=" + x + "," + z - + " placement=" + p.getName() - + " minDepthBelowSurface=" + minDepthBelowSurface); - } - continue; - } - int xx = caveAnchor == null ? rng.i(blockX, blockX + 16) : caveAnchor.x(); - int zz = caveAnchor == null ? rng.i(blockZ, blockZ + 16) : caveAnchor.z(); - int id = rng.i(0, Integer.MAX_VALUE); - if (golden) { - KList pool = p.getVariantObjects(engine.getData()); - log.debug("Goldendebug procedural pick: chunk=" + x + "," + z - + " placement=" + p.getName() - + " densityIndex=" + i - + " variant=" + variant.getLoadKey() - + " variantIndex=" + pool.indexOf(variant) + "/" + pool.size() - + " xx=" + xx - + " zz=" + zz - + " mode=" + placement.getMode() - + " carving=" + carving); - } - try { - int placeResult = -1; - CaveObjectPlacementTransaction.CommitResult commitResult = CaveObjectPlacementTransaction.CommitResult.EMPTY; - if (carving) { - int caveFloorY = caveAnchor.y(); - if (golden) { - log.debug("Goldendebug procedural caveFloor: chunk=" + x + "," + z - + " placement=" + p.getName() - + " xx=" + xx - + " zz=" + zz - + " caveFloorY=" + caveFloorY); - } - IrisObjectPlacement effectivePlacement = resolveCavePlacement(placement, variant, caveProfile); - ContainedPlacementResult contained = placeContainedCaveObject( - placer, - variant, - xx, - caveFloorY, - zz, - effectivePlacement, - minDepthBelowSurface, - id, - "procedural", - treePlacement, - rng - ); - placeResult = contained.resultY(); - commitResult = contained.commitResult(); - } else { - String marker = placementMarker(variant, id, "procedural"); - placeResult = variant.place(xx, -1, zz, placer, placement, rng, (b, data) -> { - if (marker != null) { - placer.setData(b.getX(), b.getY(), b.getZ(), marker); - } - if (treePlacement && marker != null) { - writeTreeMaterial(placer, b.getX(), b.getY(), b.getZ(), data); - } - }, null, engine.getData()); - } - if (golden) { - log.debug("Goldendebug procedural result: chunk=" + x + "," + z - + " placement=" + p.getName() - + " variant=" + variant.getLoadKey() - + " xx=" + xx - + " zz=" + zz - + " resultY=" + placeResult - + " commit=" + commitResult); - } - } catch (Throwable e) { - log.error("Failed to place procedural object '" + p.getName() + "' in " + scope, e); - } + private void guessFrom(ObjectSettings settings, RNG rng, int chunkX, int chunkZ, Set keys) { + for (ObjectPlacement placement : settings.objects()) { + if (placement.carvingSupport().supportsSurface() && rng.chance(placement.chance() + rng.d(-CHANCE_JITTER, CHANCE_JITTER))) { + keys.addAll(guessPlacedKeys(rng, chunkX, chunkZ, placement)); } } } - static boolean passesProceduralChance(RNG rng, double chance) { - if (chance <= 0.0) { - return false; + private Set guessPlacedKeys(RNG rng, int x, int z, ObjectPlacement placement) { + Set keys = new HashSet<>(); + for (int i = 0; i < host.density(placement, rng, x, z); i++) { + Optional picked = host.pickScaled(placement, rng); + picked.ifPresent(object -> keys.add(object.key())); } - if (chance >= 1.0) { - return true; - } - return rng.chance(Math.max(0.0, Math.min(1.0, chance + rng.d(-0.005, 0.005)))); - } - - private CavePlacementAnchor findCavePlacementAnchor( - MantleWriter writer, - RNG rng, - int minX, - int minZ, - CaveAnchorMode anchorMode, - int anchorScanStep, - int minDepthBelowSurface, - int searchAttempts, - String expectedCaveBiomeKey, - boolean underwater, - CaveAnchorCache anchorCache - ) { - for (int search = 0; search < searchAttempts; search++) { - int candidateX = rng.i(minX, minX + 16); - int candidateZ = rng.i(minZ, minZ + 16); - int candidateY = findCaveAnchorY( - writer, - rng, - candidateX, - candidateZ, - anchorMode, - anchorScanStep, - minDepthBelowSurface, - anchorCache - ); - if (candidateY < 0 - || caveAnchorBiomeConflicts(candidateX, candidateY, candidateZ, expectedCaveBiomeKey) - || !acceptsCaveAnchorFluid( - underwater, - writer.getDataIfPresent(candidateX, candidateY, candidateZ, MatterCavern.class), - candidateY, - engine.getDimension().getCaveLavaHeight())) { - continue; - } - return new CavePlacementAnchor(candidateX, candidateY, candidateZ); - } - return null; - } - - static boolean acceptsCaveAnchorFluid(boolean underwater, MatterCavern cavern, int y, int lavaHeight) { - if (cavern == null || !cavern.isCavern()) { - return false; - } - if (underwater || cavern.getLiquid() == LIQUID_FORCED_AIR) { - return true; - } - return cavern.isAir() && y > lavaHeight; - } - - private ContainedPlacementResult placeContainedCaveObject( - IObjectPlacer placer, - IrisObject object, - int x, - int anchorY, - int z, - IrisObjectPlacement placement, - int minDepthBelowSurface, - int id, - String markerContext, - boolean treePlacement, - RNG rng - ) { - CaveObjectPlacementTransaction transaction = new CaveObjectPlacementTransaction(placer, anchorY, minDepthBelowSurface); - int placeY = anchorY; - if (placement.getMode().placeMode().has(PlaceTrait.UPSIDE_DOWN)) { - placeY = Math.max(1, transaction.getCaveCeiling(x, z) - 1 - Math.floorDiv(object.getH(), 2)); - } - String marker = placementMarker(object, id, markerContext); - int result = object.place(x, placeY, z, transaction, placement, rng, (block, data) -> { - if (marker != null) { - transaction.setData(block.getX(), block.getY(), block.getZ(), marker); - } - if (treePlacement && marker != null) { - writeTreeMaterial(transaction, block.getX(), block.getY(), block.getZ(), data); - } - if (placement.isDolphinTarget() && placement.isUnderwater() && B.isStorageChest(data)) { - transaction.setData(block.getX(), block.getY(), block.getZ(), MatterStructurePOI.BURIED_TREASURE); - } - }, null, engine.getData()); - if (result < 0) { - transaction.discard(); - return new ContainedPlacementResult(result, CaveObjectPlacementTransaction.CommitResult.EMPTY); - } - return new ContainedPlacementResult(result, transaction.commit()); - } - - @BlockCoordinates - private ObjectPlacementResult placeObject( - MantleWriter writer, - RNG rng, - int x, - int z, - IrisObjectPlacement objectPlacement, - IrisComplex complex, - boolean traceRegen, - int chunkX, - int chunkZ, - String scope - ) { - int attempts = 0; - int placed = 0; - int rejected = 0; - int nullObjects = 0; - int errors = 0; - int density = objectPlacement.getDensity(rng, x, z, engine.getData()); - boolean golden = GoldenDebugObjectPlacer.isGoldenDebugChunk(chunkX, chunkZ); - - for (int i = 0; i < density; i++) { - attempts++; - IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(complex, rng), engine); - if (v == null) { - nullObjects++; - if (traceRegen) { - log.debug("Regen object placement null object: chunk=" + chunkX + "," + chunkZ - + " scope=" + scope - + " densityIndex=" + i - + " density=" + density - + " placementKeys=" + objectPlacement.getPlace().toString(",")); - } - continue; - } - int xx = rng.i(x, x + 16); - int zz = rng.i(z, z + 16); - IrisObjectPlacement effectivePlacement = resolveEffectivePlacement(objectPlacement, v); - boolean treePlacement = isTreePlacement(v, effectivePlacement); - int id = rng.i(0, Integer.MAX_VALUE); - IObjectPlacer placePlacer = golden ? new GoldenDebugObjectPlacer(writer, scope + "/" + v.getLoadKey(), log) : writer; - if (golden) { - log.debug("Goldendebug object attempt: chunk=" + chunkX + "," + chunkZ - + " scope=" + scope - + " object=" + v.getLoadKey() - + " densityIndex=" + i - + " xx=" + xx - + " zz=" + zz - + " mode=" + effectivePlacement.getMode()); - } - try { - String marker = placementMarker(v, id, "surface"); - int result = v.place(xx, -1, zz, placePlacer, effectivePlacement, rng, (b, data) -> { - if (marker != null) { - writer.setData(b.getX(), b.getY(), b.getZ(), marker); - } - if (treePlacement && marker != null) { - writeTreeMaterial(writer, b.getX(), b.getY(), b.getZ(), data); - } - if (effectivePlacement.isDolphinTarget() && effectivePlacement.isUnderwater() && B.isStorageChest(data)) { - writer.setData(b.getX(), b.getY(), b.getZ(), MatterStructurePOI.BURIED_TREASURE); - } - }, null, engine.getData()); - - if (result >= 0) { - placed++; - } else { - rejected++; - } - - if (golden) { - log.debug("Goldendebug object result: chunk=" + chunkX + "," + chunkZ - + " scope=" + scope - + " object=" + v.getLoadKey() - + " resultY=" + result - + " fallback=surface"); - } - - if (traceRegen) { - log.debug("Regen object placement result: chunk=" + chunkX + "," + chunkZ - + " scope=" + scope - + " object=" + v.getLoadKey() - + " resultY=" + result - + " px=" + xx - + " pz=" + zz - + " fallback=surface" - + " densityIndex=" + i - + " density=" + density); - } - } catch (Throwable e) { - errors++; - log.error("Regen object placement exception: chunk=" + chunkX + "," + chunkZ - + " scope=" + scope - + " object=" + v.getLoadKey() - + " densityIndex=" + i - + " density=" + density - + " error=" + e.getClass().getSimpleName() + ":" + e.getMessage(), e); - } - } - - return new ObjectPlacementResult(attempts, placed, rejected, nullObjects, errors); - } - - @ChunkCoordinates - private boolean caveAnchorBiomeConflicts(int x, int y, int z, String expectedCaveBiomeKey) { - if (expectedCaveBiomeKey == null) { - return false; - } - IrisBiome at = engine.getCaveBiome(x, y, z); - IrisBiome surface = engine.getSurfaceBiome(x, z); - return caveAnchorBiomeConflicts(at, surface, expectedCaveBiomeKey); - } - - static boolean caveAnchorBiomeConflicts(IrisBiome at, IrisBiome surface, String expectedCaveBiomeKey) { - if (expectedCaveBiomeKey == null || at == null) { - return false; - } - String atKey = at.getLoadKey(); - if (atKey == null || atKey.equals(expectedCaveBiomeKey)) { - return false; - } - if (surface != null && atKey.equals(surface.getLoadKey())) { - return false; - } - return true; - } - - private ObjectPlacementResult placeCaveObject( - MantleWriter writer, - RNG rng, - int chunkX, - int chunkZ, - IrisObjectPlacement objectPlacement, - CaveProfile caveProfile, - IrisComplex complex, - boolean traceRegen, - int metricChunkX, - int metricChunkZ, - String scope, - String expectedCaveBiomeKey, - CaveAnchorCache anchorCache - ) { - int attempts = 0; - int placed = 0; - int rejected = 0; - int nullObjects = 0; - int errors = 0; - int minX = chunkX << 4; - int minZ = chunkZ << 4; - int density = objectPlacement.getDensity(rng, minX, minZ, engine.getData()); - CaveAnchorMode anchorMode = resolveAnchorMode(objectPlacement, caveProfile); - if (objectPlacement.getMode().placeMode().has(PlaceTrait.UPSIDE_DOWN)) { - anchorMode = CaveAnchorMode.CEILING; - } - int anchorScanStep = resolveAnchorScanStep(caveProfile); - int objectMinDepthBelowSurface = resolveObjectMinDepthBelowSurface(caveProfile); - int anchorSearchAttempts = resolveAnchorSearchAttempts(caveProfile); - - for (int i = 0; i < density; i++) { - attempts++; - IrisObject object = objectPlacement.getScale().get(rng, objectPlacement.getObject(complex, rng), engine); - if (object == null) { - nullObjects++; - if (traceRegen) { - log.debug("Regen cave object placement null object: chunk=" + metricChunkX + "," + metricChunkZ - + " scope=" + scope - + " densityIndex=" + i - + " density=" + density - + " placementKeys=" + objectPlacement.getPlace().toString(",")); - } - logCaveReject( - scope, - "NULL_OBJECT", - metricChunkX, - metricChunkZ, - objectPlacement, - null, - i, - density, - anchorMode, - anchorSearchAttempts, - anchorScanStep, - objectMinDepthBelowSurface, - null, - null - ); - continue; - } - - CavePlacementAnchor anchor = findCavePlacementAnchor( - writer, - rng, - minX, - minZ, - anchorMode, - anchorScanStep, - objectMinDepthBelowSurface, - anchorSearchAttempts, - expectedCaveBiomeKey, - objectPlacement.isUnderwater(), - anchorCache - ); - - if (anchor == null) { - rejected++; - logCaveReject( - scope, - "NO_ANCHOR", - metricChunkX, - metricChunkZ, - objectPlacement, - object, - i, - density, - anchorMode, - anchorSearchAttempts, - anchorScanStep, - objectMinDepthBelowSurface, - null, - null - ); - continue; - } - - int x = anchor.x(); - int y = anchor.y(); - int z = anchor.z(); - - int id = rng.i(0, Integer.MAX_VALUE); - IrisObjectPlacement effectivePlacement = resolveCavePlacement(objectPlacement, object, caveProfile); - - try { - ContainedPlacementResult contained = placeContainedCaveObject( - writer, - object, - x, - y, - z, - effectivePlacement, - objectMinDepthBelowSurface, - id, - "cave", - isTreePlacement(object, effectivePlacement), - rng - ); - int result = contained.resultY(); - boolean wroteBlocks = contained.commitResult() == CaveObjectPlacementTransaction.CommitResult.COMMITTED; - if (wroteBlocks) { - placed++; - } else { - rejected++; - String rejectReason; - if (result < 0) { - rejectReason = "PLACE_NEGATIVE"; - } else if (contained.commitResult() == CaveObjectPlacementTransaction.CommitResult.REJECTED_BOUNDS) { - rejectReason = "CONTAINMENT"; - } else { - rejectReason = "NO_WRITES"; - } - logCaveReject( - scope, - rejectReason, - metricChunkX, - metricChunkZ, - objectPlacement, - object, - i, - density, - anchorMode, - anchorSearchAttempts, - anchorScanStep, - objectMinDepthBelowSurface, - y, - null - ); - } - - if (traceRegen) { - log.debug("Regen cave object placement result: chunk=" + metricChunkX + "," + metricChunkZ - + " scope=" + scope - + " object=" + object.getLoadKey() - + " resultY=" + result - + " anchorY=" + y - + " px=" + x - + " pz=" + z - + " wroteBlocks=" + wroteBlocks - + " densityIndex=" + i - + " density=" + density); - } - } catch (Throwable e) { - errors++; - log.error("Regen cave object placement exception: chunk=" + metricChunkX + "," + metricChunkZ - + " scope=" + scope - + " object=" + object.getLoadKey() - + " densityIndex=" + i - + " density=" + density - + " error=" + e.getClass().getSimpleName() + ":" + e.getMessage(), e); - logCaveReject( - scope, - "EXCEPTION", - metricChunkX, - metricChunkZ, - objectPlacement, - object, - i, - density, - anchorMode, - anchorSearchAttempts, - anchorScanStep, - objectMinDepthBelowSurface, - y, - e - ); - } - } - - return new ObjectPlacementResult(attempts, placed, rejected, nullObjects, errors); - } - - @ChunkCoordinates - private void placeUpperObjects( - MantleWriter writer, - RNG rng, - int chunkX, - int chunkZ, - int centerX, - int centerZ, - int lowerSurfaceCenterY, - UpperDimensionContext upperCtx, - IrisDimension dimension, - IrisComplex complex, - boolean traceRegen - ) { - IrisBiome upperBiome = upperCtx.getUpperBiome(centerX, centerZ); - IrisRegion upperRegion = upperCtx.getUpperRegion(centerX, centerZ); - if (upperBiome == null && upperRegion == null) { - return; - } - - boolean forcePlace = ObjectPlacements.upperObjectsForced(dimension); - if (upperBiome != null) { - for (IrisObjectPlacement i : ObjectPlacements.surface(upperBiome)) { - if (!rng.chance(i.getChance() + rng.d(-0.005, 0.005))) { - continue; - } - try { - placeUpperObject(writer, rng, chunkX, chunkZ, i, upperCtx, dimension, complex, forcePlace, traceRegen, "upper-biome-surface"); - } catch (Throwable e) { - log.error("Failed to place upper-dimension objects in biome " + upperBiome.getName() - + ": " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ")", e); - } - } - } - - if (upperRegion != null) { - for (IrisObjectPlacement i : ObjectPlacements.surface(upperRegion)) { - if (!rng.chance(i.getChance() + rng.d(-0.005, 0.005))) { - continue; - } - try { - placeUpperObject(writer, rng, chunkX, chunkZ, i, upperCtx, dimension, complex, forcePlace, traceRegen, "upper-region-surface"); - } catch (Throwable e) { - log.error("Failed to place upper-dimension objects in region " + upperRegion.getName() - + ": " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ")", e); - } - } - } - } - - @ChunkCoordinates - private void placeUpperObject( - MantleWriter writer, - RNG rng, - int chunkX, - int chunkZ, - IrisObjectPlacement objectPlacement, - UpperDimensionContext upperCtx, - IrisDimension dimension, - IrisComplex complex, - boolean forcePlace, - boolean traceRegen, - String scope - ) { - int chunkHeight = engine.getHeight(); - int upperGap = dimension.getUpperDimensionGap(); - int minX = chunkX << 4; - int minZ = chunkZ << 4; - int density = objectPlacement.getDensity(rng, minX, minZ, engine.getData()); - - for (int i = 0; i < density; i++) { - IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(complex, rng), engine); - if (v == null) { - continue; - } - - int xx = rng.i(minX, minX + 16); - int zz = rng.i(minZ, minZ + 16); - int columnLowerSurfaceY = engine.getHeight(xx, zz, true); - int rawUpperSurface = upperCtx.getUpperSurfaceY(xx, zz); - int upperSurfaceY = Math.max(rawUpperSurface, columnLowerSurfaceY + upperGap); - if (upperSurfaceY >= chunkHeight - 2) { - continue; - } - - int halfH = Math.floorDiv(v.getH(), 2); - int anchorY = upperSurfaceY - 1 - halfH; - if (anchorY <= 1) { - continue; - } - - int id = rng.i(0, Integer.MAX_VALUE); - IrisObjectPlacement placement = objectPlacement.toPlacement(v.getLoadKey()); - placement.setMode(ObjectPlaceMode.CENTER_HEIGHT); - placement.setRotation(buildUpsideDownRotation()); - placement.setCarvingSupport(CarvingMode.ANYWHERE); - if (forcePlace) { - placement.setForcePlace(true); - } - boolean treePlacement = isTreePlacement(v, objectPlacement); - String marker = placementMarker(v, id, "upper"); - - int result = v.place(xx, anchorY, zz, writer, placement, rng, (b, data) -> { - if (marker != null) { - writer.setData(b.getX(), b.getY(), b.getZ(), marker); - } - if (treePlacement && marker != null) { - writeTreeMaterial(writer, b.getX(), b.getY(), b.getZ(), data); - } - if (placement.isDolphinTarget() && placement.isUnderwater() && B.isStorageChest(data)) { - writer.setData(b.getX(), b.getY(), b.getZ(), MatterStructurePOI.BURIED_TREASURE); - } - }, null, engine.getData()); - - if (traceRegen) { - log.debug("Upper object placement: chunk=" + chunkX + "," + chunkZ - + " scope=" + scope - + " object=" + v.getLoadKey() - + " anchorY=" + anchorY - + " upperSurfaceY=" + upperSurfaceY - + " resultY=" + result - + " forcePlace=" + forcePlace); - } - } - } - - private IrisObjectRotation buildUpsideDownRotation() { - IrisObjectRotation rt = new IrisObjectRotation(); - rt.setEnabled(true); - rt.setXAxis(AxisRotationClamp.of(true, true, 180D, 180D, 90D)); - rt.setYAxis(AxisRotationClamp.of(true, false, 0D, 0D, 90D)); - rt.setZAxis(new AxisRotationClamp()); - return rt; - } - - private void logCaveReject( - String scope, - String reason, - int chunkX, - int chunkZ, - IrisObjectPlacement objectPlacement, - IrisObject object, - int densityIndex, - int density, - CaveAnchorMode anchorMode, - int anchorSearchAttempts, - int anchorScanStep, - int objectMinDepthBelowSurface, - Integer anchorY, - Throwable error - ) { - if (!IrisSettings.get().getGeneral().isDebug()) { - return; - } - - String placementKeys = objectPlacement == null ? "none" : objectPlacement.getPlace().toString(","); - String objectKey = object == null ? "null" : object.getLoadKey(); - String throttleKey = scope + "|" + reason + "|" + placementKeys + "|" + objectKey; - CaveRejectLogState state = CAVE_REJECT_LOG_STATE.computeIfAbsent(throttleKey, (k) -> new CaveRejectLogState()); - long now = System.currentTimeMillis(); - long last = state.lastLogMs.get(); - if ((now - last) < CAVE_REJECT_LOG_THROTTLE_MS) { - state.suppressed.incrementAndGet(); - return; - } - - if (!state.lastLogMs.compareAndSet(last, now)) { - state.suppressed.incrementAndGet(); - return; - } - - int suppressed = state.suppressed.getAndSet(0); - String anchorYText = anchorY == null ? "none" : String.valueOf(anchorY); - String errorText = error == null ? "none" : error.getClass().getSimpleName() + ":" + String.valueOf(error.getMessage()); - log.debug("Cave object reject: scope=" + scope - + " reason=" + reason - + " chunk=" + chunkX + "," + chunkZ - + " object=" + objectKey - + " placements=" + placementKeys - + " densityIndex=" + densityIndex - + " density=" + density - + " anchorMode=" + anchorMode - + " anchorSearchAttempts=" + anchorSearchAttempts - + " anchorScanStep=" + anchorScanStep - + " minDepthBelowSurface=" + objectMinDepthBelowSurface - + " anchorY=" + anchorYText - + " forcePlace=" + (objectPlacement != null && objectPlacement.isForcePlace()) - + " carvingSupport=" + (objectPlacement == null ? "none" : objectPlacement.getCarvingSupport()) - + " bottom=" + (objectPlacement != null && objectPlacement.isBottom()) - + " suppressed=" + suppressed - + " error=" + errorText); - } - - private IrisObjectPlacement resolveEffectivePlacement(IrisObjectPlacement objectPlacement, IrisObject object) { - if (objectPlacement == null || object == null) { - return objectPlacement; - } - - return applyDimensionSurfaceSupport(resolveImportedPlacement(objectPlacement, object)); - } - - /** Dimension acts as the floor: it can force support on and widen the buffer, never weaken either. */ - private IrisObjectPlacement applyDimensionSurfaceSupport(IrisObjectPlacement placement) { - IrisDimension dimension = engine.getDimension(); - boolean require = placement.isRequireSurfaceSupport() && ObjectPlacements.requiresSurfaceSupport(dimension); - int buffer = Math.max(placement.getSurfaceSupportBuffer(), ObjectPlacements.surfaceSupportBuffer(dimension)); - if (require == placement.isRequireSurfaceSupport() && buffer == placement.getSurfaceSupportBuffer()) { - return placement; - } - - IrisObjectPlacement resolved = placement.toPlacement(placement.getPlace().toArray(new String[0])); - resolved.setRequireSurfaceSupport(require); - resolved.setSurfaceSupportBuffer(buffer); - return resolved; - } - - private IrisObjectPlacement resolveImportedPlacement(IrisObjectPlacement objectPlacement, IrisObject object) { - String loadKey = object.getLoadKey(); - if (loadKey == null || loadKey.isBlank()) { - return objectPlacement; - } - - String normalized = loadKey.toLowerCase(Locale.ROOT); - boolean imported = normalized.startsWith("imports/") - || normalized.contains("/imports/") - || normalized.contains("imports/"); - - if (!imported) { - return objectPlacement; - } - - ObjectPlaceMode mode = objectPlacement.getMode(); - if (mode.placeMode().has(PlaceTrait.FREE_HEIGHT)) { - return objectPlacement; - } - boolean needsModeChange = mode != ObjectPlaceMode.FAST_MIN_STILT; - if (!needsModeChange) { - return objectPlacement; - } - - IrisObjectPlacement effectivePlacement = objectPlacement.toPlacement(loadKey); - effectivePlacement.setMode(ObjectPlaceMode.FAST_MIN_STILT); - return effectivePlacement; - } - - private IrisObjectPlacement resolveCavePlacement(IrisObjectPlacement objectPlacement, IrisObject object, CaveProfile caveProfile) { - IrisObjectPlacement resolvedPlacement = resolveEffectivePlacement(objectPlacement, object); - if (resolvedPlacement.getMode() != ObjectPlaceMode.CENTER_HEIGHT || caveProfile == null) { - return resolvedPlacement; - } - - ObjectPlaceMode profileMode = caveProfile.defaultObjectPlaceMode().orElse(null); - if (profileMode == null) { - return resolvedPlacement; - } - - String loadKey = object.getLoadKey(); - if (loadKey == null || loadKey.isBlank()) { - resolvedPlacement = resolvedPlacement.toPlacement(); - } else { - resolvedPlacement = resolvedPlacement.toPlacement(loadKey); - } - resolvedPlacement.setMode(profileMode); - return resolvedPlacement; - } - - static int caveAnchorScanUpperBound(int worldHeight, int surfaceY, int minDepthBelowSurface) { - int maxAnchorY = CaveObjectPlacementTransaction.maxBuriedY(worldHeight, surfaceY, minDepthBelowSurface); - if (maxAnchorY <= 1) { - return 0; - } - return maxAnchorY + 1; - } - - private int findCaveAnchorY(MantleWriter writer, RNG rng, int x, int z, CaveAnchorMode anchorMode, int anchorScanStep, int objectMinDepthBelowSurface, CaveAnchorCache anchorCache) { - KList anchors = anchorCache.get(writer, anchorMode, anchorScanStep, objectMinDepthBelowSurface, x, z); - if (anchors.isEmpty()) { - return -1; - } - - if (anchors.size() == 1) { - return anchors.get(0); - } - - return anchors.get(rng.i(anchors.size())); - } - - private KList scanCaveAnchorColumn(MantleWriter writer, CaveAnchorMode anchorMode, int anchorScanStep, int objectMinDepthBelowSurface, int x, int z, CaveAnchorCache anchorCache) { - int height = engine.getHeight(); - int step = Math.max(1, anchorScanStep); - int surfaceY = anchorCache.getSurfaceHeight(x, z); - int maxAnchorExclusive = caveAnchorScanUpperBound(height, surfaceY, objectMinDepthBelowSurface); - if (maxAnchorExclusive == 0) { - return new KList<>(); - } - - int carvedHeight = Math.min(height, maxAnchorExclusive + 3); - byte[] carvedColumn = anchorCache.getCarvedColumn(writer, x, z, carvedHeight); - return scanCaveAnchorRange(anchorMode, step, carvedHeight, BEDROCK_CLEARANCE, maxAnchorExclusive, carvedColumn); - } - - private KList scanCaveAnchorRange(CaveAnchorMode anchorMode, int step, int height, int minAnchorY, int maxAnchorY, byte[] carvedColumn) { - KList anchors = new KList<>(); - int startY = alignAnchorScanStart(minAnchorY, step); - for (int y = startY; y < maxAnchorY; y += step) { - if (!isCarved(carvedColumn, y)) { - continue; - } - - boolean solidBelow = hasSolidNeighbor(carvedColumn, y, height, -1); - boolean solidAbove = hasSolidNeighbor(carvedColumn, y, height, 1); - if (matchesCaveAnchor(anchorMode, solidBelow, solidAbove)) { - anchors.add(y); - } - } - return anchors; - } - - private int alignAnchorScanStart(int minAnchorY, int step) { - if (minAnchorY <= BEDROCK_CLEARANCE) { - return BEDROCK_CLEARANCE; - } - - int delta = minAnchorY - BEDROCK_CLEARANCE; - int steps = (delta + step - 1) / step; - return BEDROCK_CLEARANCE + (steps * step); - } - - private boolean isCarved(byte[] carvedColumn, int y) { - return y >= 0 && y < carvedColumn.length && carvedColumn[y] == 1; - } - - private boolean hasSolidNeighbor(byte[] carvedColumn, int y, int height, int direction) { - for (int d = 1; d <= 3; d++) { - int ny = y + (direction * d); - if (ny < 0 || ny >= height) { - return true; - } - if (!isCarved(carvedColumn, ny)) { - return true; - } - } - return false; - } - - private boolean matchesCaveAnchor(CaveAnchorMode anchorMode, boolean solidBelow, boolean solidAbove) { - return switch (anchorMode) { - case PROFILE_DEFAULT, FLOOR -> solidBelow; - case CEILING -> solidAbove; - case CENTER -> !solidBelow && !solidAbove; - case ANY -> true; - }; - } - - private CaveProfile resolveCaveProfile(CaveProfile preferred, CaveProfile secondary) { - CaveProfile dimensionProfile = CaveProfiles.declaredBy(engine.getDimension()); - if (preferred != null && preferred.enabled()) { - return preferred; - } - - if (secondary != null && secondary.enabled()) { - return secondary; - } - - if (dimensionProfile != null) { - return dimensionProfile; - } - - return DEFAULT_CAVE_PROFILE; - } - - private CaveAnchorMode resolveAnchorMode(IrisObjectPlacement objectPlacement, CaveProfile caveProfile) { - CaveAnchorMode placementMode = objectPlacement.getCaveAnchorMode(); - if (placementMode != null && !placementMode.equals(CaveAnchorMode.PROFILE_DEFAULT)) { - return placementMode; - } - - if (caveProfile == null) { - return CaveAnchorMode.FLOOR; - } - - CaveAnchorMode profileMode = caveProfile.defaultObjectAnchor(); - if (profileMode == null || profileMode.equals(CaveAnchorMode.PROFILE_DEFAULT)) { - return CaveAnchorMode.FLOOR; - } - - return profileMode; - } - - private int resolveAnchorScanStep(CaveProfile caveProfile) { - if (caveProfile == null) { - return 1; - } - - return Math.max(1, caveProfile.anchorScanStep()); - } - - private int resolveObjectMinDepthBelowSurface(CaveProfile caveProfile) { - if (caveProfile == null) { - return 6; - } - - return Math.max(0, caveProfile.objectMinDepthBelowSurface()); - } - - private int resolveAnchorSearchAttempts(CaveProfile caveProfile) { - if (caveProfile == null) { - return 6; - } - - return Math.max(1, caveProfile.anchorSearchAttempts()); - } - - private boolean isRegenTraceThread() { - return Thread.currentThread().getName().startsWith("Iris-Regen-") - && IrisSettings.get().getGeneral().isDebug(); - } - - private record ObjectPlacementSummary( - int biomeSurfacePlacersChecked, - int biomeSurfacePlacersTriggered, - int biomeCavePlacersChecked, - int biomeCavePlacersTriggered, - int regionSurfacePlacersChecked, - int regionSurfacePlacersTriggered, - int regionCavePlacersChecked, - int regionCavePlacersTriggered, - int objectAttempts, - int objectPlaced, - int objectRejected, - int objectNull, - int objectErrors - ) { - } - - private record ObjectPlacementResult(int attempts, int placed, int rejected, int nullObjects, int errors) { - } - - private record CavePlacementAnchor(int x, int y, int z) { - } - - private record ContainedPlacementResult( - int resultY, - CaveObjectPlacementTransaction.CommitResult commitResult - ) { - } - - private static final class CaveRejectLogState { - private final AtomicLong lastLogMs = new AtomicLong(0L); - private final AtomicInteger suppressed = new AtomicInteger(0); - } - - @BlockCoordinates - private Set guessPlacedKeys(RNG rng, int x, int z, IrisObjectPlacement objectPlacement) { - Set f = new KSet<>(); - for (int i = 0; i < objectPlacement.getDensity(rng, x, z, engine.getData()); i++) { - IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(engine.getComplex(), rng), engine); - if (v == null) { - continue; - } - - f.add(v.getLoadKey()); - } - - return f; - } - - public Set guess(int x, int z) { - // todo The guess doesnt bring into account that the placer may return -1 - RNG rng = applyNoise(x, z, CacheKey.key(x, z) + engine.getSeedManager().getMantle()); - IrisBiome biome = engine.getSurfaceBiome((x << 4) + 8, (z << 4) + 8); - IrisRegion region = engine.getRegion((x << 4) + 8, (z << 4) + 8); - Set v = new KSet<>(); - for (IrisObjectPlacement i : ObjectPlacements.surface(biome)) { - if (rng.chance(i.getChance() + rng.d(-0.005, 0.005))) { - v.addAll(guessPlacedKeys(rng, x, z, i)); - } - } - - for (IrisObjectPlacement i : ObjectPlacements.surface(region)) { - if (rng.chance(i.getChance() + rng.d(-0.005, 0.005))) { - v.addAll(guessPlacedKeys(rng, x, z, i)); - } - } - - return v; + return keys; } /** How far, in blocks along X and Z, placements may write beyond their chunk. */ - public int reach() { - IrisDimension dimension = engine.getDimension(); - KMap sizeCache = new KMap<>(); - KSet warnedLargeObjects = new KSet<>(); - int radius = 0; - for (IrisRegion region : dimension.getAllRegions(engine)) { - if (region == null) { - continue; - } - radius = Math.max(radius, computePlacementRadius(ObjectPlacements.all(region), sizeCache, warnedLargeObjects)); - radius = Math.max(radius, computeProceduralRadius(ObjectPlacements.procedural(region))); - } - for (IrisBiome biome : dimension.getReachableBiomes(engine)) { - if (biome == null) { - continue; - } - radius = Math.max(radius, computePlacementRadius(ObjectPlacements.all(biome), sizeCache, warnedLargeObjects)); - radius = Math.max(radius, computeProceduralRadius(ObjectPlacements.procedural(biome))); - } - - return radius; + public int reach(PackSettings settings) { + return new PlacementReach(host, log).ofPack(settings); } - - private int computePlacementRadius( - KList placements, - KMap sizeCache, - KSet warnedLargeObjects - ) { - int radius = 0; - for (IrisObjectPlacement placement : placements) { - if (placement == null) { - continue; - } - for (String objectKey : placement.getPlace()) { - try { - IrisBlockVector size = loadObjectSize(sizeCache, objectKey); - if (size == null) { - continue; - } - int reach = calculatePlacementReach(size, placement); - if (reach > 128 && warnedLargeObjects.add(objectKey)) { - log.warn("Object " + objectKey + " has a large placement reach (" + reach + " blocks) and may increase memory usage!"); - } - radius = Math.max(radius, reach); - } catch (Throwable e) { - log.error("Failed to work out the reach of an object placement", e); - } - } - } - return radius; - } - - private int computeProceduralRadius(ResolvedProceduralObjects procedural) { - if (procedural == null || procedural.isEmpty()) { - return 0; - } - int radius = 0; - for (IrisProceduralPlacement placement : procedural.getAllPlacements()) { - if (placement == null) { - continue; - } - KList variants = placement.getVariantObjects(engine.getData()); - if (variants == null) { - continue; - } - IrisObjectPlacement objectPlacement = placement.asPlacement(); - for (IrisObject variant : variants) { - if (variant == null) { - continue; - } - IrisBlockVector size = new IrisBlockVector(variant.getW(), variant.getH(), variant.getD()); - radius = Math.max(radius, calculatePlacementReach(size, objectPlacement)); - } - } - return radius; - } - - static int calculatePlacementReach(IrisBlockVector size, IrisObjectPlacement placement) { - if (size == null) { - return 0; - } - if (placement == null) { - return Math.max(Math.abs(size.getBlockX()), Math.abs(size.getBlockZ())); - } - - double scale = placement.getScale() != null ? Math.max(1D, placement.getScale().getMaxScale()) : 1D; - int width = scaledDimension(size.getBlockX(), scale); - int height = scaledDimension(size.getBlockY(), scale); - int depth = scaledDimension(size.getBlockZ(), scale); - IrisObjectRotation rotation = placement.getRotation(); - boolean rotateX = rotation != null && rotation.isEnabled() && rotation.getXAxis() != null && rotation.getXAxis().enabled(); - boolean rotateZ = rotation != null && rotation.isEnabled() && rotation.getZAxis() != null && rotation.getZAxis().enabled(); - int footprint = rotateX || rotateZ ? Math.max(width, Math.max(height, depth)) : Math.max(width, depth); - int translation = calculateTranslationReach(placement.getTranslate(), rotation, rotateX || rotateZ); - int warp = placement.getWarp() != null && !placement.getWarp().isFlat() - ? (int) Math.ceil(Math.abs(placement.getWarp().getMultiplier()) / 2D) - : 0; - int vacuum = placement.getMode().placeMode().bendsTerrain() - ? 2 * IrisObjectVacuum.resolveRadius(placement.getMode().placeMode().vacuum(), placement.getVacuumSettings()) - : 0; - long reach = (long) footprint + translation + warp + vacuum; - return reach > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) reach; - } - - private static int scaledDimension(int dimension, double scale) { - int absoluteDimension = Math.abs(dimension); - if (scale <= 1D) { - return absoluteDimension; - } - return (int) Math.ceil((absoluteDimension * scale) + (scale * 2D)); - } - - private static int calculateTranslationReach(IrisObjectTranslate translate, IrisObjectRotation rotation, boolean rotateVertically) { - if (translate == null || !translate.canTranslate()) { - return 0; - } - double x = translate.getX(); - double y = translate.getY(); - double z = translate.getZ(); - if (rotateVertically) { - return (int) Math.ceil(Math.sqrt((x * x) + (y * y) + (z * z))); - } - boolean rotateY = rotation != null && rotation.isEnabled() && rotation.getYAxis() != null && rotation.getYAxis().enabled(); - return rotateY ? (int) Math.ceil(Math.hypot(x, z)) : (int) Math.max(Math.abs(x), Math.abs(z)); - } - - private IrisBlockVector loadObjectSize(KMap sizeCache, String objectKey) { - return sizeCache.computeIfAbsent(objectKey, k -> { - try { - return IrisObject.sampleSize(engine.getData().getObjectLoader().findFile(objectKey)); - } catch (IOException e) { - log.error("Failed to size an object", e); - } - - return null; - }); - } - - private final class CaveAnchorCache { - private final Long2ObjectOpenHashMap>> settingCaches; - private final Long2ObjectOpenHashMap carvedColumns; - private final Long2IntOpenHashMap surfaceHeights; - - private CaveAnchorCache() { - this.settingCaches = new Long2ObjectOpenHashMap<>(); - this.carvedColumns = new Long2ObjectOpenHashMap<>(); - this.surfaceHeights = new Long2IntOpenHashMap(); - this.surfaceHeights.defaultReturnValue(Integer.MIN_VALUE); - } - - private KList get(MantleWriter writer, CaveAnchorMode anchorMode, int anchorScanStep, int objectMinDepthBelowSurface, int x, int z) { - if (anchorScanStep > 65535 || objectMinDepthBelowSurface > 65535) { - return scanCaveAnchorColumn(writer, anchorMode, anchorScanStep, objectMinDepthBelowSurface, x, z, this); - } - - long settingKey = ((long) anchorMode.ordinal() << 32) | ((long) anchorScanStep << 16) | objectMinDepthBelowSurface; - Long2ObjectOpenHashMap> columnCache = settingCaches.get(settingKey); - if (columnCache == null) { - columnCache = new Long2ObjectOpenHashMap<>(); - settingCaches.put(settingKey, columnCache); - } - - long columnKey = CacheKey.key(x, z); - KList anchors = columnCache.get(columnKey); - if (anchors != null) { - return anchors; - } - - anchors = scanCaveAnchorColumn(writer, anchorMode, anchorScanStep, objectMinDepthBelowSurface, x, z, this); - columnCache.put(columnKey, anchors); - return anchors; - } - - private byte[] getCarvedColumn(MantleWriter writer, int x, int z, int height) { - long columnKey = CacheKey.key(x, z); - byte[] carvedColumn = carvedColumns.get(columnKey); - if (carvedColumn != null && carvedColumn.length == height) { - return carvedColumn; - } - - carvedColumn = writer.getCarvedColumn(x, z, height); - carvedColumns.put(columnKey, carvedColumn); - return carvedColumn; - } - - private int getSurfaceHeight(int x, int z) { - long columnKey = CacheKey.key(x, z); - int surfaceY = surfaceHeights.get(columnKey); - if (surfaceY != Integer.MIN_VALUE) { - return surfaceY; - } - - surfaceY = engine.getHeight(x, z); - surfaceHeights.put(columnKey, surfaceY); - return surfaceY; - } - } - } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java index 5f8855641..6b9241941 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java @@ -18,17 +18,19 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.placement.ObjectPlacements; -import art.arcane.iris.engine.object.procedural.ResolvedProceduralObjects; -import art.arcane.iris.engine.object.procedural.IrisProceduralPlacement; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.volmlib.util.collection.KList; +import art.arcane.iris.builtin.objects.ObjectHost; +import art.arcane.iris.builtin.objects.ObjectHost.Declaration; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectSettings; +import art.arcane.iris.builtin.objects.ProceduralObjectSettings; +import art.arcane.iris.builtin.objects.ProceduralPlacement; +import art.arcane.iris.builtin.IrisSeed; import art.arcane.volmlib.util.math.RNG; +import com.volmit.FeatureAttachment.Target; +import com.volmit.world.PackWorld; import java.util.Comparator; +import java.util.List; /** * Builds what object placing would build on first use, for every object placement and procedural object the world's @@ -38,55 +40,48 @@ import java.util.Comparator; */ final class ObjectWarmUp { private static final long ROOT_SEED_SALT = 7777L; - private static final int PROBE_COORDINATE = 0; - private final Engine engine; + private final ObjectHost host; private final RNG root; private int warmed; - ObjectWarmUp(Engine engine) { - this.engine = engine; - this.root = new RNG(engine.getSeedManager().getComponent() + ROOT_SEED_SALT); + ObjectWarmUp(PackWorld world) { + this.host = ObjectHost.of(world); + this.root = new RNG(IrisSeed.COMPONENT.of(world) + ROOT_SEED_SALT); } void warm() { - KList biomes = engine.getAllBiomes(); - biomes.sort(Comparator.comparing(IrisBiome::getLoadKey)); - for (IrisBiome biome : biomes) { - warmPlacements(ObjectPlacements.all(biome)); - warmProcedural(ObjectPlacements.procedural(biome)); - } - - KList regions = engine.getDimension().getAllRegions(engine); - regions.sort(Comparator.comparing(IrisRegion::getLoadKey)); - for (IrisRegion region : regions) { - warmPlacements(ObjectPlacements.all(region)); - warmProcedural(ObjectPlacements.procedural(region)); - } - } - - private void warmPlacements(KList placements) { - if (placements == null) { - return; - } - for (IrisObjectPlacement placement : placements) { - if (placement == null) { - continue; + List> placements = byKey(host.declarations(ObjectSettings.class)); + List> procedural = byKey(host.declarations(ProceduralObjectSettings.class)); + for (Target level : new Target[]{Target.BIOME, Target.REGION}) { + for (Declaration declaration : placements) { + if (declaration.level() == level) { + warmPlacements(declaration.settings().objects()); + } + } + for (Declaration declaration : procedural) { + if (declaration.level() == level) { + warmProcedural(declaration.settings()); + } } - RNG rng = root.nextParallelRNG(warmed++); - placement.getSurfaceWarp(rng, engine.getData(), engine); - placement.getDensity(rng, PROBE_COORDINATE, PROBE_COORDINATE, engine.getData()); } } - private void warmProcedural(ResolvedProceduralObjects procedural) { - if (procedural == null) { - return; - } - for (IrisProceduralPlacement placement : procedural.getAllPlacements()) { + private static List> byKey(List> declarations) { + return declarations.stream().sorted(Comparator.comparing(Declaration::key)).toList(); + } + + private void warmPlacements(List placements) { + for (ObjectPlacement placement : placements) { if (placement != null) { - placement.getVariantObject(engine.getData(), root.nextParallelRNG(warmed++)); + host.warm(placement, root.nextParallelRNG(warmed++)); } } } + + private void warmProcedural(ProceduralObjectSettings settings) { + for (ProceduralPlacement placement : host.procedural(settings)) { + placement.variant(root.nextParallelRNG(warmed++)); + } + } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/PlacementReach.java b/src/main/java/art/arcane/iris/engine/mantle/components/PlacementReach.java new file mode 100644 index 000000000..c98c94fd3 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/PlacementReach.java @@ -0,0 +1,170 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.builtin.anchor.PlaceMode; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectSize; +import art.arcane.iris.builtin.objects.ObjectSettings; +import art.arcane.iris.builtin.objects.ProceduralObjectSettings; +import art.arcane.iris.builtin.objects.ObjectHost; +import art.arcane.iris.builtin.objects.PlaceableObject; +import art.arcane.iris.builtin.objects.ProceduralPlacement; +import art.arcane.iris.builtin.prepare.AxisRotationClamp; +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.iris.builtin.prepare.ObjectTranslate; +import art.arcane.iris.builtin.vacuum.VacuumSettings; +import com.volmit.ModuleLog; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.PackSettings; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +/** How far, in blocks along X and Z, the objects a pack places may write beyond their chunk. */ +final class PlacementReach { + private static final int LARGE_REACH_WARNING_BLOCKS = 128; + private static final int MAX_VACUUM_RADIUS_BLOCKS = 128; + private static final double SCALE_PADDING_FACTOR = 2D; + + private final ObjectHost host; + private final ModuleLog log; + private final Map> sizes = new HashMap<>(); + private final Set warnedLargeObjects = new HashSet<>(); + + PlacementReach(ObjectHost host, ModuleLog log) { + this.host = host; + this.log = log; + } + + /** The largest reach of any object placement or procedural object the pack's regions and biomes declare. */ + int ofPack(PackSettings settings) { + int radius = 0; + for (Entry entry : settings.declared(ObjectSettings.class)) { + radius = Math.max(radius, ofPlacements(entry.value().objects())); + } + for (Entry entry : settings.declared(ProceduralObjectSettings.class)) { + radius = Math.max(radius, ofProcedural(entry.value())); + } + return radius; + } + + private int ofPlacements(List placements) { + int radius = 0; + for (ObjectPlacement placement : placements) { + if (placement == null) { + continue; + } + for (String objectKey : placement.place()) { + radius = Math.max(radius, ofObject(placement, objectKey)); + } + } + return radius; + } + + private int ofObject(ObjectPlacement placement, String objectKey) { + try { + Optional size = sizes.computeIfAbsent(objectKey, host::sizeOf); + if (size.isEmpty()) { + return 0; + } + int reach = of(size.get(), placement); + if (reach > LARGE_REACH_WARNING_BLOCKS && warnedLargeObjects.add(objectKey)) { + log.warn("Object " + objectKey + " has a large placement reach (" + reach + " blocks) and may increase memory usage!"); + } + return reach; + } catch (Throwable failure) { + log.error("Failed to work out the reach of an object placement", failure); + return 0; + } + } + + private int ofProcedural(ProceduralObjectSettings settings) { + int radius = 0; + for (ProceduralPlacement placement : host.procedural(settings)) { + for (PlaceableObject variant : placement.variants()) { + radius = Math.max(radius, of(new ObjectSize(variant.width(), variant.height(), variant.depth()), placement)); + } + } + return radius; + } + + /** The reach of an object of {@code size} placed with the options a procedural object has. */ + static int of(ObjectSize size, ProceduralPlacement placement) { + return of(size, placement.mode().placeMode(), null, placement.rotation(), placement.translate(), null, + placement.vacuumSettings().orElse(null)); + } + + static int of(ObjectSize size, ObjectPlacement placement) { + return of(size, placement.mode().placeMode(), placement.scale().maxScale(), placement.rotation(), placement.translate(), + placement.warp() == null || placement.warp().isFlat() ? 0 : placement.warp().multiplier(), + placement.vacuumSettings().orElse(null)); + } + + private static int of(ObjectSize size, PlaceMode mode, Double maxScale, ObjectRotation rotation, ObjectTranslate translate, + Double warpMultiplier, VacuumSettings vacuum) { + double scale = maxScale == null ? 1D : Math.max(1D, maxScale); + int width = scaledDimension(size.width(), scale); + int height = scaledDimension(size.height(), scale); + int depth = scaledDimension(size.depth(), scale); + boolean rotateX = rotation != null && rotation.enabled() && rotation.xAxis() != null && rotation.xAxis().enabled(); + boolean rotateZ = rotation != null && rotation.enabled() && rotation.zAxis() != null && rotation.zAxis().enabled(); + int footprint = rotateX || rotateZ ? Math.max(width, Math.max(height, depth)) : Math.max(width, depth); + int translation = translationReach(translate, rotation, rotateX || rotateZ); + int warp = warpMultiplier == null ? 0 : (int) Math.ceil(Math.abs(warpMultiplier) / 2D); + int vacuumReach = mode.bendsTerrain() ? 2 * vacuumRadius(mode, vacuum) : 0; + long reach = (long) footprint + translation + warp + vacuumReach; + return reach > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) reach; + } + + private static int scaledDimension(int dimension, double scale) { + int absoluteDimension = Math.abs(dimension); + if (scale <= 1D) { + return absoluteDimension; + } + return (int) Math.ceil((absoluteDimension * scale) + (scale * SCALE_PADDING_FACTOR)); + } + + private static int translationReach(ObjectTranslate translate, ObjectRotation rotation, boolean rotateVertically) { + if (translate == null || (translate.x() == 0 && translate.y() == 0 && translate.z() == 0)) { + return 0; + } + double x = translate.x(); + double y = translate.y(); + double z = translate.z(); + if (rotateVertically) { + return (int) Math.ceil(Math.sqrt((x * x) + (y * y) + (z * z))); + } + AxisRotationClamp yAxis = rotation == null ? null : rotation.yAxis(); + boolean rotateY = rotation != null && rotation.enabled() && yAxis != null && yAxis.enabled(); + return rotateY ? (int) Math.ceil(Math.hypot(x, z)) : (int) Math.max(Math.abs(x), Math.abs(z)); + } + + private static int vacuumRadius(PlaceMode mode, VacuumSettings settings) { + int radius = mode.vacuum().defaultRadiusBlocks(); + if (settings != null && settings.radius() > 0) { + radius = settings.radius(); + } + return Math.max(0, Math.min(MAX_VACUUM_RADIUS_BLOCKS, radius)); + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java index e97c60212..68bb0e90a 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java @@ -73,7 +73,7 @@ public final class StructureModule implements IrisModule, ModuleLifecycle { @Override public void install(StageGraph graph) { - graph.define(IrisStages.Structure.PLACE).requires(IrisStages.Objects.PLACE).softAfter(IrisStages.Floating.OBJECTS.ref()) + graph.define(IrisStages.Structure.PLACE).softAfter(IrisStages.Objects.PLACE.ref(), IrisStages.Floating.OBJECTS.ref()) .reach(this::reach).run(StructureModule::place); } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java index bd8a3c3d1..51f73827a 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java @@ -18,27 +18,22 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.modules.IrisPackWorld; -import art.arcane.iris.core.modules.PlatformBlockStates; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.placement.IObjectPlacer; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.placement.ObjectPlacements; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.TileData; -import art.arcane.iris.engine.object.procedural.ResolvedProceduralObjects; -import art.arcane.iris.builtin.objects.tree.Tree; -import art.arcane.iris.engine.object.procedural.tree.ResolvedTree; +import art.arcane.iris.builtin.objects.ObjectHost; +import art.arcane.iris.builtin.objects.ObjectHost.Declaration; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectSettings; +import art.arcane.iris.builtin.objects.ObjectSink; +import art.arcane.iris.builtin.objects.PlaceableObject; +import art.arcane.iris.builtin.objects.ProceduralObjectSettings; +import art.arcane.iris.builtin.objects.TreeGrowthSettings; import art.arcane.iris.builtin.objects.TreeMode; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.spi.IrisPlatforms; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.volmlib.util.collection.KList; +import art.arcane.iris.builtin.objects.tree.Tree; import art.arcane.volmlib.util.math.RNG; +import com.volmit.FeatureAttachment.Target; +import com.volmit.config.FeatureSettings.Entry; import com.volmit.block.BlockState; import com.volmit.placement.PlacedBlock; +import com.volmit.resource.ResourceId; import com.volmit.service.SaplingGrowth; import com.volmit.world.BlockPosition; import com.volmit.world.PackWorld; @@ -60,80 +55,83 @@ public final class TreeGrowing implements SaplingGrowth { @Override public Optional grow(PackWorld world, Sapling sapling, Surroundings surroundings) { - Engine engine = IrisPackWorld.of(world).engine(); - if (!ObjectPlacements.treeGrowth(engine.getDimension()).enabled()) { + ObjectHost host = ObjectHost.of(world); + BlockPosition at = sapling.at(); + TreeGrowthSettings growth = treeGrowth(host, at); + if (!growth.enabled()) { return Optional.empty(); } - - IrisObjectPlacement placement = pickPlacement(engine, sapling); - if (placement == null) { + Optional placement = pickPlacement(host, growth, sapling); + if (placement.isEmpty()) { return Optional.empty(); } - - IrisData data = engine.getData(); - IrisObject object = data.getObjectLoader().load(placement.getPlace().getRandom(RNG.r)); - GrowthPlacer placer = new GrowthPlacer(engine, surroundings); + List keys = placement.get().place(); + Optional tree = host.object(keys.get(RNG.r.i(keys.size()))); + if (tree.isEmpty()) { + return Optional.empty(); + } + PlaceableObject object = tree.get(); + GrowthSink sink = new GrowthSink(surroundings, host); BlockPosition center = sapling.center(); - object.place(center.x(), center.y() + object.getH() / 2, center.z(), placer, placement, RNG.r, data); - return Optional.of(new Growth(object.getLoadKey(), placer.placed())); + host.placeInto(object, center.x(), center.y() + object.height() / 2, center.z(), placement.get(), sink, RNG.r); + return Optional.of(new Growth(object.key(), sink.placed())); } @Override public TreeObjects treeObjects(PackWorld world) { - Engine engine = IrisPackWorld.of(world).engine(); + ObjectHost host = ObjectHost.of(world); Set objects = new HashSet<>(); Set procedural = new HashSet<>(); - - for (IrisRegion region : engine.getDimension().getAllRegions(engine)) { - if (region != null) { - collectPlacements(ObjectPlacements.all(region), objects); - collectProceduralTrees(ObjectPlacements.procedural(region), procedural); - } + for (Declaration declaration : host.declarations(ObjectSettings.class)) { + collectPlacements(declaration.settings().objects(), objects); } - for (IrisBiome biome : engine.getDimension().getReachableBiomes(engine)) { - if (biome != null) { - collectPlacements(ObjectPlacements.all(biome), objects); - collectProceduralTrees(ObjectPlacements.procedural(biome), procedural); - } + for (Declaration declaration : host.declarations(ProceduralObjectSettings.class)) { + collectProceduralTrees(declaration.settings().trees(), procedural); } return new TreeObjects(objects, procedural); } - /** One placement, picked at random, of the tree placements that grow {@code sapling}'s species; null for none. */ - private static IrisObjectPlacement pickPlacement(Engine engine, Sapling sapling) { - KList placements = new KList<>(); - boolean useAll = ObjectPlacements.treeGrowth(engine.getDimension()).mode() == TreeMode.ALL; - - BlockPosition at = sapling.at(); - placements.addAll(matching(ObjectPlacements.all(engine.getBiome(at.x(), at.y(), at.z())), sapling.species())); - if (useAll || placements.isEmpty()) { - placements.addAll(matching(ObjectPlacements.all(engine.getRegion(at.x(), at.z())), sapling.species())); + private static TreeGrowthSettings treeGrowth(ObjectHost host, BlockPosition at) { + for (Entry entry : host.columnSettings().at(TreeGrowthSettings.class, at.x(), at.z())) { + if (entry.level() == Target.DIMENSION) { + return entry.value(); + } } - return placements.isNotEmpty() ? placements.getRandom() : null; + return new TreeGrowthSettings(); } - private static KList matching(KList objects, String species) { - KList matches = new KList<>(); - for (IrisObjectPlacement placement : objects) { - if (placement.matches(SAPLING_WIDTH, SAPLING_DEPTH, species)) { + /** One placement, picked at random, of the tree placements that grow {@code sapling}'s species. */ + private static Optional pickPlacement(ObjectHost host, TreeGrowthSettings growth, Sapling sapling) { + List placements = new ArrayList<>(); + BlockPosition at = sapling.at(); + ResourceId biome = host.biomeAt(at.x(), at.y(), at.z()); + host.biomeDeclaration(biome, ObjectSettings.class).ifPresent(settings -> placements.addAll(matching(settings, sapling.species()))); + if (growth.mode() == TreeMode.ALL || placements.isEmpty()) { + ResourceId region = host.regionAt(at.x(), at.z()); + host.regionDeclaration(region, ObjectSettings.class).ifPresent(settings -> placements.addAll(matching(settings, sapling.species()))); + } + if (placements.isEmpty()) { + return Optional.empty(); + } + return Optional.of(placements.get(RNG.r.i(placements.size()))); + } + + private static List matching(ObjectSettings settings, String species) { + List matches = new ArrayList<>(); + for (ObjectPlacement placement : settings.objects()) { + if (placement.trees().stream().anyMatch(tree -> tree.matches(SAPLING_WIDTH, SAPLING_DEPTH, species))) { matches.add(placement); } } return matches; } - private static void collectPlacements(Iterable placements, Set objectKeys) { - if (placements == null) { - return; - } - for (IrisObjectPlacement placement : placements) { - if (placement == null - || placement.getTrees() == null - || placement.getTrees().isEmpty() - || placement.getPlace() == null) { + private static void collectPlacements(List placements, Set objectKeys) { + for (ObjectPlacement placement : placements) { + if (placement == null || placement.trees().isEmpty()) { continue; } - for (String objectKey : placement.getPlace()) { + for (String objectKey : placement.place()) { if (objectKey != null && !objectKey.isBlank()) { objectKeys.add(objectKey); } @@ -141,32 +139,27 @@ public final class TreeGrowing implements SaplingGrowth { } } - private static void collectProceduralTrees(ResolvedProceduralObjects proceduralObjects, Set objectKeys) { - if (proceduralObjects == null || proceduralObjects.getTrees() == null) { - return; - } - for (ResolvedTree resolved : proceduralObjects.getTrees()) { - Tree tree = resolved.settings(); - if (tree.name() == null || tree.name().isBlank()) { + private static void collectProceduralTrees(List trees, Set objectKeys) { + for (Tree tree : trees) { + if (tree == null || tree.name() == null || tree.name().isBlank()) { continue; } int variants = Math.max(1, tree.variants()); for (int index = 0; index < variants; index++) { - objectKeys.add(resolved.getVariantLoadKey(index)); + objectKeys.add(Tree.variantLoadKey(tree.name(), index)); } } } /** Places an object into a list of blocks, reading the world around the sapling through the host. */ - private static final class GrowthPlacer implements IObjectPlacer { - private final Engine engine; + private static final class GrowthSink implements ObjectSink { private final Surroundings surroundings; - private final PlatformBlockStates states = new PlatformBlockStates(key -> IrisPlatforms.get().registries().block(key)); + private final ObjectHost host; private final List placed = new ArrayList<>(); - private GrowthPlacer(Engine engine, Surroundings surroundings) { - this.engine = engine; + private GrowthSink(Surroundings surroundings, ObjectHost host) { this.surroundings = surroundings; + this.host = host; } private List placed() { @@ -174,77 +167,23 @@ public final class TreeGrowing implements SaplingGrowth { } @Override - public int getHighest(int x, int z, IrisData data) { - return surroundings.highest(x, z, false); - } - - @Override - public int getHighest(int x, int z, IrisData data, boolean ignoreFluid) { + public int highest(int x, int z, boolean ignoreFluid) { return surroundings.highest(x, z, ignoreFluid); } @Override - public void set(int x, int y, int z, PlatformBlockState state) { - placed.add(new PlacedBlock(new BlockPosition(x, y, z), states.toApi(state), Optional.empty())); + public BlockState get(int x, int y, int z) { + return surroundings.blockAt(x, y, z); } @Override - public PlatformBlockState get(int x, int y, int z) { - BlockState block = surroundings.blockAt(x, y, z); - return states.toPlatform(block); + public void set(int x, int y, int z, BlockState state) { + placed.add(new PlacedBlock(new BlockPosition(x, y, z), state, Optional.empty())); } @Override - public boolean isPreventingDecay() { - return true; - } - - @Override - public boolean isCarved(int x, int y, int z) { - return false; - } - - @Override - public boolean isSurfaceSolid(int x, int y, int z) { - return isSolid(x, y, z); - } - - @Override - public boolean isSolid(int x, int y, int z) { - return get(x, y, z).isSolid(); - } - - @Override - public boolean isUnderwater(int x, int z) { - return false; - } - - @Override - public int getFluidHeight() { - return engine.getDimension().getFluidHeight(); - } - - @Override - public boolean isDebugSmartBore() { - return false; - } - - @Override - public void setTile(int xx, int yy, int zz, TileData tile) { - } - - @Override - public void setData(int xx, int yy, int zz, T data) { - } - - @Override - public T getData(int xx, int yy, int zz, Class t) { - return null; - } - - @Override - public Engine getEngine() { - return engine; + public int fluidHeight() { + return host.fluidHeight(); } } } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ObjectPlacements.java b/src/main/java/art/arcane/iris/engine/object/placement/ObjectPlacements.java index 4296c7c08..f69425cb5 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/ObjectPlacements.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/ObjectPlacements.java @@ -65,7 +65,12 @@ public final class ObjectPlacements { /** The procedural objects {@code owner} declares; none when it declares none. */ public static ResolvedProceduralObjects procedural(IrisRegistrant owner) { Optional settings = owner.getModuleSettings().find(ProceduralObjectSettings.class); - return PROCEDURAL.computeIfAbsent(settings.orElse(NO_PROCEDURAL_OBJECTS), ResolvedProceduralObjects::new); + return procedural(settings.orElse(NO_PROCEDURAL_OBJECTS)); + } + + /** The procedural objects {@code settings} declare. */ + public static ResolvedProceduralObjects procedural(ProceduralObjectSettings settings) { + return PROCEDURAL.computeIfAbsent(settings, ResolvedProceduralObjects::new); } /** Whether {@code dimension} places its objects in the terrain stacked above it too. */ diff --git a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObject.java b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObject.java index 5e8e05cb5..3afc0912a 100644 --- a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObject.java +++ b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObject.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.prefab; +import art.arcane.iris.builtin.objects.PlaceableObject; import art.arcane.iris.engine.object.placement.FloatingObjectFootprint; import art.arcane.iris.engine.object.placement.IObjectPlacer; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; @@ -71,7 +72,7 @@ import java.util.function.BiConsumer; */ @Accessors(chain = true) @EqualsAndHashCode(callSuper = false) -public class IrisObject extends IrisRegistrant { +public class IrisObject extends IrisRegistrant implements PlaceableObject { protected static final IrisVector HALF = new IrisVector(0.5, 0.5, 0.5); public static final class States { public static final PlatformBlockState AIR = B.getState("CAVE_AIR"); @@ -372,6 +373,26 @@ public class IrisObject extends IrisRegistrant { } } + @Override + public String key() { + return getLoadKey(); + } + + @Override + public int width() { + return w; + } + + @Override + public int height() { + return h; + } + + @Override + public int depth() { + return d; + } + public int volume() { return blocks.size(); } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralPlacement.java b/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralPlacement.java index 40b007f94..fbad263b9 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralPlacement.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralPlacement.java @@ -63,6 +63,11 @@ public abstract class ResolvedProceduralPlacement implements IrisProceduralPlace return Math.max(1, shape.variants()); } + /** The options this object shares with an object placement. */ + public Shape shape() { + return shape; + } + @Override public String getName() { return shape.name(); diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java index 5bf0f7742..36b493834 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java @@ -44,16 +44,8 @@ public final class ResolvedTree extends ResolvedProceduralPlacement { this.settings = settings; } - /** The key a variant is loaded under, which placement markers and the sapling tree list name. */ - public static String variantLoadKey(String name, int index) { - if (index < 0) { - throw new IllegalArgumentException("index must not be negative"); - } - return "procedural/tree/" + name + "#" + index; - } - public String getVariantLoadKey(int index) { - return variantLoadKey(settings.name(), index); + return Tree.variantLoadKey(settings.name(), index); } public Tree settings() {