diff --git a/CONTRACTS.md b/CONTRACTS.md index 5a44c5c53..28a138202 100644 --- a/CONTRACTS.md +++ b/CONTRACTS.md @@ -34,7 +34,7 @@ types that carry them and lists what the Iris adapter still owes. | Module-owned pack checks | `Validator`, `ValidationContext`, `Problem`, `Severity`, `Subject`, `FeatureRegistry.registerValidator`, host `FeatureCatalog.validators()` | | Per-world module state | `PackWorld` (`state`), `InvocationContext.world()`, host `WorldStates` | | Module lifecycle across loads, hotloads and reloads | `ModuleLifecycle`, `FeatureRegistry.registerLifecycle`, host `FeatureCatalog.lifecycles()`, `LifecycleRunner` | -| Host questions answered by modules | `@Service`, `Providers`, `FeatureRegistry.registerService`, host `FeatureCatalog.services(type)` / `service(type)`; services `ObjectsAt`, `StructureLocator` (`LocateResult`) | +| Host questions answered by modules | `@Service`, `Providers`, `FeatureRegistry.registerService`, host `FeatureCatalog.services(type)` / `service(type)`; services `ObjectsAt`, `StructureLocator` (`LocateResult`), `SaplingGrowth`, `Loot`, `BlockDrops`, `EntitySpawns`; values `ItemDrop`, `EntitySpec`, `ItemRegistry` (`PackResources.items()`) | | Terrain and settings sampling | `TerrainSampler`, `BiomeSample`, `TerrainSample`, `FeatureSettings` | | Dense chunk output | `Hunk`, `GenerationContext.hunk`, reference `ArrayHunk` | | Sparse geometry and transforms | `ObjectGenerator`, `GeneratedObject`, `ObjectTransform`, `ObjectTransformer` | @@ -175,7 +175,11 @@ running Iris is the pack publisher's responsibility. catalog order until one answers, and use `service(type)` for `ONE`. Call providers from any thread, but long searches off the server's main thread, and carry out what they return on the thread the platform needs. - Read a `StructureLocator` position's Y as a height above the dimension's bottom and convert it to the platform's Y - at the boundary, like every other IrisApi height. + at the boundary, like every other IrisApi height; the same goes for the positions of `Loot.Site`, `BlockDrops.Broken`, + `EntitySpawns` and `SaplingGrowth`. +- Create what `ItemDrop` and `EntitySpec` describe on the platform, skip what the platform lacks (an unknown enchantment, + attribute or item flag) with a warning, and run the checks that come with an `EntitySpawns.Attempt` (light, surface, + free space) before spawning. Report how many entities appeared with `EntitySpawns.spawned`. - Decode IrisApi's value types like settings: `BlockSpec`, `PaletteSpec`, `NoiseStyle`, `StyledRange`, `Range` and `BlockPosition` from the JSON shapes in their docs, `Object` as maps, lists, `Double`s, strings and booleans. Read a `"snippet/"` or `"snippet//"` string of a `@Snippet` type from diff --git a/DESIGN.md b/DESIGN.md index b1743169d..0ab7f2a4f 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -933,8 +933,16 @@ from a sapling, which drops a block has. A module answers such questions through have several providers. - **Threading.** The host may call a provider from any thread, several at once. A provider that searches long (`StructureLocator.locate`) is called off the server's main thread. +- **Loot, drops, entities, trees.** `Loot` (`ALL`) asks in two steps, which tables a container draws from and what a + table gives, so the host and plugins can change the tables in between. `BlockDrops`, `EntitySpawns` and `SaplingGrowth` + return values the host carries out: `ItemDrop` and `EntitySpec` carry every decision the module made (the module draws + from its streams in the order the feature always did, which is why `ItemRegistry` answers whether an item can be + damaged), and the host reads what only the platform knows (light, the surface below, free space, the blocks around a + sapling) through the attempt's conditions or a `Surroundings` view. A service that must hear how its plan went has a + second method for it (`EntitySpawns.spawned`, which keeps a spawner's rate limits). - **Services now.** `ObjectsAt` (`ALL`): pack object keys a module would place in a chunk, predicted without - generating it. `StructureLocator` (`FIRST`): every structure key a module knows, the ones a world places, and the + generating it, and the biomes and regions whose settings place a given object (`PlacedBy`, named by pack keys; the + host builds its search area from them through the biome tree it owns). `StructureLocator` (`FIRST`): every structure key a module knows, the ones a world places, and the nearest start of one as a `LocateResult` (`Found`, `NotFound`, `SearchLimitReached`; a sealed interface, so callers switch over every outcome). Keys are pack keys as packs write them and match without regard to case. - **Why not per-world provider instances.** A factory per world (`world -> provider`) would let a provider hold its diff --git a/README.md b/README.md index b524917f8..930005d27 100644 --- a/README.md +++ b/README.md @@ -264,11 +264,17 @@ them up in the pack's catalog instead of knowing the feature. ```java public void register(FeatureRegistry registry) { - registry.registerService(ObjectsAt.class, RuinsModule::objectsAt); + registry.registerService(ObjectsAt.class, new RuinsObjects()); } -private static Set objectsAt(PackWorld world, int chunkX, int chunkZ) { - return planted(world).contains(chunkX, chunkZ) ? Set.of("ruins/arch") : Set.of(); +final class RuinsObjects implements ObjectsAt { + public Set objectsAt(PackWorld world, int chunkX, int chunkZ) { + return planted(world).contains(chunkX, chunkZ) ? Set.of("ruins/arch") : Set.of(); + } + + public PlacedBy placedBy(PackWorld world, String objectKey) { + return PlacedBy.NOTHING; + } } ``` @@ -283,8 +289,12 @@ private static Set objectsAt(PackWorld world, int chunkX, int chunkZ) { | Service | Providers | What the host asks | | --- | --- | --- | -| `ObjectsAt` | `ALL` | The pack objects a module would place in a chunk, predicted without generating it (object search, studio tools). | +| `ObjectsAt` | `ALL` | The pack objects a module would place in a chunk, predicted without generating it, and the biomes and regions of the layout that place a given object (`PlacedBy`), so the host can narrow an object search to the areas it can appear in. | | `StructureLocator` | `FIRST` | Every structure key the module knows (the structure index), the ones a world places (commands complete them), and the nearest start of one, as a `LocateResult`: `Found(position)`, `NotFound` or `SearchLimitReached`. Keys match without regard to case. | +| `SaplingGrowth` | `ALL` | The tree a growing sapling becomes, as a `Growth` of placed blocks (the first module with one wins; none leaves the growth to the platform), and the objects the module places as trees (`TreeObjects`). The host passes `Surroundings` to read the world around the sapling and places the blocks itself. | +| `Loot` | `ALL` | The loot tables a container draws from at a `Site` (`Table` of the pack, `PlatformTable` with the seed to draw it with), in the order their items are added, and the `ItemDrop`s one table gives there. The host puts them together, tells listeners, creates the stacks and shuffles the container. | +| `BlockDrops` | `ALL` | What a module drops for a broken block: `ItemDrop`s, and whether the platform's own drops of the block are replaced. | +| `EntitySpawns` | `ALL` | A `Plan` of entities to spawn in a chunk or at a marker, each `Attempt` an `EntitySpec` with the block, light range and surface it needs; how many appeared (`spawned`); what a marker means (`MarkerRule`); one entity of the pack on request. The host checks light, surface and free space, spawns, and applies the spec. | ``` Service example.Clock is provided by module example:alpha from modules/alpha.jar already, and module example:beta from modules/beta.jar provides it too; a pack has one provider of it (Providers.ONE), so remove one of them @@ -424,6 +434,16 @@ Class com.example.flora.Shape of settings example:flora (module example:flora fr Snippet name 'patch' of com.example.flora.Patch of settings example:flora (module example:flora from modules/flora.jar) is not under a module of the pack; snippets of pack modules start with their module's id as a folder path, such as 'example/flora/patch' (folder snippet/example/flora/patch/) ``` +## Items and entities + +A service describes an item or an entity as a value after making every random choice, and the host creates it on the +platform. `ItemDrop` is one stack: the item key as the pack wrote it, the amount, name, lore, enchantments, attribute +modifiers, damage as a fraction of the item's durability, colours and custom data. `EntitySpec` is one entity: its type +or the other plugin's mob, flags, equipment (`ItemDrop`s), passengers, attribute modifiers, loot table keys, leash +holder, spawn effect and console commands. Modules ask the platform about items through `resources.items()` +(`ItemRegistry.maxDurability(key)`, empty for an item the platform lacks): whether an item can be damaged decides +whether a loot entry draws a damage roll, so a module needs it to keep its random stream. + ## Values in settings Settings describe blocks, noise and ranges with IrisApi's value types, which read the JSON packs already write: diff --git a/src/main/java/com/volmit/entity/EntitySpec.java b/src/main/java/com/volmit/entity/EntitySpec.java new file mode 100644 index 000000000..5eb6a06a1 --- /dev/null +++ b/src/main/java/com/volmit/entity/EntitySpec.java @@ -0,0 +1,86 @@ +package com.volmit.entity; + +import com.volmit.item.ItemAttribute; +import com.volmit.item.ItemDrop; +import java.util.List; +import java.util.Objects; + +/** + * An entity a module decided to spawn, with every random choice made: the host creates it on the platform and applies + * what is set. Names are as authored in the pack, with {@code &} colour codes. + * + * @param type the entity type's key, such as {@code minecraft:zombie}; ignored when {@code specialType} is set + * @param specialType a mob of another plugin, written {@code PluginName:MobName}, or empty + * @param reason the platform's spawn reason by name, or null for a natural spawn + * @param customName the name shown above the entity, empty for none + * @param flags the settings that every entity kind understands + * @param equipment what the entity wears and holds + * @param passengers entities that ride this one + * @param attributes attribute modifiers to apply + * @param lootTables keys of loot tables the entity drops, instead of the platform's drops, when it dies + * @param lootShuffleSeed seeds how the drops of {@code lootTables} are shuffled + * @param leashHolder the entity that holds this one on a leash, or null + * @param spawnEffect an effect to show when the entity appears, or null + * @param riseOutOfGround whether the entity slowly climbs out of the ground when players are near + * @param pandaMainGene for pandas the main gene by name, or null + * @param pandaHiddenGene for pandas the hidden gene by name, or null + * @param applySettingsToSpecial whether the settings also apply to a mob of another plugin + * @param commands console commands to run where the entity appears + */ +public record EntitySpec(String type, String specialType, String reason, String customName, Flags flags, Equipment equipment, + List passengers, List attributes, List lootTables, + long lootShuffleSeed, EntitySpec leashHolder, SpawnEffect spawnEffect, boolean riseOutOfGround, + String pandaMainGene, String pandaHiddenGene, boolean applySettingsToSpecial, + List commands) { + public EntitySpec { + Objects.requireNonNull(type, "type"); + Objects.requireNonNull(specialType, "specialType"); + Objects.requireNonNull(customName, "customName"); + Objects.requireNonNull(flags, "flags"); + Objects.requireNonNull(equipment, "equipment"); + passengers = List.copyOf(passengers); + attributes = List.copyOf(attributes); + lootTables = List.copyOf(lootTables); + commands = List.copyOf(commands); + } + + /** Whether the entity is a mob of another plugin. */ + public boolean isSpecial() { + return !specialType.isEmpty(); + } + + /** What an entity can be set to be, whatever its kind; the host applies the ones its kind has. */ + public record Flags(boolean customNameVisible, boolean aware, boolean ai, boolean glowing, boolean gravity, + boolean invulnerable, boolean silent, boolean pickupItems, boolean removable, + boolean keepEntity, boolean baby) { + } + + /** The items an entity wears and holds; null for an empty slot. */ + public record Equipment(ItemDrop helmet, ItemDrop chestplate, ItemDrop leggings, ItemDrop boots, ItemDrop mainHand, + ItemDrop offHand) { + public static final Equipment NONE = new Equipment(null, null, null, null, null, null); + } + + /** + * Sound and particles shown around an entity that appears. Offsets and the randomness of the particle motion are + * as in an effect of the pack; the host makes the random choices. + */ + public record SpawnEffect(String sound, int soundDistance, double minPitch, double maxPitch, double volume, + String particle, int particleOffset, int particleCount, double altX, double altY, + double altZ, boolean randomAltX, boolean randomAltY, boolean randomAltZ, double extra) { + } + + /** + * Console commands run when an entity appears. {@code {x}}, {@code {y}} and {@code {z}} stand for its block position. + * + * @param commands the commands + * @param delay server ticks to wait before running them + * @param repeat whether to run them again and again until the server stops + * @param repeatDelay server ticks between repeats + */ + public record Command(List commands, long delay, boolean repeat, long repeatDelay) { + public Command { + commands = List.copyOf(commands); + } + } +} diff --git a/src/main/java/com/volmit/item/ItemAttribute.java b/src/main/java/com/volmit/item/ItemAttribute.java new file mode 100644 index 000000000..cf1c45404 --- /dev/null +++ b/src/main/java/com/volmit/item/ItemAttribute.java @@ -0,0 +1,18 @@ +package com.volmit.item; + +import java.util.Objects; + +/** An attribute modifier of an {@link ItemDrop} or an entity, with the amount the module decided. The host creates a + * modifier under an id it makes unique from {@code name}, for every equipment slot. + * + * @param attribute the platform attribute's key, such as {@code max_health} or {@code minecraft:armor} + * @param name identifies the modifier among those of one item or entity; not shown to players + * @param operation {@code ADD_NUMBER}, {@code ADD_SCALAR} or {@code MULTIPLY_SCALAR_1} + */ +public record ItemAttribute(String attribute, String name, String operation, double amount) { + public ItemAttribute { + Objects.requireNonNull(attribute, "attribute"); + Objects.requireNonNull(name, "name"); + Objects.requireNonNull(operation, "operation"); + } +} diff --git a/src/main/java/com/volmit/item/ItemDrop.java b/src/main/java/com/volmit/item/ItemDrop.java new file mode 100644 index 000000000..fccc8a38a --- /dev/null +++ b/src/main/java/com/volmit/item/ItemDrop.java @@ -0,0 +1,57 @@ +package com.volmit.item; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + * One stack of items a module decided to give: what a loot entry, a block's drops or an entity's equipment turned into + * after the module made every random choice. The host creates the stack on the platform. Names and lore are as authored + * in the pack, with {@code &} colour codes; the host translates and wraps them. + * + * @param item the item's key as the pack wrote it, see {@link ItemRegistry} + * @param amount how many, at least 1 + * @param displayName the item's name, or null to keep the platform's + * @param lore lines of text under the name + * @param enchantments applied in order + * @param attributes attribute modifiers applied in order + * @param unbreakable whether the item never breaks + * @param flags platform item flags to set, by name; names the platform lacks are ignored + * @param customModel custom model number, or null + * @param damage the fraction of the item's durability already used, 0 to 1, or null to leave it undamaged + * @param leatherColor colour of leather armour as {@code #rrggbb}, or null + * @param dyeColor dye colour name, or null + * @param customNbt custom data the platform stores on the item, or empty + * @param source where the item came from, set only when the host asked for it to be shown (debug loot) + */ +public record ItemDrop(String item, int amount, String displayName, List lore, List enchantments, + List attributes, boolean unbreakable, List flags, Integer customModel, + Double damage, String leatherColor, String dyeColor, Map customNbt, Source source) { + public ItemDrop { + Objects.requireNonNull(item, "item"); + if (amount < 1) throw new IllegalArgumentException("Item amount must be at least 1: " + amount); + lore = List.copyOf(lore); + enchantments = List.copyOf(enchantments); + attributes = List.copyOf(attributes); + flags = List.copyOf(flags); + customNbt = customNbt == null ? Map.of() : Collections.unmodifiableMap(new LinkedHashMap<>(customNbt)); + } + + /** {@code amount} items of kind {@code item} and nothing else. */ + public static ItemDrop of(String item, int amount) { + return new ItemDrop(item, amount, null, List.of(), List.of(), List.of(), false, List.of(), null, null, null, null, + Map.of(), null); + } + + /** + * Where a shown item came from: the loot table, when it came from one, and the 1-in-N chances it passed. + * + * @param table the table's name, or null for an item that came from no table + * @param tableRarity the table's rarity, 1 in this many + * @param entryRarity the entry's rarity within the table + */ + public record Source(String table, int tableRarity, int entryRarity) { + } +} diff --git a/src/main/java/com/volmit/item/ItemEnchantment.java b/src/main/java/com/volmit/item/ItemEnchantment.java new file mode 100644 index 000000000..e1de9d3d7 --- /dev/null +++ b/src/main/java/com/volmit/item/ItemEnchantment.java @@ -0,0 +1,13 @@ +package com.volmit.item; + +import java.util.Objects; + +/** An enchantment of an {@link ItemDrop}, named by the key the platform's registry knows ({@code sharpness}, + * {@code mymod:vorpal}) with the level the module decided. + */ +public record ItemEnchantment(String key, int level) { + public ItemEnchantment { + Objects.requireNonNull(key, "key"); + if (level < 1) throw new IllegalArgumentException("Enchantment level must be at least 1: " + level); + } +} diff --git a/src/main/java/com/volmit/item/ItemRegistry.java b/src/main/java/com/volmit/item/ItemRegistry.java new file mode 100644 index 000000000..7a83e573e --- /dev/null +++ b/src/main/java/com/volmit/item/ItemRegistry.java @@ -0,0 +1,15 @@ +package com.volmit.item; + +import java.util.OptionalInt; + +/** What a module may ask the platform about items, so that its decisions follow the item they concern. Item keys are + * written as in packs: {@code diamond_sword}, {@code minecraft:diamond_sword}, or a custom item of a provider such as + * {@code itemsadder:ruby}. Safe for concurrent use. + */ +public interface ItemRegistry { + /** + * The most damage an item of this kind takes before it breaks, 0 for an item that cannot be damaged; empty when no + * item is known by {@code key}. + */ + OptionalInt maxDurability(String key); +} diff --git a/src/main/java/com/volmit/resource/PackResources.java b/src/main/java/com/volmit/resource/PackResources.java index f7e164bdb..733ba0319 100644 --- a/src/main/java/com/volmit/resource/PackResources.java +++ b/src/main/java/com/volmit/resource/PackResources.java @@ -1,6 +1,7 @@ package com.volmit.resource; import com.volmit.block.BlockRegistry; +import com.volmit.item.ItemRegistry; import com.volmit.noise.NoiseFactory; import java.util.List; import java.util.NoSuchElementException; @@ -21,6 +22,9 @@ public interface PackResources { UUID snapshotId(); BlockRegistry blocks(); + /** Asks the platform about items, such as how much damage one takes. */ + ItemRegistry items(); + /** Builds the noise of the {@link com.volmit.noise.NoiseStyle}s the pack's settings describe. */ NoiseFactory noise(); diff --git a/src/main/java/com/volmit/service/BlockDrops.java b/src/main/java/com/volmit/service/BlockDrops.java new file mode 100644 index 000000000..b1156b0e8 --- /dev/null +++ b/src/main/java/com/volmit/service/BlockDrops.java @@ -0,0 +1,44 @@ +package com.volmit.service; + +import com.volmit.block.BlockState; +import com.volmit.item.ItemDrop; +import com.volmit.world.BlockPosition; +import com.volmit.world.PackWorld; +import java.util.List; +import java.util.Objects; + +/** + * Items a module drops when a block breaks, in addition to or instead of the platform's. The host asks every provider + * when a player breaks a block in a world generated with the pack, drops the items of all answers where the block was + * and keeps the platform's own drops unless an answer replaces them. + */ +@Service(Providers.ALL) +public interface BlockDrops { + /** What this module drops for the block {@code broken}; {@link Result#NONE} when it does nothing for that block. */ + Result drops(PackWorld world, Broken broken); + + /** + * The block that was broken. + * + * @param position world X and Z, Y the height above the dimension's bottom + * @param block the block as it was + */ + record Broken(BlockPosition position, BlockState block) { + public Broken { + Objects.requireNonNull(position, "position"); + Objects.requireNonNull(block, "block"); + } + } + + /** + * @param drops the items to drop + * @param replacesVanillaDrops whether the platform's own drops of the block are not dropped + */ + record Result(List drops, boolean replacesVanillaDrops) { + public static final Result NONE = new Result(List.of(), false); + + public Result { + drops = List.copyOf(drops); + } + } +} diff --git a/src/main/java/com/volmit/service/EntitySpawns.java b/src/main/java/com/volmit/service/EntitySpawns.java new file mode 100644 index 000000000..a00a6c368 --- /dev/null +++ b/src/main/java/com/volmit/service/EntitySpawns.java @@ -0,0 +1,126 @@ +package com.volmit.service; + +import com.volmit.entity.EntitySpec; +import com.volmit.world.BlockPosition; +import com.volmit.world.PackWorld; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +/** + * The entities a module spawns in the world over time: spawners the dimension, region and biomes list, and the spawners + * markers in the world name. The host decides when and where to look, asks the providers, and spawns what the first + * answer plans, after checking the conditions of the platform that come with it (light, the surface below, free space). + * It tells the module how many entities appeared so that the module can keep its limits on how often a spawner fires. + */ +@Service(Providers.ALL) +public interface EntitySpawns { + /** What the module plans to spawn in the chunk or at the marker, or empty to spawn nothing. */ + Optional plan(PackWorld world, Site site); + + /** Called with the number of entities of {@code plan} that appeared, so the spawner's rate limits count them. */ + void spawned(PackWorld world, Plan plan, int count); + + /** The entity of the pack named {@code key} as this module would spawn it, for tools that spawn one on request; empty for an unknown key. */ + Optional entity(PackWorld world, String key); + + /** What a marker in the world means for spawning; empty for a marker this module does not know. */ + Optional marker(PackWorld world, String tag); + + /** Where entities may spawn. */ + sealed interface Site permits Chunk, Marker { + } + + /** + * An ambient spawn in a chunk. + * + * @param chunkX chunk coordinates + * @param livingEntities how many living entities the chunk already holds + * @param initial whether this is the spawn of a chunk that was just generated + */ + record Chunk(int chunkX, int chunkZ, int livingEntities, boolean initial) implements Site { + } + + /** + * A spawn at a marker. + * + * @param position the marker's block: world X and Z, Y the height above the dimension's bottom + * @param marker the marker's tag + * @param spawner the key of the spawner chosen among the marker's + * @param initial whether the spawner's initial spawns are used rather than its ordinary ones + */ + record Marker(BlockPosition position, String marker, String spawner, boolean initial) implements Site { + public Marker { + Objects.requireNonNull(position, "position"); + Objects.requireNonNull(marker, "marker"); + Objects.requireNonNull(spawner, "spawner"); + } + } + + /** + * What a marker does. + * + * @param spawners keys of the spawners at the marker + * @param emptyAbove whether it only counts with free space above it + * @param removeOnChange whether it goes away when its block changes + */ + record MarkerRule(List spawners, boolean emptyAbove, boolean removeOnChange) { + public MarkerRule { + spawners = List.copyOf(spawners); + } + } + + /** + * Entities to spawn, tried one after the other. + * + * @param spawner the key of the spawner that planned them + * @param chunkX the chunk they spawn in, where the spawner's per-chunk limit counts them + * @param exhaustsMarker whether the marker that led here is used up and should be removed + * @param attempts the spawns to try + */ + record Plan(String spawner, int chunkX, int chunkZ, boolean exhaustsMarker, List attempts) { + public Plan { + Objects.requireNonNull(spawner, "spawner"); + attempts = List.copyOf(attempts); + } + } + + /** + * One entity to spawn at a block. The host spawns it only if the block's light level lies in the range (when the + * range is restricted) and, when {@code checkSurface}, the block below suits the entity's {@code surface} and the + * space the entity needs is free. + * + * @param at world X and Z, Y the height above the dimension's bottom + * @param entity what to spawn + * @param surface the kind of ground or fluid the entity needs below it + * @param minLight lowest light level allowed, 0 for any + * @param maxLight highest light level allowed, 15 for any + * @param checkSurface whether to check the surface and the free space + */ + record Attempt(BlockPosition at, EntitySpec entity, Surface surface, int minLight, int maxLight, boolean checkSurface) { + public Attempt { + Objects.requireNonNull(at, "at"); + Objects.requireNonNull(entity, "entity"); + Objects.requireNonNull(surface, "surface"); + } + + /** Whether the light level matters. */ + public boolean restrictsLight() { + return minLight > 0 || maxLight < 15; + } + } + + /** The ground or fluid an entity spawns on. */ + enum Surface { + /** Solid ground. */ + LAND, + /** Ground animals spawn on, such as grass, dirt and podzol. */ + ANIMAL, + /** Within water. */ + WATER, + /** Solid ground or water. */ + OVERWORLD, + /** Within lava. */ + LAVA + } +} diff --git a/src/main/java/com/volmit/service/Loot.java b/src/main/java/com/volmit/service/Loot.java new file mode 100644 index 000000000..d6eee283d --- /dev/null +++ b/src/main/java/com/volmit/service/Loot.java @@ -0,0 +1,64 @@ +package com.volmit.service; + +import com.volmit.block.BlockState; +import com.volmit.item.ItemDrop; +import com.volmit.world.BlockPosition; +import com.volmit.world.PackWorld; +import java.util.List; +import java.util.Objects; + +/** + * The loot a module gives containers and mobs. The host asks in two steps so that it, and plugins listening to it, can + * see and change which tables are used: {@link #tables} names the tables a container draws from, {@link #items} turns + * one table into items. The host asks every provider and puts the answers together; a provider answers {@link #items} + * only for the tables it knows. A container is filled with items the host creates on the platform, in the order of the + * tables. + */ +@Service(Providers.ALL) +public interface Loot { + /** + * The tables the container at {@code site} draws from, in the order their items are added. Empty when the module + * gives that container nothing. + */ + List tables(PackWorld world, Site site); + + /** The items table {@code key} gives at {@code site}; empty for a table this module does not know. */ + List items(PackWorld world, Site site, String key); + + /** + * Where loot is given. + * + * @param position the container, or the mob's spawn spot: world X and Z, Y the height above the dimension's + * bottom + * @param container the container's block when it is a storage chest the module may give the loot of the object + * placed there, null for any other spot + * @param nativeLootDefined whether the platform already gave the container a loot table of its own + * @param debug whether items should say where they came from ({@link ItemDrop#source()}) + */ + record Site(BlockPosition position, BlockState container, boolean nativeLootDefined, boolean debug) { + public Site { + Objects.requireNonNull(position, "position"); + } + } + + /** Where a container's items come from. */ + sealed interface Source permits Table, PlatformTable { + } + + /** A loot table of the pack, named by its key as packs write it ({@code dungeon/chest}). */ + record Table(String key) implements Source { + public Table { + Objects.requireNonNull(key, "key"); + } + } + + /** + * A loot table of the platform, such as {@code minecraft:chests/simple_dungeon}. The host draws it with {@code seed} + * so that the same container always gets the same items. + */ + record PlatformTable(String key, long seed) implements Source { + public PlatformTable { + Objects.requireNonNull(key, "key"); + } + } +} diff --git a/src/main/java/com/volmit/service/ObjectsAt.java b/src/main/java/com/volmit/service/ObjectsAt.java index 03f6e183b..01c9945d2 100644 --- a/src/main/java/com/volmit/service/ObjectsAt.java +++ b/src/main/java/com/volmit/service/ObjectsAt.java @@ -1,10 +1,11 @@ package com.volmit.service; import com.volmit.world.PackWorld; +import java.util.Objects; import java.util.Set; -/** Which pack objects a module places in a chunk, predicted without generating it. The host's object search and its - * studio tools ask every provider and use all the keys together. +/** Which pack objects a module places, predicted without generating anything. The host's object search and its + * studio tools ask every provider and use all the answers together. */ @Service(Providers.ALL) public interface ObjectsAt { @@ -15,4 +16,26 @@ public interface ObjectsAt { * there. */ Set objectsAt(PackWorld world, int chunkX, int chunkZ); + + /** + * The biomes and regions of {@code world}'s layout whose own settings make this module place the object + * {@code objectKey}. The host finds the areas where the object can appear from these: a biome counts for the areas + * it generates in and, through its children, for the areas of the biomes inside it, so a provider names only the + * layout entries that place the object themselves. Only biomes and regions the dimension can reach are named. + */ + PlacedBy placedBy(PackWorld world, String objectKey); + + /** Layout entries that place an object, named by the keys packs write ({@code land/plains}, {@code temperate}). */ + record PlacedBy(Set biomes, Set regions) { + public static final PlacedBy NOTHING = new PlacedBy(Set.of(), Set.of()); + + public PlacedBy { + biomes = Set.copyOf(Objects.requireNonNull(biomes, "biomes")); + regions = Set.copyOf(Objects.requireNonNull(regions, "regions")); + } + + public boolean isEmpty() { + return biomes.isEmpty() && regions.isEmpty(); + } + } } diff --git a/src/main/java/com/volmit/service/SaplingGrowth.java b/src/main/java/com/volmit/service/SaplingGrowth.java new file mode 100644 index 000000000..39cfa7143 --- /dev/null +++ b/src/main/java/com/volmit/service/SaplingGrowth.java @@ -0,0 +1,80 @@ +package com.volmit.service; + +import com.volmit.block.BlockState; +import com.volmit.placement.PlacedBlock; +import com.volmit.world.BlockPosition; +import com.volmit.world.PackWorld; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; + +/** + * Trees a module grows when a sapling or mushroom grows in a world generated with the pack, and which objects it + * counts as trees. The host asks every provider in order when something grows and uses the first {@link Growth}; no + * answer leaves the growth to the platform. The module decides what grows and the blocks it consists of; the host + * clears the sapling, places the blocks on the right thread and tells listeners. + */ +@Service(Providers.ALL) +public interface SaplingGrowth { + /** + * The tree that replaces the growth at {@code sapling}, or empty to leave it to the platform. Reads the world around + * the sapling through {@code surroundings}, which is only valid during the call and sees the saplings that are + * growing as air. + */ + Optional grow(PackWorld world, Sapling sapling, Surroundings surroundings); + + /** The objects of the pack this module places as trees, for tools that tell trees from other objects. */ + TreeObjects treeObjects(PackWorld world); + + /** + * What grows. + * + * @param at where the growth happened: world X and Z, Y the height above the dimension's bottom + * @param center the middle of the plane of saplings that grow together, the same way + * @param species the platform's name for the kind of tree that would grow, such as {@code TREE} or {@code JUNGLE} + */ + record Sapling(BlockPosition at, BlockPosition center, String species) { + public Sapling { + Objects.requireNonNull(at, "at"); + Objects.requireNonNull(center, "center"); + Objects.requireNonNull(species, "species"); + } + } + + /** The world around a growing sapling, read where the tree is placed. X and Z are world coordinates, Y the height above the dimension's bottom. */ + interface Surroundings { + /** The height of the topmost block at the column, ignoring fluids when {@code ignoreFluid}. */ + int highest(int x, int z, boolean ignoreFluid); + + BlockState blockAt(int x, int y, int z); + } + + /** + * The tree to place. + * + * @param object the pack object key the tree comes from, in the form packs write it + * @param blocks the blocks to place, in order, later ones over earlier ones + */ + record Growth(String object, List blocks) { + public Growth { + Objects.requireNonNull(object, "object"); + blocks = List.copyOf(blocks); + } + } + + /** + * Object keys a module places as trees. + * + * @param objects pack objects its placements mark as trees + * @param procedural the keys of the objects its procedural trees generate, one per variant + */ + record TreeObjects(Set objects, Set procedural) { + public static final TreeObjects NONE = new TreeObjects(Set.of(), Set.of()); + + public TreeObjects { + objects = Set.copyOf(objects); + procedural = Set.copyOf(procedural); + } + } +} diff --git a/src/test/java/com/volmit/ItemAndEntityValuesTest.java b/src/test/java/com/volmit/ItemAndEntityValuesTest.java new file mode 100644 index 000000000..d930ae66f --- /dev/null +++ b/src/test/java/com/volmit/ItemAndEntityValuesTest.java @@ -0,0 +1,65 @@ +package com.volmit; + +import com.volmit.entity.EntitySpec; +import com.volmit.item.ItemDrop; +import com.volmit.item.ItemEnchantment; +import com.volmit.service.BlockDrops; +import com.volmit.service.EntitySpawns; +import com.volmit.service.SaplingGrowth; +import com.volmit.world.BlockPosition; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; + +/** The values services hand the host are immutable and refuse what the host could not create. */ +class ItemAndEntityValuesTest { + @Test + void anItemDropRefusesNothingToDropAndKeepsItsListsApart() { + assertThrows(IllegalArgumentException.class, () -> ItemDrop.of("stick", 0)); + + List enchantments = new ArrayList<>(List.of(new ItemEnchantment("sharpness", 3))); + ItemDrop drop = new ItemDrop("diamond_sword", 1, null, List.of(), enchantments, List.of(), false, List.of(), null, + 0.25, null, null, Map.of(), null); + enchantments.clear(); + + assertEquals(1, drop.enchantments().size()); + assertThrows(UnsupportedOperationException.class, () -> drop.enchantments().clear()); + assertThrows(IllegalArgumentException.class, () -> new ItemEnchantment("sharpness", 0)); + } + + @Test + void anEntityKnowsWhetherItIsAnotherPluginsMob() { + EntitySpec zombie = entity("minecraft:zombie", ""); + EntitySpec special = entity("", "mythic:dragon"); + + assertFalse(zombie.isSpecial()); + assertTrue(special.isSpecial()); + } + + @Test + void anAttemptSaysWhetherLightMatters() { + BlockPosition at = new BlockPosition(1, 2, 3); + EntitySpec zombie = entity("minecraft:zombie", ""); + + assertFalse(new EntitySpawns.Attempt(at, zombie, EntitySpawns.Surface.LAND, 0, 15, true).restrictsLight()); + assertTrue(new EntitySpawns.Attempt(at, zombie, EntitySpawns.Surface.LAND, 0, 7, true).restrictsLight()); + assertTrue(new EntitySpawns.Attempt(at, zombie, EntitySpawns.Surface.LAND, 8, 15, true).restrictsLight()); + } + + @Test + void answersWithNothingAreEmpty() { + assertTrue(BlockDrops.Result.NONE.drops().isEmpty()); + assertFalse(BlockDrops.Result.NONE.replacesVanillaDrops()); + assertTrue(SaplingGrowth.TreeObjects.NONE.objects().isEmpty()); + } + + private static EntitySpec entity(String type, String specialType) { + return new EntitySpec(type, specialType, null, "", new EntitySpec.Flags(false, true, true, false, true, false, false, + false, false, false, false), EntitySpec.Equipment.NONE, List.of(), List.of(), List.of(), 0L, null, null, false, + null, null, false, List.of()); + } +} diff --git a/src/test/java/com/volmit/example/world/WorldStateExampleTest.java b/src/test/java/com/volmit/example/world/WorldStateExampleTest.java index 4fbf30f66..1671313e0 100644 --- a/src/test/java/com/volmit/example/world/WorldStateExampleTest.java +++ b/src/test/java/com/volmit/example/world/WorldStateExampleTest.java @@ -49,7 +49,17 @@ class WorldStateExampleTest { public void register(FeatureRegistry registry) { registry.registerLifecycle(this); - registry.registerService(ObjectsAt.class, RuinsModule::objectsAt); + registry.registerService(ObjectsAt.class, new ObjectsAt() { + @Override + public Set objectsAt(PackWorld world, int chunkX, int chunkZ) { + return RuinsModule.objectsAt(world, chunkX, chunkZ); + } + + @Override + public PlacedBy placedBy(PackWorld world, String objectKey) { + return PlacedBy.NOTHING; + } + }); } @Override diff --git a/src/test/java/com/volmit/support/EmptyResources.java b/src/test/java/com/volmit/support/EmptyResources.java index dc7d483eb..777685530 100644 --- a/src/test/java/com/volmit/support/EmptyResources.java +++ b/src/test/java/com/volmit/support/EmptyResources.java @@ -1,6 +1,7 @@ package com.volmit.support; import com.volmit.block.BlockRegistry; +import com.volmit.item.ItemRegistry; import com.volmit.noise.NoiseFactory; import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; @@ -28,6 +29,11 @@ public final class EmptyResources implements PackResources { throw new AssertionError("Unused blocks"); } + @Override + public ItemRegistry items() { + throw new AssertionError("Unused items"); + } + @Override public NoiseFactory noise() { throw new AssertionError("Unused noise");