diff --git a/src/main/java/com/volmit/FeatureRegistry.java b/src/main/java/com/volmit/FeatureRegistry.java index 4a2817e15..050828d3f 100644 --- a/src/main/java/com/volmit/FeatureRegistry.java +++ b/src/main/java/com/volmit/FeatureRegistry.java @@ -8,7 +8,6 @@ import com.volmit.resource.ResourceKind; import com.volmit.service.Service; import com.volmit.stage.StageGraph; import com.volmit.validation.Validator; -import com.volmit.vanilla.VanillaStructureHook; /** Host implementation collects non-stage registrations before loading pack configuration. * Feature IDs must be unique. JSON fields must be unique per attachment target, including the @@ -60,9 +59,4 @@ public interface FeatureRegistry { * are {@link com.volmit.service.Providers#ONE} fails the pack load when a second module provides it, naming both. */ void registerService(Class service, S provider); - - /** Lets this module decide over the platform's own structures in the pack's worlds: block them, leave them to the - * platform, or place them itself. - */ - void registerVanillaStructureHook(VanillaStructureHook hook); } diff --git a/src/main/java/com/volmit/host/FeatureCatalog.java b/src/main/java/com/volmit/host/FeatureCatalog.java index 551f95e28..ac0c753f9 100644 --- a/src/main/java/com/volmit/host/FeatureCatalog.java +++ b/src/main/java/com/volmit/host/FeatureCatalog.java @@ -12,7 +12,7 @@ import java.util.Optional; import java.util.function.Function; /** Frozen registrations. Lists use lexical feature/layer/kind ID order, and validators, lifecycle hooks, service - * providers and vanilla structure hooks are in module id order, each module's in the order it registered them, so + * providers are in module id order, each module's in the order it registered them, so * nothing depends on discovery. Factory, codec, validator, hook and provider implementations must themselves obey their * concurrency contracts. */ @@ -25,7 +25,6 @@ public final class FeatureCatalog { private final List validators; private final List lifecycles; private final List services; - private final List vanillaStructureHooks; FeatureCatalog( Map, FeatureDescriptor> settings, @@ -35,8 +34,7 @@ public final class FeatureCatalog { Collection heldTypes, List validators, List lifecycles, - List services, - List vanillaStructureHooks) { + List services) { this.settings = Map.copyOf(settings); this.objects = Map.copyOf(objects); this.mantle = Map.copyOf(mantle); @@ -45,7 +43,6 @@ public final class FeatureCatalog { this.validators = inModuleOrder(validators, ValidatorRegistration::module); this.lifecycles = inModuleOrder(lifecycles, LifecycleRegistration::module); this.services = inModuleOrder(services, ServiceRegistration::module); - this.vanillaStructureHooks = inModuleOrder(vanillaStructureHooks, VanillaStructureHookRegistration::module); } /** Settings types that activate stages; the host decodes them from pack JSON. */ @@ -76,11 +73,6 @@ public final class FeatureCatalog { return validators; } - /** The vanilla structure hooks modules registered, by module id, each module's in the order it registered them. */ - public List vanillaStructureHooks() { - return vanillaStructureHooks; - } - /** The lifecycle hooks modules registered, by module id, each module's in the order it registered them. */ public List lifecycles() { return lifecycles; diff --git a/src/main/java/com/volmit/host/ModuleRegistry.java b/src/main/java/com/volmit/host/ModuleRegistry.java index b6c302cda..a84b5cb18 100644 --- a/src/main/java/com/volmit/host/ModuleRegistry.java +++ b/src/main/java/com/volmit/host/ModuleRegistry.java @@ -13,7 +13,6 @@ import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceKind; import com.volmit.service.Providers; import com.volmit.validation.Validator; -import com.volmit.vanilla.VanillaStructureHook; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -48,7 +47,6 @@ public final class ModuleRegistry implements FeatureRegistry { private final List validators = new ArrayList<>(); private final List lifecycles = new ArrayList<>(); private final List services = new ArrayList<>(); - private final List vanillaStructureHooks = new ArrayList<>(); private final Set reservedFolders; private final List registered = new ArrayList<>(); private FeatureCatalog catalog; @@ -175,14 +173,6 @@ public final class ModuleRegistry implements FeatureRegistry { services.add(added); } - @Override - public void registerVanillaStructureHook(VanillaStructureHook hook) { - checkOpen(); - Objects.requireNonNull(hook, "hook"); - requireRegistering("Vanilla structure hook " + hook); - vanillaStructureHooks.add(new VanillaStructureHookRegistration(hook, registering)); - } - /** Catalogs a settings type named by a stage's when(...), whose owner {@link StageGraphBuilder} * has checked. Several stages, and the owner's {@link #registerSettings}, may name one type. Call * it after every module has registered, so the owner is known. @@ -204,7 +194,7 @@ public final class ModuleRegistry implements FeatureRegistry { public FeatureCatalog freeze() { if (catalog == null) { catalog = new FeatureCatalog(settings, objects, mantle, resourceKinds.values(), heldTypes.values(), - validators, lifecycles, services, vanillaStructureHooks); + validators, lifecycles, services); } return catalog; } diff --git a/src/main/java/com/volmit/host/VanillaStructureHookRegistration.java b/src/main/java/com/volmit/host/VanillaStructureHookRegistration.java deleted file mode 100644 index 446fba6af..000000000 --- a/src/main/java/com/volmit/host/VanillaStructureHookRegistration.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.volmit.host; - -import com.volmit.vanilla.VanillaStructureHook; -import java.util.Objects; - -/** A vanilla structure hook and the module that registered it, which the host names when the hook fails. */ -public record VanillaStructureHookRegistration(VanillaStructureHook hook, DiscoveredModule module) { - public VanillaStructureHookRegistration { - Objects.requireNonNull(hook, "hook"); - Objects.requireNonNull(module, "module"); - } -} diff --git a/src/main/java/com/volmit/service/VanillaStructures.java b/src/main/java/com/volmit/service/VanillaStructures.java new file mode 100644 index 000000000..896720138 --- /dev/null +++ b/src/main/java/com/volmit/service/VanillaStructures.java @@ -0,0 +1,94 @@ +package com.volmit.service; + +import com.volmit.resource.ResourceId; +import com.volmit.vanilla.PlatformStart; +import com.volmit.vanilla.StartMemo; +import com.volmit.vanilla.StartReach; +import com.volmit.vanilla.StructureFit; +import com.volmit.vanilla.VanillaStructureContext; +import com.volmit.vanilla.VanillaStructureRule; +import com.volmit.vanilla.VanillaStructureSetup; +import com.volmit.vanilla.VanillaStructureStart; +import com.volmit.vanilla.VanillaStructureStartContext; +import java.util.List; +import java.util.Optional; + +/** A module's say over the platform's own structures, the ones Minecraft, data packs and mods register, in the pack's + * worlds. The host asks every provider, in module id order: + * + *
    + *
  • {@link #rule} before the platform starts one of its structures, and when it locates one;
  • + *
  • {@link #starts} for every chunk, for the starts modules place where the platform would not;
  • + *
  • {@link #shift} before it publishes a start the platform made itself, and {@link #reach} before it publishes any + * start;
  • + *
  • {@link #beforePieces} and {@link #afterPieces} around the platform placing the starts' pieces in a chunk;
  • + *
  • {@link #setup} before a world of the dimension exists, when the platform sets up its structures and when the + * host installs data packs.
  • + *
+ * + *

The host asks {@link #rule} once per world, structure and pack snapshot and keeps the answer, so a rule is decided + * from the pack (its settings and resources) and never from where a start would be. Rules combine with + * {@link VanillaStructureRule#and}: any module may block the platform's starts. Shifts add up; reaches are all covered; + * setups combine with {@link VanillaStructureSetup#and}. Every method may be called from any thread, concurrently, but + * one chunk's {@link StructureFit} is used on one thread. + */ +@Service(Providers.ALL) +public interface VanillaStructures { + /** What this module wants for the platform structure {@code structure}, such as {@code minecraft:village_plains}, + * in the world {@code context} describes. {@link VanillaStructureRule#GENERATE} when the module has no part in it. + */ + default VanillaStructureRule rule(ResourceId structure, VanillaStructureContext context) { + return VanillaStructureRule.GENERATE; + } + + /** The platform structures this module starts in chunk {@code chunkX, chunkZ}: starts the platform generates from + * that chunk, wherever its own placement rules would put them. At most one start per structure and chunk counts; + * the host keeps the first, in module id order. Decided from the world and the chunk only, so the same chunk always + * gets the same starts: the host asks again when it locates structures and when it checks a start it finds in + * the world. + */ + default List starts(int chunkX, int chunkZ, VanillaStructureStartContext context) { + return List.of(); + } + + /** How many blocks the platform's own start {@code start} moves up (negative: down) before the host publishes it. + * Decided from the start's place and the terrain only, so asking again for the same start gives the same answer: + * the host asks again when it predicts where the platform's starts end up. The host keeps the start inside the + * world, moving it less when it would leave it. 0 when the module has no part in it. + */ + default int shift(PlatformStart start, VanillaStructureContext context) { + return 0; + } + + /** How far around its pieces this module changes the terrain for a start of {@code structure}: a start the module + * placed itself, with the {@code memo} it gave it, or one of the platform's own starts (no memo; {@code underground} + * says whether the platform generates the structure in one of its underground steps). The platform hands the start to + * every chunk the reach covers, so {@link #beforePieces} sees it there. {@link StartReach#PLATFORM} when the module + * changes no more than the platform's own terrain adaptation would. + */ + default StartReach reach(ResourceId structure, boolean underground, Optional memo, + VanillaStructureContext context) { + return StartReach.PLATFORM; + } + + /** Called once per chunk before the platform places any piece of {@code fit}'s starts there: the module fits the + * terrain to the starts it cares about, writing only inside {@link StructureFit#area()}. + */ + default void beforePieces(StructureFit fit) { + } + + /** Called after the platform placed the pieces of {@code placed}, one of {@code fit}'s starts, in the chunk, before + * it places the next start's; the last call of a chunk is for the last of {@link StructureFit#starts()}. + */ + default void afterPieces(StructureFit fit, StructureFit.Start placed) { + } + + /** What this module changes about how the platform sets up its structures for the dimension {@code context} + * describes. Protecting the platform's definitions in one dimension protects them in every data pack the host + * installs, since those are shared by every world. {@link VanillaStructureSetup#UNCHANGED} when the module has no + * part in it. + */ + default VanillaStructureSetup setup(VanillaStructureContext context) { + return VanillaStructureSetup.UNCHANGED; + } +} diff --git a/src/main/java/com/volmit/vanilla/PieceKind.java b/src/main/java/com/volmit/vanilla/PieceKind.java new file mode 100644 index 000000000..cdda3e62a --- /dev/null +++ b/src/main/java/com/volmit/vanilla/PieceKind.java @@ -0,0 +1,11 @@ +package com.volmit.vanilla; + +/** How a structure piece was made and how it sits on the terrain. */ +public enum PieceKind { + /** A piece the platform builds in code, not from a jigsaw pool, such as a stronghold room. */ + FIXED, + /** A jigsaw piece that keeps its own shape, whatever the terrain under it. */ + RIGID, + /** A jigsaw piece whose blocks follow the terrain's surface, such as a village road. */ + TERRAIN_MATCHING +} diff --git a/src/main/java/com/volmit/vanilla/PlatformStart.java b/src/main/java/com/volmit/vanilla/PlatformStart.java new file mode 100644 index 000000000..57eed5226 --- /dev/null +++ b/src/main/java/com/volmit/vanilla/PlatformStart.java @@ -0,0 +1,33 @@ +package com.volmit.vanilla; + +import com.volmit.mantle.BlockBox; +import com.volmit.resource.ResourceId; + +/** One of the platform's own starts, as the platform made it, before the host publishes it. Valid only while the + * provider runs. + */ +public interface PlatformStart { + ResourceId structure(); + + int chunkX(); + + int chunkZ(); + + /** The box around all of the start's pieces; Y is the height above the dimension's bottom. */ + BlockBox bounds(); + + /** Whether the platform generates the structure in one of its underground steps (strongholds, mineshafts, trial + * chambers, ancient cities). + */ + boolean underground(); + + /** Whether the host aligns this structure itself: an ocean monument to the sea level, a desert or jungle temple to + * the terrain. A shift then applies on top of that alignment instead of to the platform's height. + */ + boolean aligned(); + + /** The height of the terrain's surface at a column, above the dimension's bottom: the highest block of the terrain + * the host generated there, fluids ignored. + */ + int surfaceY(int x, int z); +} diff --git a/src/main/java/com/volmit/vanilla/StartMemo.java b/src/main/java/com/volmit/vanilla/StartMemo.java new file mode 100644 index 000000000..e57637ed6 --- /dev/null +++ b/src/main/java/com/volmit/vanilla/StartMemo.java @@ -0,0 +1,16 @@ +package com.volmit.vanilla; + +import java.util.Objects; + +/** What a module noted about a start it placed, for itself: two texts in the module's own format, one about how the + * start meets the terrain and one about its foundation. The host keeps the memo with the start for as long as the world + * does and hands it back whenever it asks the module about the start again ({@link StructureFit.Start#memo()}, + * {@link com.volmit.service.VanillaStructures#reach}), so a start that spans many chunks is finished the way it was + * begun, even after the pack changed. The host never reads the texts. + */ +public record StartMemo(String terrain, String foundation) { + public StartMemo { + Objects.requireNonNull(terrain, "terrain"); + Objects.requireNonNull(foundation, "foundation"); + } +} diff --git a/src/main/java/com/volmit/vanilla/StartReach.java b/src/main/java/com/volmit/vanilla/StartReach.java new file mode 100644 index 000000000..3d4fb4d0d --- /dev/null +++ b/src/main/java/com/volmit/vanilla/StartReach.java @@ -0,0 +1,24 @@ +package com.volmit.vanilla; + +/** How far around its pieces a module changes the terrain for a start, so the platform hands the start to every chunk + * the change reaches: {@link #PLATFORM} for the area the platform's own terrain adaptation of the structure covers, or + * a number of blocks around the pieces. The host covers the reaches of every provider together. + */ +public record StartReach(boolean platform, int blocks) { + /** The area the platform's own terrain adaptation of the structure covers (its pieces when it adapts none). */ + public static final StartReach PLATFORM = new StartReach(true, 0); + + public StartReach { + if (blocks < 0) { + throw new IllegalArgumentException("A start's reach cannot be negative: " + blocks); + } + if (platform && blocks != 0) { + throw new IllegalArgumentException("The platform's reach has no block count"); + } + } + + /** {@code blocks} around the start's pieces, horizontally; 0 for the pieces alone. */ + public static StartReach blocks(int blocks) { + return new StartReach(false, blocks); + } +} diff --git a/src/main/java/com/volmit/vanilla/StructureFit.java b/src/main/java/com/volmit/vanilla/StructureFit.java new file mode 100644 index 000000000..16954ab1d --- /dev/null +++ b/src/main/java/com/volmit/vanilla/StructureFit.java @@ -0,0 +1,119 @@ +package com.volmit.vanilla; + +import com.volmit.block.BlockState; +import com.volmit.mantle.BlockBox; +import com.volmit.resource.ResourceId; +import com.volmit.world.BlockAccess; +import com.volmit.world.BlockPosition; +import com.volmit.world.PackWorld; +import java.util.List; +import java.util.Optional; +import java.util.function.Supplier; + +/** The starts the platform places in one chunk while it decorates it, and the chunk's blocks, for modules that fit + * those starts into the terrain ({@link com.volmit.service.VanillaStructures#beforePieces}, + * {@link com.volmit.service.VanillaStructures#afterPieces}). Heights are above the dimension's bottom (0 = bottom) unless + * a method says otherwise. One fit is handed to every provider for the chunk; it is valid only while they run, on one + * thread. + */ +public interface StructureFit { + PackWorld world(); + + /** The seed of the platform's world, which the platform's own structure randomness derives from. */ + long seed(); + + /** The blocks the platform decorates now: the chunk's columns, from one above its bottom to one below its top. + * {@link #blocks()} may read the whole chunk column but a fit only writes here. + */ + BlockBox area(); + + /** The world height of the dimension's bottom, for rules written in world heights: a band of world heights, the + * platform's deepslate below 0, noise sampled at world heights. + */ + int bottomY(); + + /** The chunk column's live blocks. */ + BlockAccess blocks(); + + /** The height of the terrain's surface the host generated at a column: its highest terrain block, fluids ignored. */ + int surfaceY(int x, int z); + + /** The block the platform's natural terrain of this dimension is made of at height {@code y}: stone or deepslate in + * an overworld, netherrack in a nether, end stone in an end. + */ + BlockState naturalBlock(int y); + + /** Every start the platform places in the chunk now, in the order it places them. */ + List starts(); + + /** The fit's one {@code type} instance, created by {@code create} the first time a provider asks for it: what a + * provider works out before the pieces are placed and needs again after them. Use a class of the module as + * {@code type}. Gone once the chunk is done. + */ + T state(Class type, Supplier create); + + /** A start the platform places in the chunk. */ + interface Start { + ResourceId structure(); + + /** The chunk the start belongs to, where the platform started it. */ + int chunkX(); + + int chunkZ(); + + StructureStep step(); + + /** The terrain adaptation the platform's definition of the structure asks for. */ + TerrainAdaptation adaptation(); + + /** The memo the module that placed the start gave it ({@link VanillaStructureStart#withMemo}); empty for the + * platform's own starts. + */ + Optional memo(); + + /** Every piece of the start, in the platform's order: also the pieces outside the chunk. */ + List pieces(); + + /** An object that stays the same for this start for as long as the platform keeps it, across chunks: a key for + * caches about the start, held weakly so the start can be forgotten. + */ + Object key(); + } + + /** A piece of a start. */ + interface Piece { + /** The piece's bounds, minima inclusive and maxima exclusive like every {@link BlockBox}. */ + BlockBox box(); + + PieceKind kind(); + + /** How far above the piece's lowest block its ground level lies; 0 for a {@link PieceKind#FIXED} piece. */ + int groundLevelDelta(); + + /** Where the jigsaw connections of this piece meet the pieces they lead to: the X and Z of the connection and the + * ground height at its source. Empty for a {@link PieceKind#FIXED} piece. + */ + List junctions(); + + /** The piece's template blocks inside {@code region}, processed as the platform would place them now, against + * the blocks the chunk holds at this moment. Asked again, the host reads the template again. + */ + TemplateCells cells(BlockBox region); + + /** The piece's shape as vertical spans, one per column it occupies: from the lowest to the highest block of its + * templates that is neither air nor structure void, or its whole box when the host cannot read a template. + */ + void columns(ColumnVisitor visitor); + + /** The air blocks of the piece's legacy templates inside {@code clip}, the ones the platform's own legacy + * placement would leave as air over existing terrain. Empty when the piece has no legacy template. + */ + List legacyAir(BlockBox clip); + } + + /** Receives one vertical span of a piece per column, both heights inclusive. */ + @FunctionalInterface + interface ColumnVisitor { + void column(int x, int z, int minY, int maxY); + } +} diff --git a/src/main/java/com/volmit/vanilla/StructureStep.java b/src/main/java/com/volmit/vanilla/StructureStep.java new file mode 100644 index 000000000..ce10204af --- /dev/null +++ b/src/main/java/com/volmit/vanilla/StructureStep.java @@ -0,0 +1,21 @@ +package com.volmit.vanilla; + +/** The decoration step in which the platform places a structure's pieces, in the platform's order. */ +public enum StructureStep { + RAW_GENERATION, + LAKES, + LOCAL_MODIFICATIONS, + UNDERGROUND_STRUCTURES, + SURFACE_STRUCTURES, + STRONGHOLDS, + UNDERGROUND_ORES, + UNDERGROUND_DECORATION, + FLUID_SPRINGS, + VEGETAL_DECORATION, + TOP_LAYER_MODIFICATION; + + /** Whether this is one of the steps the platform places its underground structures in. */ + public boolean isUnderground() { + return this == UNDERGROUND_STRUCTURES || this == UNDERGROUND_DECORATION || this == STRONGHOLDS; + } +} diff --git a/src/main/java/com/volmit/vanilla/StructureStilts.java b/src/main/java/com/volmit/vanilla/StructureStilts.java deleted file mode 100644 index e3f8e7de5..000000000 --- a/src/main/java/com/volmit/vanilla/StructureStilts.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.volmit.vanilla; - -import com.volmit.block.BlockSpec; -import com.volmit.block.PaletteSpec; -import com.volmit.config.Desc; -import com.volmit.config.MaxNumber; -import com.volmit.config.MinNumber; -import java.util.List; -import java.util.Objects; - -/** Foundation columns the host builds beneath a structure's pieces after placing them, as packs write it: - * {@code {"maxDepth": 32, "palette": {"palette": [{"block": "stone_bricks"}]}, "spacing": 2}}. A value the host - * creates with the no-argument constructor and reads the JSON into. - */ -@Desc("Defines foundation columns placed beneath a structure.") -public final class StructureStilts { - private static final int DEFAULT_MAX_DEPTH = 64; - private static final String DEFAULT_BLOCK = "minecraft:cobblestone"; - - @MinNumber(1) - @MaxNumber(4064) - @Desc("Maximum number of blocks each foundation column may descend while searching for solid ground.") - private int maxDepth = DEFAULT_MAX_DEPTH; - - @Desc("Block palette used for foundation columns.") - private PaletteSpec palette = PaletteSpec.of(List.of(BlockSpec.of(DEFAULT_BLOCK))); - - @MinNumber(1) - @MaxNumber(64) - @Desc("Horizontal spacing between support columns. One fills every eligible foundation column.") - private int spacing = 1; - - @Desc("Whether solid partial blocks such as slabs, stairs, and walls may seed foundation columns.") - private boolean supportNonOccluding = false; - - private StructureStilts() { - } - - private StructureStilts(int maxDepth, PaletteSpec palette, int spacing, boolean supportNonOccluding) { - this.maxDepth = maxDepth; - this.palette = Objects.requireNonNull(palette, "palette"); - this.spacing = spacing; - this.supportNonOccluding = supportNonOccluding; - } - - /** Columns of {@code palette} under every eligible block, at most 64 deep. */ - public static StructureStilts of(PaletteSpec palette) { - return new StructureStilts(DEFAULT_MAX_DEPTH, palette, 1, false); - } - - public StructureStilts withMaxDepth(int maxDepth) { - return new StructureStilts(maxDepth, palette(), spacing, supportNonOccluding); - } - - public StructureStilts withSpacing(int spacing) { - return new StructureStilts(maxDepth, palette(), spacing, supportNonOccluding); - } - - /** These stilts, also seeded from partial blocks such as slabs, stairs and walls. */ - public StructureStilts supportingNonOccluding() { - return new StructureStilts(maxDepth, palette(), spacing, true); - } - - public int maxDepth() { - return maxDepth; - } - - /** The blocks of the columns; cobblestone where the pack wrote none. */ - public PaletteSpec palette() { - return palette == null ? PaletteSpec.of(List.of(BlockSpec.of(DEFAULT_BLOCK))) : palette; - } - - public int spacing() { - return spacing; - } - - public boolean supportNonOccluding() { - return supportNonOccluding; - } - - @Override - public boolean equals(Object other) { - return other instanceof StructureStilts that && maxDepth == that.maxDepth && palette().equals(that.palette()) - && spacing == that.spacing && supportNonOccluding == that.supportNonOccluding; - } - - @Override - public int hashCode() { - return Objects.hash(maxDepth, palette(), spacing, supportNonOccluding); - } - - @Override - public String toString() { - return "StructureStilts[" + palette() + ", depth " + maxDepth + ", spacing " + spacing + "]"; - } -} diff --git a/src/main/java/com/volmit/vanilla/StructureTerrain.java b/src/main/java/com/volmit/vanilla/StructureTerrain.java deleted file mode 100644 index 76bfd84fd..000000000 --- a/src/main/java/com/volmit/vanilla/StructureTerrain.java +++ /dev/null @@ -1,222 +0,0 @@ -package com.volmit.vanilla; - -import com.volmit.block.PaletteSpec; -import com.volmit.config.Desc; -import com.volmit.config.MaxNumber; -import com.volmit.config.MinNumber; -import java.util.Objects; -import java.util.Optional; - -/** How the host fits the terrain around a structure before its pieces are placed, as packs write it: - * {@code {"mode": "FORCE_CARVE", "horizontalPadding": 4, "shape": "ERODED"}}. The host carries the work out; a module - * only describes it. A value the host creates with the no-argument constructor and reads the JSON into. - */ -@Desc("Terrain integration applied after a structure graph is assembled and before its pieces are placed.") -public final class StructureTerrain { - private static final double DEFAULT_EROSION_STRENGTH = 0.8D; - private static final double DEFAULT_EROSION_FREQUENCY = 0.07D; - private static final double DEFAULT_LOBE_STRENGTH = 0.85D; - - /** What the host does to the terrain around the structure. */ - @Desc("Controls how terrain is integrated with a structure.") - public enum Mode { - @Desc("Replays the registered structure's own authored terrain adaptation.") - SOURCE, - @Desc("Disables all terrain integration.") - PRESERVE, - @Desc("Clears one straight box around the assembled pieces, expanded by the paddings.") - BORE, - @Desc("Clears the padded envelope in the configured carve shape.") - FORCE_CARVE, - @Desc("Raises surface terrain under rigid foundations with a 12-block falloff without lowering existing ground.") - VACUUM, - @Desc("Fills the padded piece volume with solid blocks before any piece is placed.") - ENCASE - } - - /** The shape {@link Mode#FORCE_CARVE} clears. */ - @Desc("Controls the shape of the expanded terrain carve around a structure.") - public enum Shape { - @Desc("The full expanded box with straight walls, ceiling and floor.") - BOX, - @Desc("A smooth rounded volume without erosion noise.") - ROUNDED, - @Desc("A rounded volume whose outer boundary is eroded by noise.") - ERODED - } - - @Desc("Terrain operation.") - private Mode mode = Mode.SOURCE; - - @MinNumber(0) - @MaxNumber(128) - @Desc("Horizontal clearance around the assembled pieces for BORE, FORCE_CARVE, and ENCASE.") - private int horizontalPadding = 0; - - @MinNumber(0) - @MaxNumber(128) - @Desc("Air clearance above the assembled pieces.") - private int ceilingPadding = 0; - - @MinNumber(0) - @MaxNumber(64) - @Desc("Terrain cleared below the assembled pieces. Zero preserves their supporting floor.") - private int floorPadding = 0; - - @Desc("Shape used by FORCE_CARVE.") - private Shape shape = Shape.BOX; - - @Desc("Block palette used by ENCASE. When unset, the host picks the dimension's own stone.") - private PaletteSpec encasePalette = null; - - @MinNumber(0) - @MaxNumber(1) - @Desc("Boundary erosion strength for ERODED force carving.") - private double erosionStrength = DEFAULT_EROSION_STRENGTH; - - @MinNumber(0.001) - @MaxNumber(1) - @Desc("Boundary noise frequency for ERODED force carving.") - private double erosionFrequency = DEFAULT_EROSION_FREQUENCY; - - @MinNumber(0) - @MaxNumber(1) - @Desc("Low frequency lobe wavelength for ERODED force carving. Zero derives it from the erosion frequency.") - private double lobeFrequency = 0D; - - @MinNumber(0) - @MaxNumber(1) - @Desc("Fraction of the horizontal padding the lobes may remove for ERODED force carving.") - private double lobeStrength = DEFAULT_LOBE_STRENGTH; - - private StructureTerrain() { - } - - private StructureTerrain(StructureTerrain source) { - mode = source.mode(); - horizontalPadding = source.horizontalPadding; - ceilingPadding = source.ceilingPadding; - floorPadding = source.floorPadding; - shape = source.shape(); - encasePalette = source.encasePalette; - erosionStrength = source.erosionStrength; - erosionFrequency = source.erosionFrequency; - lobeFrequency = source.lobeFrequency; - lobeStrength = source.lobeStrength; - } - - /** Terrain fitting in {@code mode} with every other option at its default. */ - public static StructureTerrain of(Mode mode) { - StructureTerrain terrain = new StructureTerrain(); - terrain.mode = Objects.requireNonNull(mode, "mode"); - return terrain; - } - - /** This fitting with clearance around the pieces: sideways, above and below, in blocks. */ - public StructureTerrain withPadding(int horizontal, int ceiling, int floor) { - StructureTerrain terrain = new StructureTerrain(this); - terrain.horizontalPadding = horizontal; - terrain.ceilingPadding = ceiling; - terrain.floorPadding = floor; - return terrain; - } - - public StructureTerrain withShape(Shape shape) { - StructureTerrain terrain = new StructureTerrain(this); - terrain.shape = Objects.requireNonNull(shape, "shape"); - return terrain; - } - - public StructureTerrain withEncasePalette(PaletteSpec palette) { - StructureTerrain terrain = new StructureTerrain(this); - terrain.encasePalette = Objects.requireNonNull(palette, "palette"); - return terrain; - } - - /** This fitting with the erosion of an {@link Shape#ERODED} boundary: its strength and noise frequency. */ - public StructureTerrain withErosion(double strength, double frequency) { - StructureTerrain terrain = new StructureTerrain(this); - terrain.erosionStrength = strength; - terrain.erosionFrequency = frequency; - return terrain; - } - - /** This fitting with the low frequency lobes of an {@link Shape#ERODED} boundary. */ - public StructureTerrain withLobes(double frequency, double strength) { - StructureTerrain terrain = new StructureTerrain(this); - terrain.lobeFrequency = frequency; - terrain.lobeStrength = strength; - return terrain; - } - - /** The terrain operation; {@link Mode#SOURCE} where the pack wrote none or one the host does not know. */ - public Mode mode() { - return mode == null ? Mode.SOURCE : mode; - } - - public int horizontalPadding() { - return horizontalPadding; - } - - public int ceilingPadding() { - return ceilingPadding; - } - - public int floorPadding() { - return floorPadding; - } - - /** The carve shape; {@link Shape#BOX} where the pack wrote none or one the host does not know. */ - public Shape shape() { - return shape == null ? Shape.BOX : shape; - } - - /** The blocks {@link Mode#ENCASE} fills with; empty for the dimension's own stone. */ - public Optional encasePalette() { - return Optional.ofNullable(encasePalette); - } - - /** As the pack wrote it; the host clamps it to 0..1. */ - public double erosionStrength() { - return erosionStrength; - } - - /** As the pack wrote it; the host clamps it to 0.001..1. */ - public double erosionFrequency() { - return erosionFrequency; - } - - /** As the pack wrote it; zero or less lets the host derive it from the erosion frequency. */ - public double lobeFrequency() { - return lobeFrequency; - } - - /** As the pack wrote it; the host clamps it to 0..1. */ - public double lobeStrength() { - return lobeStrength; - } - - @Override - public boolean equals(Object other) { - return other instanceof StructureTerrain that && mode() == that.mode() - && horizontalPadding == that.horizontalPadding && ceilingPadding == that.ceilingPadding - && floorPadding == that.floorPadding && shape() == that.shape() - && Objects.equals(encasePalette, that.encasePalette) - && Double.compare(erosionStrength, that.erosionStrength) == 0 - && Double.compare(erosionFrequency, that.erosionFrequency) == 0 - && Double.compare(lobeFrequency, that.lobeFrequency) == 0 - && Double.compare(lobeStrength, that.lobeStrength) == 0; - } - - @Override - public int hashCode() { - return Objects.hash(mode(), horizontalPadding, ceilingPadding, floorPadding, shape(), encasePalette, - erosionStrength, erosionFrequency, lobeFrequency, lobeStrength); - } - - @Override - public String toString() { - return "StructureTerrain[" + mode() + ", padding " + horizontalPadding + "/" + ceilingPadding + "/" + floorPadding - + ", " + shape() + "]"; - } -} diff --git a/src/main/java/com/volmit/vanilla/TemplateCells.java b/src/main/java/com/volmit/vanilla/TemplateCells.java new file mode 100644 index 000000000..bac0c9dd9 --- /dev/null +++ b/src/main/java/com/volmit/vanilla/TemplateCells.java @@ -0,0 +1,82 @@ +package com.volmit.vanilla; + +import com.volmit.block.BlockState; +import java.util.Objects; + +/** The blocks a structure piece's template places, at their world positions (Y above the dimension's bottom), after the + * platform ran the template's processors and turned it with the piece. A cell whose template block the processors + * removed has no state: nothing is placed there, but the template still claims it. Cells come in no particular order, + * each position once. + * + *

{@link #resolved()} is false for a piece whose blocks the host cannot read from a template (a piece the platform + * builds in code, or a jigsaw element that places a feature); it then has no cells. {@link #readBlocks()} says how many + * template blocks the host read and processed for the answer, so a caller can bound the work it allows. + */ +public final class TemplateCells { + /** The answer for a piece without a template. */ + public static final TemplateCells UNRESOLVED = new TemplateCells(false, new int[0], new int[0], new int[0], new BlockState[0], 0); + + private final boolean resolved; + private final int[] xs; + private final int[] ys; + private final int[] zs; + private final BlockState[] states; + private final int readBlocks; + + private TemplateCells(boolean resolved, int[] xs, int[] ys, int[] zs, BlockState[] states, int readBlocks) { + this.resolved = resolved; + this.xs = xs; + this.ys = ys; + this.zs = zs; + this.states = states; + this.readBlocks = readBlocks; + } + + /** Cells at {@code (xs[i], ys[i], zs[i])} holding {@code states[i]}, null for a removed block. The arrays are kept, + * not copied. + */ + public static TemplateCells of(int[] xs, int[] ys, int[] zs, BlockState[] states, int readBlocks) { + int size = Objects.requireNonNull(states, "states").length; + if (xs.length != size || ys.length != size || zs.length != size) { + throw new IllegalArgumentException("Template cell coordinates and states differ in length"); + } + if (readBlocks < 0) { + throw new IllegalArgumentException("Read block count cannot be negative: " + readBlocks); + } + return new TemplateCells(true, xs, ys, zs, states, readBlocks); + } + + public boolean resolved() { + return resolved; + } + + public int readBlocks() { + return readBlocks; + } + + public int size() { + return states.length; + } + + public int x(int cell) { + return xs[cell]; + } + + public int y(int cell) { + return ys[cell]; + } + + public int z(int cell) { + return zs[cell]; + } + + /** Whether the processors removed the template's block of this cell. */ + public boolean removed(int cell) { + return states[cell] == null; + } + + /** The cell's processed block; null when {@link #removed}. */ + public BlockState state(int cell) { + return states[cell]; + } +} diff --git a/src/main/java/com/volmit/vanilla/TerrainAdaptation.java b/src/main/java/com/volmit/vanilla/TerrainAdaptation.java new file mode 100644 index 000000000..e52db3d20 --- /dev/null +++ b/src/main/java/com/volmit/vanilla/TerrainAdaptation.java @@ -0,0 +1,17 @@ +package com.volmit.vanilla; + +/** How the platform's own definition of a structure adapts the terrain around it when the platform generates the + * terrain itself. The host generates the terrain, so a module that wants the adaptation does it in its fit. + */ +public enum TerrainAdaptation { + /** No adaptation. */ + NONE, + /** Terrain buries the structure's rigid pieces from their ground level, closer horizontally than vertically. */ + BURY, + /** A thin skirt of terrain grows to meet the structure's base. */ + BEARD_THIN, + /** A box-shaped skirt of terrain grows to meet the structure's base. */ + BEARD_BOX, + /** Terrain wraps the structure's rigid pieces on every side. */ + ENCAPSULATE +} diff --git a/src/main/java/com/volmit/vanilla/VanillaStructureAdjustment.java b/src/main/java/com/volmit/vanilla/VanillaStructureAdjustment.java deleted file mode 100644 index 215b88ba1..000000000 --- a/src/main/java/com/volmit/vanilla/VanillaStructureAdjustment.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.volmit.vanilla; - -import java.util.Objects; -import java.util.Optional; - -/** What a module changes about the platform's own starts of one structure, the ones the platform places where it - * would on its own: how far they move up or down, a band of world heights to move them into, whether they keep the - * height the platform chose, and how they {@link VanillaStructureFit fit} the terrain. - * - *

Precedence, as the host applies it: keeping the platform's height wins over a band, a band wins over the - * host's own repositioning of buried structures, and the shift applies on top of whichever height results. - * Structures with a fixed platform alignment (an ocean monument's sea level) keep it. - */ -public final class VanillaStructureAdjustment { - /** The platform's starts as the platform makes them. */ - public static final VanillaStructureAdjustment NONE = new VanillaStructureAdjustment(0, null, false, VanillaStructureFit.SOURCE); - - private final int yShift; - private final YBand yBand; - private final boolean keepsSourceY; - private final VanillaStructureFit fit; - - private VanillaStructureAdjustment(int yShift, YBand yBand, boolean keepsSourceY, VanillaStructureFit fit) { - this.yShift = yShift; - this.yBand = yBand; - this.keepsSourceY = keepsSourceY; - this.fit = fit; - } - - /** This adjustment, moving the starts {@code blocks} further up (negative: down). */ - public VanillaStructureAdjustment shifted(int blocks) { - return new VanillaStructureAdjustment(Math.addExact(yShift, blocks), yBand, keepsSourceY, fit); - } - - public VanillaStructureAdjustment withYBand(YBand band) { - return new VanillaStructureAdjustment(yShift, Objects.requireNonNull(band, "band"), keepsSourceY, fit); - } - - /** This adjustment, keeping the height the platform chose instead of the host's repositioning of buried structures. */ - public VanillaStructureAdjustment keepingSourceY() { - return new VanillaStructureAdjustment(yShift, yBand, true, fit); - } - - public VanillaStructureAdjustment withFit(VanillaStructureFit fit) { - return new VanillaStructureAdjustment(yShift, yBand, keepsSourceY, Objects.requireNonNull(fit, "fit")); - } - - /** Blocks the starts move up; negative moves them down. */ - public int yShift() { - return yShift; - } - - public Optional yBand() { - return Optional.ofNullable(yBand); - } - - public boolean keepsSourceY() { - return keepsSourceY; - } - - public VanillaStructureFit fit() { - return fit; - } - - /** Both adjustments applied, {@code later} after this one: shifts add up, keeping the platform's height sticks, and - * a band or a fit part {@code later} states replaces this one's. The host combines the adjustments of several - * modules this way, in module id order. - */ - public VanillaStructureAdjustment then(VanillaStructureAdjustment later) { - return new VanillaStructureAdjustment(Math.addExact(yShift, later.yShift), later.yBand().orElse(yBand), - keepsSourceY || later.keepsSourceY, fit.then(later.fit)); - } - - @Override - public boolean equals(Object other) { - return other instanceof VanillaStructureAdjustment that && yShift == that.yShift - && Objects.equals(yBand, that.yBand) && keepsSourceY == that.keepsSourceY && fit.equals(that.fit); - } - - @Override - public int hashCode() { - return Objects.hash(yShift, yBand, keepsSourceY, fit); - } - - @Override - public String toString() { - return "VanillaStructureAdjustment[shift " + yShift + ", " + yBand().map(Object::toString).orElse("no band") - + (keepsSourceY ? ", source Y" : "") + ", " + fit + "]"; - } -} diff --git a/src/main/java/com/volmit/vanilla/VanillaStructureContext.java b/src/main/java/com/volmit/vanilla/VanillaStructureContext.java index 5a5ec797a..ecde18518 100644 --- a/src/main/java/com/volmit/vanilla/VanillaStructureContext.java +++ b/src/main/java/com/volmit/vanilla/VanillaStructureContext.java @@ -3,7 +3,7 @@ package com.volmit.vanilla; import com.volmit.config.PackSettings; import com.volmit.resource.PackResources; -/** The world a {@link VanillaStructureHook} decides for. Valid only while the hook runs. */ +/** The world a {@link com.volmit.service.VanillaStructures} provider decides for. Valid only while the provider runs. */ public interface VanillaStructureContext { /** The resources of the world's pack, module resource kinds included. */ PackResources resources(); diff --git a/src/main/java/com/volmit/vanilla/VanillaStructureFit.java b/src/main/java/com/volmit/vanilla/VanillaStructureFit.java deleted file mode 100644 index e711e7cdd..000000000 --- a/src/main/java/com/volmit/vanilla/VanillaStructureFit.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.volmit.vanilla; - -import java.util.Objects; -import java.util.Optional; - -/** How a platform structure sits in the terrain: the fitting the host does around it before its pieces are placed, - * and the foundation columns it builds under them afterwards. Without a terrain fitting the host replays the - * structure's own ({@link StructureTerrain.Mode#SOURCE}); without stilts it builds none. - */ -public final class VanillaStructureFit { - /** The structure's own terrain adaptation and no stilts. */ - public static final VanillaStructureFit SOURCE = new VanillaStructureFit(null, null); - - private final StructureTerrain terrain; - private final StructureStilts stilts; - - private VanillaStructureFit(StructureTerrain terrain, StructureStilts stilts) { - this.terrain = terrain; - this.stilts = stilts; - } - - public VanillaStructureFit withTerrain(StructureTerrain terrain) { - return new VanillaStructureFit(Objects.requireNonNull(terrain, "terrain"), stilts); - } - - public VanillaStructureFit withStilts(StructureStilts stilts) { - return new VanillaStructureFit(terrain, Objects.requireNonNull(stilts, "stilts")); - } - - public Optional terrain() { - return Optional.ofNullable(terrain); - } - - public Optional stilts() { - return Optional.ofNullable(stilts); - } - - /** This fit with each part {@code later} states replaced by {@code later}'s. */ - public VanillaStructureFit then(VanillaStructureFit later) { - return new VanillaStructureFit(later.terrain().orElse(terrain), later.stilts().orElse(stilts)); - } - - @Override - public boolean equals(Object other) { - return other instanceof VanillaStructureFit that && Objects.equals(terrain, that.terrain) - && Objects.equals(stilts, that.stilts); - } - - @Override - public int hashCode() { - return Objects.hash(terrain, stilts); - } - - @Override - public String toString() { - return "VanillaStructureFit[" + terrain().map(Object::toString).orElse("source terrain") + ", " - + stilts().map(Object::toString).orElse("no stilts") + "]"; - } -} diff --git a/src/main/java/com/volmit/vanilla/VanillaStructureHook.java b/src/main/java/com/volmit/vanilla/VanillaStructureHook.java deleted file mode 100644 index 952f03a4a..000000000 --- a/src/main/java/com/volmit/vanilla/VanillaStructureHook.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.volmit.vanilla; - -import com.volmit.resource.ResourceId; -import java.util.List; - -/** A module's say over the platform's own structures. Modules register it with - * {@link com.volmit.FeatureRegistry#registerVanillaStructureHook}; the host asks every hook of the pack, in module id - * order: - * - *

    - *
  • {@link #rule} before the platform starts one of its structures, and when it locates one;
  • - *
  • {@link #adjustment} before it places a start the platform made itself;
  • - *
  • {@link #starts} for every chunk, for the starts modules place where the platform would not;
  • - *
  • {@link #setup} before a world of the dimension exists, when the platform sets up its structures and when the - * host installs data packs.
  • - *
- * - *

The host asks {@link #rule} and {@link #adjustment} once per world, structure and pack snapshot and keeps the - * answer, so they decide from the pack (its settings and resources) and never from where a start would be. Rules of - * several modules combine with {@link VanillaStructureRule#and}: any module may block the platform's starts. - * Adjustments combine with {@link VanillaStructureAdjustment#then}, setups with {@link VanillaStructureSetup#and}. - * Every method may be called from any thread, concurrently. - */ -@FunctionalInterface -public interface VanillaStructureHook { - /** What this module wants for the platform structure {@code structure}, such as {@code minecraft:village_plains}, - * in the world {@code context} describes. {@link VanillaStructureRule#GENERATE} when the module has no part in it. - */ - VanillaStructureRule rule(ResourceId structure, VanillaStructureContext context); - - /** What this module changes about the platform's own starts of {@code structure}; {@code underground} says whether - * the platform generates it in one of its underground steps (strongholds, mineshafts, trial chambers, ancient - * cities). {@link VanillaStructureAdjustment#NONE} when the module has no part in it. - */ - default VanillaStructureAdjustment adjustment(ResourceId structure, boolean underground, VanillaStructureContext context) { - return VanillaStructureAdjustment.NONE; - } - - /** The platform structures this module starts in chunk {@code chunkX, chunkZ}: starts the platform generates from - * that chunk, wherever its own placement rules would put them. At most one start per structure and chunk counts; - * the host keeps the first, in module id order. Decided from the world and the chunk only, so the same chunk always - * gets the same starts: the host asks again when it locates structures and when it checks a start it finds in - * the world. - */ - default List starts(int chunkX, int chunkZ, VanillaStructureStartContext context) { - return List.of(); - } - - /** What this module changes about how the platform sets up its structures for the dimension {@code context} - * describes. Protecting the platform's definitions in one dimension protects them in every data pack the host - * installs, since those are shared by every world. {@link VanillaStructureSetup#UNCHANGED} when the module has no - * part in it. - */ - default VanillaStructureSetup setup(VanillaStructureContext context) { - return VanillaStructureSetup.UNCHANGED; - } -} diff --git a/src/main/java/com/volmit/vanilla/VanillaStructureStart.java b/src/main/java/com/volmit/vanilla/VanillaStructureStart.java index eea65fcb7..7ff666429 100644 --- a/src/main/java/com/volmit/vanilla/VanillaStructureStart.java +++ b/src/main/java/com/volmit/vanilla/VanillaStructureStart.java @@ -14,7 +14,9 @@ import java.util.Optional; * {@link VanillaStructureRule#REPLACE replaced} by a module. * *

{@link #identity()} names what placed the start, stable for one pack: the host records it with every start it - * publishes, so a start found in the world later can be traced back to its placement. + * publishes, so a start found in the world later can be traced back to its placement. The {@link #memo() memo} is kept + * with that record and handed back whenever the host asks the module about the start again, so a start that spans many + * chunks keeps what the module decided for it when it was placed, even after the pack changed. */ public final class VanillaStructureStart { private final ResourceId structure; @@ -25,11 +27,11 @@ public final class VanillaStructureStart { private final boolean replacesPlatformStart; private final long identity; private final JigsawOverrides jigsaw; - private final VanillaStructureFit fit; + private final StartMemo memo; private VanillaStructureStart(ResourceId structure, int chunkX, int chunkZ, int y, boolean underground, boolean replacesPlatformStart, long identity, JigsawOverrides jigsaw, - VanillaStructureFit fit) { + StartMemo memo) { this.structure = Objects.requireNonNull(structure, "structure"); this.chunkX = chunkX; this.chunkZ = chunkZ; @@ -38,28 +40,28 @@ public final class VanillaStructureStart { this.replacesPlatformStart = replacesPlatformStart; this.identity = identity; this.jigsaw = jigsaw; - this.fit = Objects.requireNonNull(fit, "fit"); + this.memo = memo; } - /** A surface start of {@code structure} in chunk {@code chunkX, chunkZ}, planned at height {@code y}, with the - * structure's own terrain fitting, its registered definition and identity 0. + /** A surface start of {@code structure} in chunk {@code chunkX, chunkZ}, planned at height {@code y}, with its + * registered definition, identity 0 and no memo. */ public static VanillaStructureStart at(ResourceId structure, int chunkX, int chunkZ, int y) { - return new VanillaStructureStart(structure, chunkX, chunkZ, y, false, false, 0L, null, VanillaStructureFit.SOURCE); + return new VanillaStructureStart(structure, chunkX, chunkZ, y, false, false, 0L, null, null); } /** This start with the structure's lowest block at {@link #y()} instead of on the surface. */ public VanillaStructureStart underground() { - return new VanillaStructureStart(structure, chunkX, chunkZ, y, true, replacesPlatformStart, identity, jigsaw, fit); + return new VanillaStructureStart(structure, chunkX, chunkZ, y, true, replacesPlatformStart, identity, jigsaw, memo); } /** This start, taking the chunk even where the platform already started the structure there. */ public VanillaStructureStart replacingPlatformStart() { - return new VanillaStructureStart(structure, chunkX, chunkZ, y, underground, true, identity, jigsaw, fit); + return new VanillaStructureStart(structure, chunkX, chunkZ, y, underground, true, identity, jigsaw, memo); } public VanillaStructureStart withIdentity(long identity) { - return new VanillaStructureStart(structure, chunkX, chunkZ, y, underground, replacesPlatformStart, identity, jigsaw, fit); + return new VanillaStructureStart(structure, chunkX, chunkZ, y, underground, replacesPlatformStart, identity, jigsaw, memo); } /** This start, assembled with {@code overrides} applied to a jigsaw structure's definition. Only jigsaw structures @@ -67,11 +69,13 @@ public final class VanillaStructureStart { */ public VanillaStructureStart withJigsaw(JigsawOverrides overrides) { return new VanillaStructureStart(structure, chunkX, chunkZ, y, underground, replacesPlatformStart, identity, - Objects.requireNonNull(overrides, "overrides"), fit); + Objects.requireNonNull(overrides, "overrides"), memo); } - public VanillaStructureStart withFit(VanillaStructureFit fit) { - return new VanillaStructureStart(structure, chunkX, chunkZ, y, underground, replacesPlatformStart, identity, jigsaw, fit); + /** This start with {@code memo}, which the host keeps with it and hands back in every later question about it. */ + public VanillaStructureStart withMemo(StartMemo memo) { + return new VanillaStructureStart(structure, chunkX, chunkZ, y, underground, replacesPlatformStart, identity, jigsaw, + Objects.requireNonNull(memo, "memo")); } public ResourceId structure() { @@ -108,8 +112,9 @@ public final class VanillaStructureStart { return Optional.ofNullable(jigsaw); } - public VanillaStructureFit fit() { - return fit; + /** What the module noted about the start for itself; empty when it noted nothing. */ + public Optional memo() { + return Optional.ofNullable(memo); } @Override @@ -117,12 +122,12 @@ public final class VanillaStructureStart { return other instanceof VanillaStructureStart that && structure.equals(that.structure) && chunkX == that.chunkX && chunkZ == that.chunkZ && y == that.y && underground == that.underground && replacesPlatformStart == that.replacesPlatformStart && identity == that.identity - && Objects.equals(jigsaw, that.jigsaw) && fit.equals(that.fit); + && Objects.equals(jigsaw, that.jigsaw) && Objects.equals(memo, that.memo); } @Override public int hashCode() { - return Objects.hash(structure, chunkX, chunkZ, y, underground, replacesPlatformStart, identity, jigsaw, fit); + return Objects.hash(structure, chunkX, chunkZ, y, underground, replacesPlatformStart, identity, jigsaw, memo); } @Override diff --git a/src/main/java/com/volmit/vanilla/VanillaStructureStartContext.java b/src/main/java/com/volmit/vanilla/VanillaStructureStartContext.java index b55aae13c..22b87a616 100644 --- a/src/main/java/com/volmit/vanilla/VanillaStructureStartContext.java +++ b/src/main/java/com/volmit/vanilla/VanillaStructureStartContext.java @@ -3,7 +3,7 @@ package com.volmit.vanilla; import com.volmit.world.PackWorld; import com.volmit.world.TerrainSampler; -/** The world and chunk a {@link VanillaStructureHook} places starts for. Valid only while the hook runs. */ +/** The world and chunk a {@link com.volmit.service.VanillaStructures} provider places starts for. Valid only while the provider runs. */ public interface VanillaStructureStartContext { /** The world: its seed, pack resources and settings, and the state modules keep for it. */ PackWorld world(); diff --git a/src/main/java/com/volmit/vanilla/YBand.java b/src/main/java/com/volmit/vanilla/YBand.java deleted file mode 100644 index d4cd5ceaa..000000000 --- a/src/main/java/com/volmit/vanilla/YBand.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.volmit.vanilla; - -import com.volmit.config.Desc; -import com.volmit.config.MaxNumber; -import com.volmit.config.MinNumber; -import java.util.Objects; - -/** A band of absolute world heights a platform structure is moved into, as packs write it: - * {@code {"min": -120, "max": -20}}. Unlike other API heights these are world Y, as the platform's own structure - * definitions use them. Reversed bounds mean the same band. A value the host creates with the no-argument constructor - * and reads the JSON into. - */ -@Desc("An absolute world Y band a native structure is relocated into. Reversed bounds are normalized.") -public final class YBand { - @MinNumber(-4064) - @MaxNumber(4064) - @Desc("Lowest absolute world Y of the band.") - private int min = 0; - - @MinNumber(-4064) - @MaxNumber(4064) - @Desc("Highest absolute world Y of the band.") - private int max = 0; - - private YBand() { - } - - private YBand(int min, int max) { - this.min = min; - this.max = max; - } - - public static YBand of(int min, int max) { - return new YBand(min, max); - } - - public int lowest() { - return Math.min(min, max); - } - - public int highest() { - return Math.max(min, max); - } - - @Override - public boolean equals(Object other) { - return other instanceof YBand that && lowest() == that.lowest() && highest() == that.highest(); - } - - @Override - public int hashCode() { - return Objects.hash(lowest(), highest()); - } - - @Override - public String toString() { - return "YBand[" + lowest() + ".." + highest() + "]"; - } -} diff --git a/src/main/java/com/volmit/world/BlockAccess.java b/src/main/java/com/volmit/world/BlockAccess.java new file mode 100644 index 000000000..3e868791f --- /dev/null +++ b/src/main/java/com/volmit/world/BlockAccess.java @@ -0,0 +1,49 @@ +package com.volmit.world; + +import com.volmit.block.BlockFace; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.mantle.BlockBox; +import com.volmit.resource.ResourceId; + +/** The live blocks of an area of the platform's world, for code that reads and changes them in place while the + * platform decorates them, such as a module fitting a structure into its terrain. X and Z are world coordinates; Y is + * the height above the dimension's bottom (0 = bottom), also in {@link #bounds()}. Reading or writing outside the bounds + * throws IndexOutOfBoundsException. + * + *

Built for many calls: {@link #get} returns the same {@link BlockState} instance every time it reads the same + * platform state, {@link #column} reads a whole column into an array the caller keeps, and writing a state this access + * returned, or one the caller keeps as a constant, allocates nothing. Questions about states ({@link #is}, + * {@link #inTag}, {@link #fluid}) take any state, also one the access never returned. + * + *

Not thread-safe, and valid only while the call that handed it out runs. + */ +public interface BlockAccess { + BlockBox bounds(); + + BlockState get(int x, int y, int z); + + /** Reads {@code into.length} blocks of a column upward: {@code into[i]} is the block at height {@code fromY + i}. */ + void column(int x, int z, int fromY, BlockState[] into); + + /** Replaces the block, without updating neighbours, the way the platform's own decoration writes. */ + void set(int x, int y, int z, BlockState state); + + /** + * Whether {@code state} has {@code trait}, as the platform's world answers it: {@link BlockTrait#AIR} for air, + * {@link BlockTrait#SOLID} for what the platform counts as solid, {@link BlockTrait#FLUID} for a state holding any + * fluid (a source, a flowing fluid, a waterlogged block), {@link BlockTrait#LOG} for logs, wood, stems and hyphae and + * {@link BlockTrait#LEAVES} for leaves, by the platform's tags or names. These can differ in corner cases from + * {@link com.volmit.block.BlockRegistry#hasTrait}, which describes blocks the way generation picks them. + */ + boolean is(BlockState state, BlockTrait trait); + + /** Whether {@code state} is in the platform's block tag {@code tag}, such as {@code minecraft:logs}. */ + boolean inTag(BlockState state, ResourceId tag); + + /** Whether the block at the position can carry a full block on its {@code face}, as the platform decides support. */ + boolean sturdy(int x, int y, int z, BlockFace face); + + /** The block of the fluid {@code state} holds, such as water for a waterlogged stair; air when it holds none. */ + BlockState fluid(BlockState state); +} diff --git a/src/test/java/com/volmit/VanillaStructureValuesTest.java b/src/test/java/com/volmit/VanillaStructureValuesTest.java index 811cfffdb..e5b78a2a1 100644 --- a/src/test/java/com/volmit/VanillaStructureValuesTest.java +++ b/src/test/java/com/volmit/VanillaStructureValuesTest.java @@ -1,19 +1,18 @@ package com.volmit; -import com.volmit.block.BlockSpec; -import com.volmit.block.PaletteSpec; +import com.volmit.block.BlockState; import com.volmit.config.OptionsMetadata; import com.volmit.resource.ResourceId; +import com.volmit.service.VanillaStructures; import com.volmit.vanilla.JigsawOverrides; -import com.volmit.vanilla.StructureStilts; -import com.volmit.vanilla.StructureTerrain; -import com.volmit.vanilla.VanillaStructureAdjustment; -import com.volmit.vanilla.VanillaStructureFit; -import com.volmit.vanilla.VanillaStructureHook; +import com.volmit.vanilla.StartMemo; +import com.volmit.vanilla.StartReach; +import com.volmit.vanilla.StructureStep; +import com.volmit.vanilla.TemplateCells; +import com.volmit.vanilla.VanillaStructureContext; import com.volmit.vanilla.VanillaStructureRule; import com.volmit.vanilla.VanillaStructureSetup; import com.volmit.vanilla.VanillaStructureStart; -import com.volmit.vanilla.YBand; import org.junit.jupiter.api.Test; import java.util.List; import java.util.Map; @@ -21,45 +20,18 @@ import java.util.Optional; import java.util.OptionalInt; import static org.junit.jupiter.api.Assertions.*; -/** The values a vanilla structure hook answers with and how the host combines several modules' answers. */ +/** The values a vanilla structures provider answers with and how the host combines several modules' answers. */ class VanillaStructureValuesTest { private static final ResourceId VILLAGES = ResourceId.parse("minecraft:villages"); private static final ResourceId CITY = ResourceId.parse("minecraft:ancient_city"); @Test - void fitValuesKeepThePacksJsonNamesAndDefaults() { - assertEquals(List.of("mode", "horizontalPadding", "ceilingPadding", "floorPadding", "shape", "encasePalette", - "erosionStrength", "erosionFrequency", "lobeFrequency", "lobeStrength"), names(StructureTerrain.class)); - assertEquals(List.of("maxDepth", "palette", "spacing", "supportNonOccluding"), names(StructureStilts.class)); - assertEquals(List.of("min", "max"), names(YBand.class)); + void jigsawOverridesKeepThePacksJsonNamesAndDefaults() { assertEquals(List.of("startPool", "startJigsawName", "maxDepth", "maxDistanceHorizontal", "maxDistanceVertical", "useExpansionHack", "projectStartToHeightmap", "dimensionPaddingBottom", "dimensionPaddingTop", "liquidSettings"), names(JigsawOverrides.class)); - - var terrain = StructureTerrain.of(StructureTerrain.Mode.FORCE_CARVE); - assertEquals(StructureTerrain.Shape.BOX, terrain.shape()); - assertEquals(0.8, terrain.erosionStrength()); - assertEquals(0.07, terrain.erosionFrequency()); - assertEquals(Optional.empty(), terrain.encasePalette()); - var stilts = StructureStilts.of(PaletteSpec.of(List.of(BlockSpec.of("minecraft:cobblestone")))); - assertEquals(64, stilts.maxDepth()); - assertEquals(1, stilts.spacing()); assertEquals(OptionalInt.empty(), JigsawOverrides.none().maxDepth()); assertEquals(JigsawOverrides.Heightmap.SOURCE, JigsawOverrides.none().projectStartToHeightmap()); - } - - @Test - void fitValuesAreValuesChangedOnlyThroughWithers() { - var carve = StructureTerrain.of(StructureTerrain.Mode.FORCE_CARVE).withPadding(4, 2, 1) - .withShape(StructureTerrain.Shape.ERODED).withErosion(0.5, 0.1).withLobes(0.2, 0.4); - - assertEquals(carve, StructureTerrain.of(StructureTerrain.Mode.FORCE_CARVE).withShape(StructureTerrain.Shape.ERODED) - .withLobes(0.2, 0.4).withErosion(0.5, 0.1).withPadding(4, 2, 1)); - assertEquals(4, carve.horizontalPadding()); - assertEquals(0.4, carve.lobeStrength()); - assertNotEquals(carve, carve.withPadding(4, 2, 0)); - assertEquals(YBand.of(-20, -120), YBand.of(-120, -20), "reversed bounds are the same band"); - assertEquals(-120, YBand.of(-20, -120).lowest()); var overrides = JigsawOverrides.none().withStartPool("minecraft:village/plains/town_centers").withMaxDepth(4) .withMaxDistance(80, 120).withHeightmap(JigsawOverrides.Heightmap.NONE); assertEquals(OptionalInt.of(4), overrides.maxDepth()); @@ -69,22 +41,36 @@ class VanillaStructureValuesTest { } @Test - void adjustmentsAddShiftsAndLetTheLaterBandAndFitPartsWin() { - var stilts = StructureStilts.of(PaletteSpec.of(List.of(BlockSpec.of("stone")))); - var carve = StructureTerrain.of(StructureTerrain.Mode.BORE); - var first = VanillaStructureAdjustment.NONE.shifted(-32).withYBand(YBand.of(-60, -20)) - .withFit(VanillaStructureFit.SOURCE.withStilts(stilts)); - var second = VanillaStructureAdjustment.NONE.shifted(8).keepingSourceY() - .withFit(VanillaStructureFit.SOURCE.withTerrain(carve)); + void reachesAreThePlatformsOrANumberOfBlocks() { + assertTrue(StartReach.PLATFORM.platform()); + assertEquals(StartReach.blocks(0), StartReach.blocks(0)); + assertFalse(StartReach.blocks(12).platform()); + assertEquals(12, StartReach.blocks(12).blocks()); + assertThrows(IllegalArgumentException.class, () -> StartReach.blocks(-1)); + assertThrows(IllegalArgumentException.class, () -> new StartReach(true, 3)); + } - var combined = first.then(second); + @Test + void templateCellsKeepTheirCellsAndMarkRemovedBlocks() { + var stone = new BlockState("minecraft:stone"); + var cells = TemplateCells.of(new int[]{1, 2}, new int[]{60, 61}, new int[]{-3, -4}, new BlockState[]{stone, null}, 7); - assertEquals(-24, combined.yShift()); - assertEquals(Optional.of(YBand.of(-60, -20)), combined.yBand(), "the later adjustment has no band"); - assertTrue(combined.keepsSourceY()); - assertEquals(VanillaStructureFit.SOURCE.withStilts(stilts).withTerrain(carve), combined.fit()); - assertEquals(Optional.of(YBand.of(0, 10)), combined.then(VanillaStructureAdjustment.NONE.withYBand(YBand.of(0, 10))).yBand()); - assertEquals(first, first.then(VanillaStructureAdjustment.NONE), "NONE changes nothing"); + assertTrue(cells.resolved()); + assertEquals(2, cells.size()); + assertEquals(7, cells.readBlocks()); + assertEquals(61, cells.y(1)); + assertSame(stone, cells.state(0)); + assertTrue(cells.removed(1)); + assertFalse(TemplateCells.UNRESOLVED.resolved()); + assertEquals(0, TemplateCells.UNRESOLVED.size()); + assertThrows(IllegalArgumentException.class, + () -> TemplateCells.of(new int[]{1}, new int[0], new int[]{1}, new BlockState[]{stone}, 0)); + } + + @Test + void onlyTheUndergroundStepsAreUnderground() { + assertEquals(List.of(StructureStep.UNDERGROUND_STRUCTURES, StructureStep.STRONGHOLDS, StructureStep.UNDERGROUND_DECORATION), + java.util.Arrays.stream(StructureStep.values()).filter(StructureStep::isUnderground).toList()); } @Test @@ -101,12 +87,15 @@ class VanillaStructureValuesTest { } @Test - void startsSitOnTheSurfaceWithTheStructuresOwnFitUnlessTheModuleSaysOtherwise() { + void startsSitOnTheSurfaceWithoutAMemoUnlessTheModuleSaysOtherwise() { var start = VanillaStructureStart.at(CITY, 12, -7, 40); assertFalse(start.isUnderground()); assertFalse(start.replacesPlatformStart()); - assertEquals(VanillaStructureFit.SOURCE, start.fit()); + assertEquals(Optional.empty(), start.memo()); + var memo = new StartMemo("{\"mode\":\"VACUUM\"}", "null"); + assertEquals(Optional.of(memo), start.withMemo(memo).memo()); + assertNotEquals(start, start.withMemo(memo)); assertEquals(Optional.empty(), start.jigsaw()); var underground = start.underground().replacingPlatformStart().withIdentity(-5L) .withJigsaw(JigsawOverrides.none().withMaxDepth(3)); @@ -119,12 +108,20 @@ class VanillaStructureValuesTest { } @Test - void aHookThatOnlyRulesChangesNothingElse() { - VanillaStructureHook hook = (structure, context) -> VanillaStructureRule.BLOCK; + void aProviderThatOnlyRulesChangesNothingElse() { + VanillaStructures provider = new VanillaStructures() { + @Override + public VanillaStructureRule rule(ResourceId structure, VanillaStructureContext context) { + return VanillaStructureRule.BLOCK; + } + }; - assertEquals(VanillaStructureAdjustment.NONE, hook.adjustment(CITY, true, null)); - assertEquals(List.of(), hook.starts(0, 0, null)); - assertEquals(VanillaStructureSetup.UNCHANGED, hook.setup(null)); + assertEquals(VanillaStructureRule.BLOCK, provider.rule(CITY, null)); + assertEquals(List.of(), provider.starts(0, 0, null)); + assertEquals(0, provider.shift(null, null)); + assertEquals(StartReach.PLATFORM, provider.reach(CITY, true, Optional.empty(), null)); + assertEquals(VanillaStructureSetup.UNCHANGED, provider.setup(null)); + assertEquals(VanillaStructureRule.GENERATE, new VanillaStructures() { }.rule(CITY, null)); } private static List names(Class type) { diff --git a/src/test/java/com/volmit/host/ModuleRegistryTest.java b/src/test/java/com/volmit/host/ModuleRegistryTest.java index d625d4d69..6e080f80a 100644 --- a/src/test/java/com/volmit/host/ModuleRegistryTest.java +++ b/src/test/java/com/volmit/host/ModuleRegistryTest.java @@ -7,8 +7,7 @@ import com.volmit.resource.ResourceKind; import com.volmit.service.Providers; import com.volmit.service.Service; import com.volmit.validation.Validator; -import com.volmit.vanilla.VanillaStructureHook; -import com.volmit.vanilla.VanillaStructureRule; +import com.volmit.service.VanillaStructures; import com.volmit.stage.PlacementStage; import com.volmit.stage.Stage; import com.volmit.stage.StageGraph; @@ -429,22 +428,14 @@ class ModuleRegistryTest { } @Test - void vanillaStructureHooksAreCataloguedByModuleIdInTheOrderEachModuleRegisteredThem() { + void vanillaStructuresAreAServiceEveryModuleMayProvide() { var registry = new ModuleRegistry(); - VanillaStructureHook first = (structure, world) -> VanillaStructureRule.REPLACE; - VanillaStructureHook second = (structure, world) -> VanillaStructureRule.GENERATE; - VanillaStructureHook other = (structure, world) -> VanillaStructureRule.BLOCK; - registerAs(registry, "test:zeta", hooks -> hooks.registerVanillaStructureHook(other)); - registerAs(registry, "test:alpha", hooks -> { - hooks.registerVanillaStructureHook(first); - hooks.registerVanillaStructureHook(second); - }); + VanillaStructures first = new VanillaStructures() { }; + VanillaStructures other = new VanillaStructures() { }; + registerAs(registry, "test:zeta", services -> services.registerService(VanillaStructures.class, other)); + registerAs(registry, "test:alpha", services -> services.registerService(VanillaStructures.class, first)); - assertThrows(IllegalStateException.class, () -> registry.registerVanillaStructureHook(first), "outside register"); - var hooks = registry.freeze().vanillaStructureHooks(); - assertEquals(List.of(first, second, other), hooks.stream().map(VanillaStructureHookRegistration::hook).toList()); - assertEquals("test:alpha", hooks.getFirst().module().info().id().toString()); - assertThrows(IllegalStateException.class, () -> registry.registerVanillaStructureHook(first), "registration has ended"); + assertEquals(List.of(first, other), registry.freeze().services(VanillaStructures.class)); } private static MantleCodec codec(int version) {