diff --git a/CONTRACTS.md b/CONTRACTS.md index 2a2bf1fd4..59826f03f 100644 --- a/CONTRACTS.md +++ b/CONTRACTS.md @@ -32,8 +32,8 @@ types that carry them and lists what the Iris adapter still owes. | Noise from pack-described styles | `NoiseStyle`, `StyledRange`, `PackResources.noise()`, `NoiseFactory`, `NoiseSampler` | | Values in settings | `BlockSpec`, `PaletteSpec`, `NoiseStyle`, `StyledRange`, `Range`, `BlockPosition`, `JigsawOverrides`, `Object` as `ValueKind.AnyKind` | | Decisions over and fit of the platform's own structures | service `VanillaStructures` (`rule`, `starts`, `shift`, `reach`, `beforePieces`, `afterPieces`, `setup`, `startedStructures`, `locatableStarts`, `locateStart`, `ChunkFilter`), `VanillaStructureRule`, `VanillaStructureContext`, `VanillaStructureStart`, `VanillaStructureStartContext`, `VanillaStructureSetup`, `PlatformStart`, `StartMemo`, `StartReach`, `StructureFit` (`Start`, `Piece`, `ColumnVisitor`), `DecorationStep`, `TerrainAdaptation`, `PieceKind`, `TemplateCells`, `world.BlockAccess`, host `FeatureCatalog.registrations(service)` | -| Pack-scoped resolution | `ResourceId` (`ofPackKey`), `PackResources` (`find(kind, id)`, `require`, `ids(kind)`, `idOf`; kinds `BIOMES`, `REGIONS`, `OBJECTS`), `PackBiome`, `PackRegion` | -| Module-owned pack resources | `ResourceKind`, `FeatureRegistry.registerResourceKind`, `@ResourceRef`, host `ModuleHost.reservingFolders`, `FeatureCatalog.resourceKinds()`, `ResourceKindSchema`, `ValueKind.ResourceReferenceKind` | +| Pack-scoped resolution | `ResourceId` (`ofPackKey`, `ofPlatformKey`), `ContentKey`, `PackResources` (`find(kind, id)`, `require`, `ids(kind)`, `idOf`; kinds `BIOMES`, `REGIONS`, `OBJECTS`, `EXPRESSIONS`, `IMAGE_MAPS`), `PackBiome`, `PackRegion`, `PackExpression`, `PackImageMap` | +| Module-owned pack resources | `ResourceKind`, `FeatureRegistry.registerResourceKind`, `@Ref(kind = ...)`, host `ModuleHost.reservingFolders`, `FeatureCatalog.resourceKinds()`, `ResourceKindSchema`, `ValueKind.ResourceReferenceKind` | | 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`, `PackContext`, `FeatureRegistry.registerLifecycle`, host `FeatureCatalog.lifecycles()`, `LifecycleRunner` | @@ -222,7 +222,8 @@ running Iris is the pack publisher's responsibility. 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, + attribute or item flag) with a warning, route a `ContentKey.Provided` (and a `Registered` id of a namespace another + plugin owns) to that plugin, apply the `EntitySpec.extensions()` of the host's own types and ignore the rest, and run the checks that come with an `EntitySpawns.Attempt` (light, surface, free space) before spawning. Report how many entities appeared with `EntitySpawns.spawned`. - `AmbientEffects.due`: ask for the player's last sampled position (not every tick's), carry out an `Effect` in the order sound, particles, commands, potion, skip a part the platform lacks, and give no potion to a player who already has the @@ -230,7 +231,8 @@ running Iris is the pack publisher's responsibility. - 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 - `snippet//.json`. Complete `NOISE_STYLE`, `PACK_EXPRESSION` and `PACK_IMAGE_MAP` references; + `snippet//.json`. Complete `NOISE_STYLE` references and `@Ref(kind = ...)` of the host kinds + (`EXPRESSIONS`, `IMAGE_MAPS` among them); rendering a value type with the host's own description of the same JSON is allowed. - Serve `PackResources.noise()`: build each style's noise from the host's generators, expressions and image maps, the same values for the same style and seed, cached per pack snapshot; an unknown style name is flat, a missing diff --git a/DESIGN.md b/DESIGN.md index 779238181..c561f8f2a 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -743,7 +743,7 @@ core engine is modules as well. The host's own JSON fields are not in it; no key | `List`, `E[]` | `ListKind(E, false)` | | `Set` | `ListKind(E, true)` | | `Map` | `MapKind(V)` | -| `String` with `@ResourceRef(Type.class)` | `ResourceReferenceKind(id of the kind read into Type)` | +| `String` with `@Ref(kind = Type.class)` | `ResourceReferenceKind(id of the kind read into Type)` | | a class in a host type package, in built-in settings | `HostKind(class name)` | | `Object` | `AnyKind`: any JSON value | | any other concrete class | `ObjectKind(class name)` | @@ -776,17 +776,22 @@ adding anything a pack can write. ### References -`@Ref(Reference.X)` says what a text value names. The kinds are a closed enum of what the Iris host -can list today through its `RegistryList*` annotations: blocks, items, entities, platform biomes, -structures, potion effects and enchantments from the server registries, the host's noise styles, and -biomes, regions, objects, expressions and image maps of the pack, the resource folders Iris's own settings -refer to most. More kinds come when a -module needs one and the host can serve it. `@Ref` fits `String` and `ResourceId` and lists, sets and +`@Ref` says what a text value names, in one of two ways, and exactly one of them. `@Ref(Reference.X)` names +something of the platform: the kinds are a closed enum of what the Iris host can list today through its +`RegistryList*` annotations: blocks, items, entities, platform biomes, structures, potion effects and +enchantments from the server registries, and the host's noise styles. More come when a module needs one and the +host can serve it. `@Ref(kind = Type.class)` names a pack resource of the kind read into `Type`, the host's +(`PackBiome`, `PackRegion`, `GeneratedObject`, `PackExpression`, `PackImageMap`) or a module's, so one mechanism covers +every resource of the pack (see Module-owned pack resources). It replaced both the `PACK_*` constants of `Reference` +and a separate `@ResourceRef`: two spellings for "a resource of the pack" made a module author guess which one a kind +needed. `@Ref` fits `String` and `ResourceId` and lists, sets and arrays of them, where it applies to the elements. On any other field, a map included, it fails the -load. The pack kinds (`PACK_BIOME`, `PACK_REGION`, `PACK_OBJECT`, `PACK_EXPRESSION`, `PACK_IMAGE_MAP`, `PACK_STRUCTURE`) are +load. Pack resources are plain text in the JSON either way: packs name their biomes, regions and objects by path without a namespace, such as `desert/dunes`. On a `ResourceId` field the host reads that path as the pack's id of it (`PackResources.idOf`), and a -value with a namespace as written, so a module can hand the value straight to `PackResources.find`. `BlockState` always names a block, so its fields are block references without `@Ref`; +value with a namespace as written, so a module can hand the value straight to `PackResources.find`. A resource the +API has no type for, such as Iris's structure model, is a host extension: Iris's built-ins mark those fields with their +own annotation (`@IrisStructureRef`), and to another host they are plain text. `BlockState` always names a block, so its fields are block references without `@Ref`; `@Ref(BLOCK)` there is accepted, any other kind fails. ### Defaults @@ -992,9 +997,9 @@ the resources it serves itself. folders are reserved with `ModuleHost.reservingFolders`. Either conflict fails the pack load in `ModuleRegistry`, naming both owners; the host is named as "the host". - **Lookup.** `PackResources.find(KEEPS, id)` and `ids(KEEPS)` take the kind itself, the constant the module registered, and - return its type. The host's own kinds are constants of `PackResources` (`BIOMES`, `REGIONS`, `OBJECTS`), so one call - shape serves both, and no second key type (it used to be `ResourceKey`, a pair of id and class). One class still backs - at most one kind, because `@ResourceRef` names the kind by its class. The class must be concrete; like settings it + return its type. The host's own kinds are constants of `PackResources` (`BIOMES`, `REGIONS`, `OBJECTS`, + `EXPRESSIONS`, `IMAGE_MAPS`), so one call shape serves both, and no second key type (it used to be `ResourceKey`, a + pair of id and class). One class still backs at most one kind, because `@Ref(kind = ...)` names the kind by its class. The class must be concrete; like settings it needs a no-argument constructor, checked when the pack's description is built. - **Reading.** The host creates the instance with that constructor and reads the JSON into it, exactly as it decodes settings, so a missing field keeps its default and studio's defaults are what packs get. @@ -1006,11 +1011,11 @@ the resources it serves itself. then renders the host's own description of the class. A pack module's kind of a host type fails the load. - **Studio.** `PackSchema.resources()` lists each kind with its folder and the files' type, an `ObjectKind` described in `types()` or a `HostKind`. The host writes a schema per kind for the files below its folder. An - option that names a resource of a kind carries `@ResourceRef(Keep.class)`: a class, not a kind id, so the + option that names a resource of a kind carries `@Ref(kind = Keep.class)`: a class, not a kind id, so the reference is checked by the compiler (an annotation cannot hold the kind constant). It becomes `ResourceReferenceKind(kindId)`, and studio completes the kind's keys. Keys are pack paths without a namespace in the JSON, like the pack references of `@Ref`; the field may be a `String` or a `ResourceId`, which the - host reads as the pack's id of the key. A class that backs no kind of the pack fails the load. + host reads as the pack's id of the key. A class that backs no kind of the host or the pack fails the load. ## Validators @@ -1131,6 +1136,19 @@ from a sapling, which drops a block has. A module answers such questions through 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). +- **Platform keys are ids.** What the platform registers (items, enchantments, attributes, sounds, particles, potion + effects, loot tables, tree species) travels as a `ResourceId`, never as the text a pack wrote: a host compares and + looks up one form, and a module normalises a pack's key once (`ResourceId.ofPlatformKey`, dropping a key that cannot + be one with a warning) instead of every host guessing at case and namespace. Item and entity types are a + `ContentKey`, because another plugin's mob or item is named by a provider and a name that may hold upper case, + spaces and `:`, which no id can; `Optional` for "the other plugin's" would have lost exactly those. A + registered id of another namespace stays `Registered`, and the host routes it to the plugin that owns the namespace. + Choices with a fixed set of answers are enums (`ItemAttribute.Operation`, `DyeColor`), colours are RGB ints. +- **Groups and extensions.** `ItemDrop` and `EntitySpec` group their components by what a host does with them + (`Look`, `Wear`, `PlatformExtras`; `Appearance`, `Behaviour`, `Company`, `Drops`, `Arrival`), each with a named + default, so a reader sees a dozen meaningful parts instead of seventeen positional ones. What only one host can apply + (Iris's spawn reason, panda genes, rising out of the ground) is not an API field: the module puts a value of the host's + own type in `EntitySpec.extensions()`, the host finds it with `extension(type)`, and other hosts ignore it. `AmbientEffects` follows the same rule: the module decides which effects are due (interval and chance, kept in the world's state) and every random value they carry, the host only plays them. - **Services now.** `ObjectsAt` (`ALL`): the ids of pack objects a module would place in a chunk, predicted without diff --git a/README.md b/README.md index 9c3020fef..b1cef642a 100644 --- a/README.md +++ b/README.md @@ -238,14 +238,14 @@ PackBiome dunes = resources.require(PackResources.BIOMES, resources.idOf("desert field names. - The kind's id follows the module id. The folder is one folder name directly below the pack root; the module chooses it, so a kind that replaces one of Iris's own keeps the folder and file format packs already have. -- One folder holds one kind and one class backs one kind, which `@ResourceRef` names by its class. Two kinds +- One folder holds one kind and one class backs one kind, which `@Ref(kind = ...)` names by its class. Two kinds claiming one folder, or a folder the host reads itself (`ModuleHost.reservingFolders`), fail the pack load, naming both owners. - The host creates each resource with the class's no-argument constructor and reads the JSON into it, as it does settings, so an omitted field keeps its default. It reads a resource once per pack load and hands every caller the same instance, so resources are values nobody may change. A reload (studio hotload) reads them again. - Studio describes the files from the class like settings: `@Desc`, `@MinNumber`, `@Required` and the rest. An - option that names a resource of a kind carries `@ResourceRef(Keep.class)` on a `String` or `ResourceId`, or a + option that names a resource of a kind carries `@Ref(kind = Keep.class)` on a `String` or `ResourceId`, or a list, set or array of them, and studio completes the kind's keys. Packs write the key either way; a `ResourceId` field holds the pack's id of it. Built-in kinds may read into a class the host describes itself, as built-in settings may hold one. @@ -492,7 +492,7 @@ public final class FloraSettings implements IrisFeature { @Desc("Plants per chunk") @Required @MinNumber(0) @MaxNumber(64) private int density = 4; // default 4 - @Ref(Reference.PACK_BIOME) + @Ref(kind = PackBiome.class) private List biomes = List.of(); // completes the pack's biomes private BlockState flower = new BlockState("minecraft:poppy"); // completes blocks without @Ref @@ -517,14 +517,14 @@ public final class FloraSettings implements IrisFeature { - `@Ref(Reference.X)` says what a `String` or `ResourceId` names, also on lists, sets and arrays of them, so studio offers the right list: `BLOCK`, `ITEM`, `ENTITY`, `BIOME`, `STRUCTURE`, `STRUCTURE_PREFIX` (a structure or a family prefix such as `minecraft:village`), `STRUCTURE_SET`, `TEMPLATE_POOL` (a jigsaw template pool), - `POTION_EFFECT`, `ENCHANTMENT`, `LOOT_TABLE` or `SPECIAL_ENTITY` (a mob of another plugin) from the server's registries, `NOISE_STYLE` from the host's noise - styles, or `PACK_BIOME`, `PACK_REGION`, `PACK_OBJECT`, `PACK_EXPRESSION`, `PACK_IMAGE_MAP` or `PACK_STRUCTURE` (a jigsaw structure) of the pack. - Packs write the pack kinds in the form they always have (`desert/dunes`); on a `ResourceId` field the host reads that - as the pack's id (`resources.idOf(...)`), so the value goes straight to `PackResources.find`. `BlockState` fields name blocks without it. `@Ref` on any other field fails - the load. -- `@ResourceRef(Keep.class)` says that a `String` or `ResourceId`, or a list, set or array of them, names a resource of the - module resource kind read into that class, by its key (see Pack resources of a module). The class must back a - kind of the pack; anywhere else, or together with `@Ref`, it fails the load. + `POTION_EFFECT`, `ENCHANTMENT`, `LOOT_TABLE` or `SPECIAL_ENTITY` (a mob of another plugin) from the server's registries, or `NOISE_STYLE` from the host's noise + styles. `BlockState` fields name blocks without it. `@Ref` on any other field fails the load. +- `@Ref(kind = Keep.class)` says that a `String` or `ResourceId`, or a list, set or array of them, names a pack resource + of the kind read into that class, by its key: a host kind of `PackResources` (`PackBiome`, `PackRegion`, + `GeneratedObject`, `PackExpression`, `PackImageMap`) or a module resource kind (see Pack resources of a module). + Packs write the key in the form they always have (`desert/dunes`); on a `ResourceId` field the host reads that as + the pack's id (`resources.idOf(...)`), so the value goes straight to `PackResources.find`. A `@Ref` gives exactly + one of a `Reference` and a kind; a class no kind of the host or the pack reads into fails the load. - Packs write settings under the short `key` the feature declares, which is required: a plain JSON field name (not blank, no `:`), the same at every target: `"moss": {"amount": 0.5}`. The id (`example:moss`) stays the feature's identity in the stage graph, logs and `settings.declared(MossSettings.class)`; packs never write it. @@ -571,12 +571,21 @@ Snippet name 'patch' of com.example.flora.Patch of settings example:flora (modul ## 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. +platform. Everything the platform registers is named by a `ResourceId` (`minecraft:sharpness`); a module turns a key a +pack wrote without a namespace or in upper case into one with `ResourceId.ofPlatformKey("SMOKE")` (`minecraft:smoke`). +An item or entity type is a `ContentKey`: `Registered(id)` for one of a registry, or `Provided(provider, name)` for one +another plugin provides by a name an id cannot hold (`mythicmobs:SkeletonKing`); the host routes a registered id of +another namespace to the plugin that owns it. + +`ItemDrop` is one stack: the item, the amount, its `Look` (name, lore, custom model, leather colour as RGB, `DyeColor`), +enchantments (`ItemEnchantment`), attribute modifiers (`ItemAttribute` with an `Operation`), its `Wear` (unbreakable, +damage as a fraction of the item's durability), `PlatformExtras` (item flags and custom NBT, which only some platforms +apply) and, for debugging, its `Source`. `EntitySpec` is one entity: its type, `Appearance`, `Behaviour`, equipment +(`ItemDrop`s), attribute modifiers, `Company` (passengers, leash holder), `Drops` (loot table ids and their shuffle seed), +`Arrival` (spawn effect and console commands) and host extensions, which `extension(type)` finds: what only one host +knows how to apply travels as a value of that host's type and is ignored by the others. Modules ask the platform about +items through `resources.items()` (`ItemRegistry.maxDurability(item)`, 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 @@ -886,7 +895,8 @@ Optional clock = pack.catalog().service(Clock.class); // a Pro at its edge. - `PackResources` serves one immutable pack snapshot; caches must not survive a reload. It serves pack objects (`OBJECTS`, `GeneratedObject`), biomes (`BIOMES`, `PackBiome`), regions (`REGIONS`, - `PackRegion`) and every module resource kind: `find(kind, id)` (empty when absent), `require(kind, id)` and + `PackRegion`), expressions (`EXPRESSIONS`, `PackExpression`) and image maps (`IMAGE_MAPS`, `PackImageMap`), the last + two only as their ids, which noise styles name, and every module resource kind: `find(kind, id)` (empty when absent), `require(kind, id)` and `ids(kind)`, so `BiomeSample` ids look up directly. - Value records say "absent" with `Optional`, `OptionalInt` or `OptionalDouble` components, never with `null` or an empty string (`ItemDrop`, `EntitySpec`, `AmbientEffects.Effect`). `StructureFit.Start.key()` is a `StartKey`, an @@ -942,8 +952,9 @@ for each unsupported field type, misplaced `@Ref` (pack kinds on `ResourceId` in class, bad or repeated snippet name and pack snippet outside its module's folder, host types in built-in settings (and the load error when a pack module uses one). `PackSchemaTest` also loads a module jar with a resource kind: the kind's files described from its class, -`@ResourceRef` options as references to the kind, built-in kinds of host types, the load error for a pack kind -of a host type, for a folder two kinds claim or the host reserves, and for a misplaced `@ResourceRef`. +`@Ref(kind = ...)` options as references to the kind (host kinds included), built-in kinds of host types, the load error for a pack kind +of a host type, for a folder two kinds claim or the host reserves, for a `@Ref` that gives both or neither of a +reference and a kind, and for a misplaced `@Ref(kind = ...)`. `ModuleRegistryTest` checks kind ids, types and folders, the validator and lifecycle order, service providers in module order, the load error for a second provider of a `ONE` service and for providers of unmarked interfaces or of the wrong type. `WorldStatesTest` checks that each state is created once (also when threads race), nested creation, the diff --git a/api/src/main/java/com/volmit/config/Ref.java b/api/src/main/java/com/volmit/config/Ref.java index 6a132f423..bdac17c3a 100644 --- a/api/src/main/java/com/volmit/config/Ref.java +++ b/api/src/main/java/com/volmit/config/Ref.java @@ -2,12 +2,21 @@ package com.volmit.config; import java.lang.annotation.*; -/** Says what an option's text names, such as {@code @Ref(Reference.BLOCK) String block}. Allowed on - * {@code String} and {@link com.volmit.resource.ResourceId} options and on lists, sets and arrays of - * them, where it applies to every element. Anywhere else it fails the pack load. +/** Says what an option's text names: an entry of a platform registry, {@code @Ref(Reference.BLOCK) String block}, or + * a resource of the pack by its key, {@code @Ref(kind = LootTable.class) String table}, where {@code kind} is the type + * of a {@link com.volmit.resource.ResourceKind}: a host kind, the constants of + * {@link com.volmit.resource.PackResources}, or a kind some module of the pack registers. Studio then offers the + * registry's entries or the pack's keys of that kind. Give exactly one of the two. Allowed on {@code String} and + * {@link com.volmit.resource.ResourceId} options and on lists, sets and arrays of them, where it applies to every + * element; a {@code ResourceId} option naming a pack resource holds the id the pack gives the key it writes. + * Anything else fails the pack load. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Ref { - Reference value(); + /** The platform registry the text names; give one, or none when {@link #kind} is given. */ + Reference[] value() default {}; + + /** The type of the resource kind the text names by key; {@code void.class}, the default, when {@link #value} is given. */ + Class kind() default void.class; } diff --git a/api/src/main/java/com/volmit/config/Reference.java b/api/src/main/java/com/volmit/config/Reference.java index 7e8c42e1b..e2610d093 100644 --- a/api/src/main/java/com/volmit/config/Reference.java +++ b/api/src/main/java/com/volmit/config/Reference.java @@ -1,9 +1,9 @@ package com.volmit.config; -/** What a text option names, so studio can offer the matching completion list. Platform kinds name - * entries of the server's registries, such as {@code minecraft:stone}, including those that data - * packs and mods add. Pack kinds name resources of the pack being edited. The set is closed: every - * kind is one the Iris host can list. +/** The platform registry a text option names, so studio can offer the matching completion list: entries of the + * server's registries, such as {@code minecraft:stone}, including those that data packs and mods add, and the host's + * own noise generators. Resources of the pack are named by their kind instead, {@code @Ref(kind = ...)}. The set is + * closed: every registry is one the Iris host can list. */ public enum Reference { /** A block type, such as {@code minecraft:stone}. {@link com.volmit.block.BlockState} options are block references without {@link Ref}. */ @@ -29,20 +29,8 @@ public enum Reference { ENCHANTMENT, /** A loot table of the platform, such as {@code minecraft:chests/simple_dungeon}; not a loot table of the pack. */ LOOT_TABLE, - /** A mob of another plugin or content provider, such as {@code mythicmobs:skeleton_king}. */ + /** A mob of another plugin or content provider, such as {@code mythicmobs:SkeletonKing}; see {@link com.volmit.resource.ContentKey.Provided}. */ SPECIAL_ENTITY, - /** A biome of the pack. */ - PACK_BIOME, - /** A region of the pack. */ - PACK_REGION, - /** An object of the pack. */ - PACK_OBJECT, /** One of the host's noise styles, such as {@code SIMPLEX}; see {@link com.volmit.noise.NoiseStyle}. */ - NOISE_STYLE, - /** An expression of the pack. */ - PACK_EXPRESSION, - /** An image map of the pack. */ - PACK_IMAGE_MAP, - /** A jigsaw structure of the pack. */ - PACK_STRUCTURE + NOISE_STYLE } diff --git a/api/src/main/java/com/volmit/config/ResourceRef.java b/api/src/main/java/com/volmit/config/ResourceRef.java deleted file mode 100644 index 07bb51ad5..000000000 --- a/api/src/main/java/com/volmit/config/ResourceRef.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.volmit.config; - -import java.lang.annotation.*; - -/** Says that an option names a resource of the module resource kind read into {@code value}, by its key in the - * pack, such as {@code @ResourceRef(Pool.class) String startPool = "castle/start"}. Studio then offers the keys - * of that kind's files. Allowed on {@code String} options and lists, sets and arrays of them; the class must be - * the type of a resource kind some module of the pack registers. Anywhere else it fails the pack load. - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.FIELD) -public @interface ResourceRef { - Class value(); -} diff --git a/api/src/main/java/com/volmit/entity/EntitySpec.java b/api/src/main/java/com/volmit/entity/EntitySpec.java index 66bb11c8a..2de97d3f3 100644 --- a/api/src/main/java/com/volmit/entity/EntitySpec.java +++ b/api/src/main/java/com/volmit/entity/EntitySpec.java @@ -2,6 +2,7 @@ package com.volmit.entity; import com.volmit.item.ItemAttribute; import com.volmit.item.ItemDrop; +import com.volmit.resource.ContentKey; import com.volmit.resource.ResourceId; import java.util.List; import java.util.Objects; @@ -9,57 +10,63 @@ import java.util.Optional; /** * 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. + * what is set. A part the entity cannot have, such as equipment on an item frame, is left out. A host may leave a + * {@link ContentKey.Provided} mob as its provider set it up. * - * @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}; empty for an entity of the platform - * @param reason the platform's spawn reason by name; empty 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 the pack's 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; empty for none - * @param spawnEffect an effect to show when the entity appears; empty for none - * @param riseOutOfGround whether the entity slowly climbs out of the ground when players are near - * @param pandaMainGene for pandas the main gene by name; empty to leave it to the platform - * @param pandaHiddenGene for pandas the hidden gene by name; empty to leave it to the platform - * @param applySettingsToSpecial whether the settings also apply to a mob of another plugin - * @param commands console commands to run where the entity appears + * @param type what the entity is: an entity type, such as {@code minecraft:zombie}, or a mob of a provider + * @param appearance how it looks + * @param behaviour how it acts + * @param equipment what it wears and holds + * @param attributes attribute modifiers to apply + * @param company the entities that come with it + * @param drops what it drops when it dies + * @param arrival what happens where it appears + * @param extensions values for a particular host, which other hosts ignore; see {@link #extension} */ -public record EntitySpec(Optional type, Optional specialType, Optional reason, Optional customName, - Flags flags, Equipment equipment, List passengers, List attributes, - List lootTables, long lootShuffleSeed, Optional leashHolder, - Optional spawnEffect, boolean riseOutOfGround, Optional pandaMainGene, - Optional pandaHiddenGene, boolean applySettingsToSpecial, List commands) { +public record EntitySpec(ContentKey type, Appearance appearance, Behaviour behaviour, Equipment equipment, + List attributes, Company company, Drops drops, Arrival arrival, List extensions) { public EntitySpec { Objects.requireNonNull(type, "type"); - Objects.requireNonNull(specialType, "specialType"); - Objects.requireNonNull(reason, "reason"); - Objects.requireNonNull(customName, "customName"); - Objects.requireNonNull(flags, "flags"); + Objects.requireNonNull(appearance, "appearance"); + Objects.requireNonNull(behaviour, "behaviour"); Objects.requireNonNull(equipment, "equipment"); - passengers = List.copyOf(passengers); attributes = List.copyOf(attributes); - lootTables = List.copyOf(lootTables); - Objects.requireNonNull(leashHolder, "leashHolder"); - Objects.requireNonNull(spawnEffect, "spawnEffect"); - Objects.requireNonNull(pandaMainGene, "pandaMainGene"); - Objects.requireNonNull(pandaHiddenGene, "pandaHiddenGene"); - commands = List.copyOf(commands); + Objects.requireNonNull(company, "company"); + Objects.requireNonNull(drops, "drops"); + Objects.requireNonNull(arrival, "arrival"); + extensions = List.copyOf(extensions); } - /** Whether the entity is a mob of another plugin. */ - public boolean isSpecial() { - return specialType.isPresent(); + /** The extension of type {@code type} the module added for its host; empty when it added none. */ + public Optional extension(Class type) { + return extensions.stream().filter(type::isInstance).map(type::cast).findFirst(); } - /** 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) { + /** + * How the entity looks. + * + * @param customName the name shown above the entity, as authored in the pack with {@code &} colour codes; empty for none + * @param nameVisible whether the name shows even when nobody looks at the entity + */ + public record Appearance(Optional customName, boolean nameVisible, boolean glowing, boolean baby) { + public static final Appearance PLAIN = new Appearance(Optional.empty(), false, false, false); + + public Appearance { + Objects.requireNonNull(customName, "customName"); + } + } + + /** + * How the entity acts; the host applies what the entity's kind has. + * + * @param aware whether a mob notices its surroundings + * @param ai whether a mob follows its goals + * @param removable whether the entity despawns when far from players + * @param keepEntity whether the entity is never culled + */ + public record Behaviour(boolean aware, boolean ai, boolean gravity, boolean invulnerable, boolean silent, + boolean pickupItems, boolean removable, boolean keepEntity) { + public static final Behaviour NATURAL = new Behaviour(true, true, true, false, false, false, false, false); } /** The items an entity wears and holds; empty for an empty slot. */ @@ -79,18 +86,88 @@ public record EntitySpec(Optional type, Optional specialType, Op } /** - * 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. + * The entities that come with this one. * - * @param sound the platform's sound key; empty for no sound - * @param particle the platform's particle key; empty for no particles + * @param passengers entities that ride this one + * @param leashHolder the entity that holds this one on a leash; empty for none */ - public record SpawnEffect(Optional sound, int soundDistance, double minPitch, double maxPitch, double volume, - Optional particle, int particleOffset, int particleCount, double altX, double altY, - double altZ, boolean randomAltX, boolean randomAltY, boolean randomAltZ, double extra) { + public record Company(List passengers, Optional leashHolder) { + public static final Company NONE = new Company(List.of(), Optional.empty()); + + public Company { + passengers = List.copyOf(passengers); + Objects.requireNonNull(leashHolder, "leashHolder"); + } + } + + /** + * What the entity drops when it dies. + * + * @param lootTables the pack's loot tables it drops instead of the platform's drops; none keeps the platform's + * @param shuffleSeed seeds how the drops of {@code lootTables} are shuffled + */ + public record Drops(List lootTables, long shuffleSeed) { + public static final Drops PLATFORM = new Drops(List.of(), 0L); + + public Drops { + lootTables = List.copyOf(lootTables); + } + } + + /** + * What happens where the entity appears. + * + * @param effect an effect to show; empty for none + * @param commands console commands to run + */ + public record Arrival(Optional effect, List commands) { + public static final Arrival QUIET = new Arrival(Optional.empty(), List.of()); + + public Arrival { + Objects.requireNonNull(effect, "effect"); + commands = List.copyOf(commands); + } + } + + /** + * Sound and particles shown around an entity that appears. The host makes the random choices: where in range the + * sound plays, its pitch, and the particles' random motion. + */ + public record SpawnEffect(Optional sound, Optional particles) { public SpawnEffect { Objects.requireNonNull(sound, "sound"); - Objects.requireNonNull(particle, "particle"); + Objects.requireNonNull(particles, "particles"); + } + + /** + * A sound played near the entity, at a pitch between {@code minPitch} and {@code maxPitch}. + * + * @param key the sound, such as {@code minecraft:entity.zombie.ambient} + * @param distance how many blocks from the entity, at most, along each axis it seems to come from + */ + public record Sound(ResourceId key, int distance, double minPitch, double maxPitch, double volume) { + public Sound { + Objects.requireNonNull(key, "key"); + } + } + + /** + * Particles shown around the entity. + * + * @param key the particle, such as {@code minecraft:smoke} + * @param offset how many blocks up, at most, they appear + * @param count how many particles; none makes {@code motion} their motion + * @param extra an extra value some particles take; 0 for none + */ + public record Burst(ResourceId key, int offset, int count, Motion motion, double extra) { + public Burst { + Objects.requireNonNull(key, "key"); + Objects.requireNonNull(motion, "motion"); + } + } + + /** How far the particles spread or move along each axis; a random axis takes a random amount between minus and plus its value. */ + public record Motion(double x, double y, double z, boolean randomX, boolean randomY, boolean randomZ) { } } diff --git a/api/src/main/java/com/volmit/item/DyeColor.java b/api/src/main/java/com/volmit/item/DyeColor.java new file mode 100644 index 000000000..67f00cc12 --- /dev/null +++ b/api/src/main/java/com/volmit/item/DyeColor.java @@ -0,0 +1,21 @@ +package com.volmit.item; + +/** The sixteen dye colours, which colour items such as shulker boxes, banners and beds. */ +public enum DyeColor { + WHITE, + ORANGE, + MAGENTA, + LIGHT_BLUE, + YELLOW, + LIME, + PINK, + GRAY, + LIGHT_GRAY, + CYAN, + PURPLE, + BLUE, + BROWN, + GREEN, + RED, + BLACK +} diff --git a/api/src/main/java/com/volmit/item/ItemAttribute.java b/api/src/main/java/com/volmit/item/ItemAttribute.java index cf1c45404..ccd0a7247 100644 --- a/api/src/main/java/com/volmit/item/ItemAttribute.java +++ b/api/src/main/java/com/volmit/item/ItemAttribute.java @@ -1,18 +1,28 @@ package com.volmit.item; +import com.volmit.resource.ResourceId; 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 attribute the attribute, such as {@code minecraft:max_health} * @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 record ItemAttribute(ResourceId attribute, String name, Operation operation, double amount) { public ItemAttribute { Objects.requireNonNull(attribute, "attribute"); Objects.requireNonNull(name, "name"); Objects.requireNonNull(operation, "operation"); } + + /** How the amount changes the attribute's value, as the platform's attribute modifiers do. */ + public enum Operation { + /** Adds the amount to the base value. */ + ADD_VALUE, + /** Adds the base value times the amount. */ + ADD_MULTIPLIED_BASE, + /** Multiplies the value, after the other modifiers, by one plus the amount. */ + ADD_MULTIPLIED_TOTAL + } } diff --git a/api/src/main/java/com/volmit/item/ItemDrop.java b/api/src/main/java/com/volmit/item/ItemDrop.java index eec46314c..443f90151 100644 --- a/api/src/main/java/com/volmit/item/ItemDrop.java +++ b/api/src/main/java/com/volmit/item/ItemDrop.java @@ -1,5 +1,6 @@ package com.volmit.item; +import com.volmit.resource.ContentKey; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; @@ -11,48 +12,86 @@ import java.util.OptionalInt; /** * 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. + * after the module made every random choice. The host creates the stack on the platform; a part the item cannot have, + * such as a leather colour on a sword, is left out. * - * @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; empty keeps 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; empty for none - * @param damage the fraction of the item's durability already used, 0 to 1; empty leaves it undamaged - * @param leatherColor colour of leather armour as {@code #rrggbb}; empty for none - * @param dyeColor dye colour name; empty for none - * @param customNbt custom data the platform stores on the item, or an empty map - * @param source where the item came from, present only when the host asked for it to be shown (debug loot) + * @param item what the item is + * @param amount how many, at least 1 + * @param look its name, lore and colours + * @param enchantments applied in order + * @param attributes attribute modifiers applied in order + * @param wear how worn it is + * @param extras what only some platforms understand + * @param source where the item came from, present only when the host asked for it to be shown (debug loot) */ -public record ItemDrop(String item, int amount, Optional displayName, List lore, List enchantments, - List attributes, boolean unbreakable, List flags, OptionalInt customModel, - OptionalDouble damage, Optional leatherColor, Optional dyeColor, Map customNbt, - Optional source) { +public record ItemDrop(ContentKey item, int amount, Look look, List enchantments, + List attributes, Wear wear, PlatformExtras extras, Optional source) { public ItemDrop { Objects.requireNonNull(item, "item"); if (amount < 1) throw new IllegalArgumentException("Item amount must be at least 1: " + amount); - Objects.requireNonNull(displayName, "displayName"); - lore = List.copyOf(lore); + Objects.requireNonNull(look, "look"); enchantments = List.copyOf(enchantments); attributes = List.copyOf(attributes); - flags = List.copyOf(flags); - Objects.requireNonNull(customModel, "customModel"); - Objects.requireNonNull(damage, "damage"); - Objects.requireNonNull(leatherColor, "leatherColor"); - Objects.requireNonNull(dyeColor, "dyeColor"); - customNbt = Collections.unmodifiableMap(new LinkedHashMap<>(customNbt)); + Objects.requireNonNull(wear, "wear"); + Objects.requireNonNull(extras, "extras"); Objects.requireNonNull(source, "source"); } /** {@code amount} items of kind {@code item} and nothing else. */ - public static ItemDrop of(String item, int amount) { - return new ItemDrop(item, amount, Optional.empty(), List.of(), List.of(), List.of(), false, List.of(), OptionalInt.empty(), - OptionalDouble.empty(), Optional.empty(), Optional.empty(), Map.of(), Optional.empty()); + public static ItemDrop of(ContentKey item, int amount) { + return new ItemDrop(item, amount, Look.PLAIN, List.of(), List.of(), Wear.NEW, PlatformExtras.NONE, Optional.empty()); + } + + /** + * How the item looks. Names and lore are as authored in the pack, with {@code &} colour codes; the host translates + * and wraps them. + * + * @param displayName the item's name; empty keeps the platform's + * @param lore lines of text under the name + * @param customModel custom model number; empty for none + * @param leatherColor colour of leather armour as {@code 0xRRGGBB}; empty for none + * @param dyeColor the dye colour of an item that takes one; empty for none + */ + public record Look(Optional displayName, List lore, OptionalInt customModel, OptionalInt leatherColor, + Optional dyeColor) { + public static final Look PLAIN = new Look(Optional.empty(), List.of(), OptionalInt.empty(), OptionalInt.empty(), Optional.empty()); + + public Look { + Objects.requireNonNull(displayName, "displayName"); + lore = List.copyOf(lore); + Objects.requireNonNull(customModel, "customModel"); + Objects.requireNonNull(leatherColor, "leatherColor"); + Objects.requireNonNull(dyeColor, "dyeColor"); + } + } + + /** + * How worn the item is. + * + * @param unbreakable whether the item never breaks + * @param damage the fraction of the item's durability already used, 0 to 1; empty leaves it undamaged + */ + public record Wear(boolean unbreakable, OptionalDouble damage) { + public static final Wear NEW = new Wear(false, OptionalDouble.empty()); + + public Wear { + Objects.requireNonNull(damage, "damage"); + } + } + + /** + * What only some platforms understand; a platform without them ignores them. + * + * @param flags the platform's item flags to set, by name; names the platform lacks are ignored + * @param customNbt custom data the platform stores on the item, or an empty map + */ + public record PlatformExtras(List flags, Map customNbt) { + public static final PlatformExtras NONE = new PlatformExtras(List.of(), Map.of()); + + public PlatformExtras { + flags = List.copyOf(flags); + customNbt = Collections.unmodifiableMap(new LinkedHashMap<>(customNbt)); + } } /** diff --git a/api/src/main/java/com/volmit/item/ItemEnchantment.java b/api/src/main/java/com/volmit/item/ItemEnchantment.java index e1de9d3d7..59ea61185 100644 --- a/api/src/main/java/com/volmit/item/ItemEnchantment.java +++ b/api/src/main/java/com/volmit/item/ItemEnchantment.java @@ -1,11 +1,12 @@ package com.volmit.item; +import com.volmit.resource.ResourceId; 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. +/** An enchantment of an {@link ItemDrop}, such as {@code minecraft:sharpness} or {@code mymod:vorpal}, with the level + * the module decided. */ -public record ItemEnchantment(String key, int level) { +public record ItemEnchantment(ResourceId 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/api/src/main/java/com/volmit/item/ItemRegistry.java b/api/src/main/java/com/volmit/item/ItemRegistry.java index 7a83e573e..2d5cc8f5f 100644 --- a/api/src/main/java/com/volmit/item/ItemRegistry.java +++ b/api/src/main/java/com/volmit/item/ItemRegistry.java @@ -1,15 +1,15 @@ package com.volmit.item; +import com.volmit.resource.ContentKey; 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. +/** What a module may ask the platform about items, so that its decisions follow the item they concern. 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}. + * item is known by {@code item}. */ - OptionalInt maxDurability(String key); + OptionalInt maxDurability(ContentKey item); } diff --git a/api/src/main/java/com/volmit/noise/NoiseStyle.java b/api/src/main/java/com/volmit/noise/NoiseStyle.java index e19f818ef..d45fc9eda 100644 --- a/api/src/main/java/com/volmit/noise/NoiseStyle.java +++ b/api/src/main/java/com/volmit/noise/NoiseStyle.java @@ -6,6 +6,8 @@ import com.volmit.config.MinNumber; import com.volmit.config.Ref; import com.volmit.config.Reference; import com.volmit.config.Snippet; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; import java.util.Objects; import java.util.Optional; @@ -37,13 +39,13 @@ public final class NoiseStyle { @Desc("The zoom of this style") private double zoom = 1; - @Ref(Reference.PACK_EXPRESSION) + @Ref(kind = PackExpression.class) @Desc("Instead of using the style property, use a custom expression to represent this style.") - private String expression; + private ResourceId expression; - @Ref(Reference.PACK_IMAGE_MAP) + @Ref(kind = PackImageMap.class) @Desc("Use an Image map instead of a generated value") - private String imageMap; + private ResourceId imageMap; @MinNumber(0.00001) @Desc("The Output multiplier. Only used if parent is fracture.") @@ -109,13 +111,13 @@ public final class NoiseStyle { return zoom; } - /** The key of the pack expression that replaces the base style. */ - public Optional expression() { + /** The pack expression that replaces the base style, by the id the pack gives its key; see {@link PackResources#EXPRESSIONS}. */ + public Optional expression() { return Optional.ofNullable(expression); } - /** The key of the pack image map that replaces the base style when there is no expression. */ - public Optional imageMap() { + /** The pack image map that replaces the base style when there is no expression; see {@link PackResources#IMAGE_MAPS}. */ + public Optional imageMap() { return Optional.ofNullable(imageMap); } diff --git a/api/src/main/java/com/volmit/noise/PackExpression.java b/api/src/main/java/com/volmit/noise/PackExpression.java new file mode 100644 index 000000000..9d8197c84 --- /dev/null +++ b/api/src/main/java/com/volmit/noise/PackExpression.java @@ -0,0 +1,14 @@ +package com.volmit.noise; + +import com.volmit.resource.ResourceId; +import java.util.Objects; + +/** An expression of the loaded pack, which a {@link NoiseStyle} can use instead of a base style. The host compiles it + * and builds its noise ({@link NoiseFactory}); a module only names it, and can see that the pack has it through + * {@code PackResources.find(PackResources.EXPRESSIONS, id)}. + */ +public record PackExpression(ResourceId id) { + public PackExpression { + Objects.requireNonNull(id, "id"); + } +} diff --git a/api/src/main/java/com/volmit/noise/PackImageMap.java b/api/src/main/java/com/volmit/noise/PackImageMap.java new file mode 100644 index 000000000..38067303b --- /dev/null +++ b/api/src/main/java/com/volmit/noise/PackImageMap.java @@ -0,0 +1,14 @@ +package com.volmit.noise; + +import com.volmit.resource.ResourceId; +import java.util.Objects; + +/** An image map of the loaded pack, which a {@link NoiseStyle} can use instead of a base style. The host reads the + * image and builds its noise ({@link NoiseFactory}); a module only names it, and can see that the pack has it through + * {@code PackResources.find(PackResources.IMAGE_MAPS, id)}. + */ +public record PackImageMap(ResourceId id) { + public PackImageMap { + Objects.requireNonNull(id, "id"); + } +} diff --git a/api/src/main/java/com/volmit/resource/ContentKey.java b/api/src/main/java/com/volmit/resource/ContentKey.java new file mode 100644 index 000000000..823113655 --- /dev/null +++ b/api/src/main/java/com/volmit/resource/ContentKey.java @@ -0,0 +1,45 @@ +package com.volmit.resource; + +import java.util.Objects; + +/** + * What an item or entity a module hands the host is: a registered type by its {@link ResourceId}, or a mob or item of a + * content provider by the provider's own name for it. Provider names are kept as written because providers tell their + * content apart by case ({@code mythicmobs:SkeletonKing}, {@code mmoitems_SWORD:EXCALIBUR}), which no + * {@code ResourceId} can hold. + */ +public sealed interface ContentKey permits ContentKey.Registered, ContentKey.Provided { + /** + * A type in the platform's registries, such as {@code minecraft:diamond_sword}, or one the host routes by its + * namespace to the provider that owns it, such as {@code itemsadder:ruby}; the host decides which. + */ + record Registered(ResourceId id) implements ContentKey { + public Registered { + Objects.requireNonNull(id, "id"); + } + + @Override + public String toString() { + return id.toString(); + } + } + + /** + * A mob or item of a content provider: the provider, such as {@code mythicmobs}, and its name for the content, which + * may hold any character, {@code :} included. + */ + record Provided(String provider, String name) implements ContentKey { + public Provided { + Objects.requireNonNull(provider, "provider"); + Objects.requireNonNull(name, "name"); + if (provider.isBlank() || name.isBlank()) { + throw new IllegalArgumentException("A provided key needs a provider and a name: " + provider + ":" + name); + } + } + + @Override + public String toString() { + return provider + ":" + name; + } + } +} diff --git a/api/src/main/java/com/volmit/resource/PackResources.java b/api/src/main/java/com/volmit/resource/PackResources.java index c388df0c4..319dc8aa9 100644 --- a/api/src/main/java/com/volmit/resource/PackResources.java +++ b/api/src/main/java/com/volmit/resource/PackResources.java @@ -3,6 +3,8 @@ package com.volmit.resource; import com.volmit.block.BlockRegistry; import com.volmit.item.ItemRegistry; import com.volmit.noise.NoiseFactory; +import com.volmit.noise.PackExpression; +import com.volmit.noise.PackImageMap; import com.volmit.object.GeneratedObject; import com.volmit.world.PackBiome; import com.volmit.world.PackRegion; @@ -14,8 +16,8 @@ import java.util.UUID; /** Immutable view of one loaded pack snapshot, safe for concurrent reads. * Reload produces a different snapshotId, even for the same pack. Resources must be immutable * or explicitly thread-safe. A resource is named by its kind and its id, so one id can name - * both a biome and a region. Hosts serve the kinds {@link #BIOMES}, {@link #REGIONS} and {@link #OBJECTS} - * and every {@link ResourceKind} the pack's modules register; an id the pack lacks for that kind returns empty, + * both a biome and a region. Hosts serve the kinds {@link #BIOMES}, {@link #REGIONS}, {@link #OBJECTS}, + * {@link #EXPRESSIONS} and {@link #IMAGE_MAPS} and every {@link ResourceKind} the pack's modules register; an id the pack lacks for that kind returns empty, * and a kind the host does not serve throws IllegalArgumentException. Broken resources fail loading rather than * appearing absent. The host owns resolution, imports, native handles and caches; no filesystem paths escape. */ @@ -29,6 +31,12 @@ public interface PackResources { /** The pack's objects as geometry, as the host reads them from its own folder. */ ResourceKind OBJECTS = ResourceKind.of("host:object", "objects", GeneratedObject.class); + /** The pack's expressions, which noise styles use; the host compiles them from its own folder. */ + ResourceKind EXPRESSIONS = ResourceKind.of("host:expression", "expressions", PackExpression.class); + + /** The pack's image maps, which noise styles use; the host reads them from its own folder. */ + ResourceKind IMAGE_MAPS = ResourceKind.of("host:image-map", "image-maps", PackImageMap.class); + ResourceId packId(); UUID snapshotId(); BlockRegistry blocks(); @@ -49,7 +57,7 @@ public interface PackResources { /** The id of the resource the pack's files name by {@code key} (the file path inside the kind's folder, without * {@code .json}), such as {@code overworld:dungeon/chest} for {@code dungeon/chest}; see - * {@link ResourceId#ofPackKey}. Settings that name a resource, such as a {@link com.volmit.config.ResourceRef}, or a + * {@link ResourceId#ofPackKey}. Settings that name a resource in a {@code String}, such as a {@link com.volmit.config.Ref} option, or a * biome's key in a region, hold such a key. Characters an id cannot hold are replaced the way the host does for its * own ids, so use this and not {@code new ResourceId(packId().namespace(), key)}. */ diff --git a/api/src/main/java/com/volmit/resource/ResourceId.java b/api/src/main/java/com/volmit/resource/ResourceId.java index 4b1ff3665..68198b8f3 100644 --- a/api/src/main/java/com/volmit/resource/ResourceId.java +++ b/api/src/main/java/com/volmit/resource/ResourceId.java @@ -4,12 +4,14 @@ import java.util.Locale; import java.util.Objects; import java.util.regex.Pattern; -/** Case-sensitive namespaced identity. Parsing never supplies an implicit namespace. */ +/** Case-sensitive namespaced identity. {@link #parse} never supplies an implicit namespace; {@link #ofPackKey} and + * {@link #ofPlatformKey} turn the keys packs write into ids. */ public record ResourceId(String namespace, String path) implements Comparable { private static final Pattern NAMESPACE = Pattern.compile("[a-z0-9_.-]+"); private static final Pattern PATH = Pattern.compile("[a-z0-9_./-]+"); private static final Pattern NOT_PATH = Pattern.compile("[^a-z0-9_./-]"); private static final String PATH_REPLACEMENT = "_"; + private static final String PLATFORM_NAMESPACE = "minecraft"; public ResourceId { Objects.requireNonNull(namespace, "namespace"); @@ -42,6 +44,17 @@ public record ResourceId(String namespace, String path) implements Comparable entity(PackWorld world, ResourceId entity); - /** What a marker in the world means for spawning; empty for a marker this module does not know. */ - Optional marker(PackWorld world, String tag); + /** + * What a marker in the world means for spawning; empty for a marker this module does not know. A marker's tag is a + * key of the pack, as an object's marker block names it, and {@code tag} the id the pack gives it + * ({@link com.volmit.resource.PackResources#idOf}). + */ + Optional marker(PackWorld world, ResourceId tag); /** Where entities may spawn. */ sealed interface Site permits Chunk, Marker { @@ -46,11 +50,11 @@ public interface EntitySpawns { * 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 marker the id of the marker's tag, as {@link EntitySpawns#marker} takes it * @param spawner the pack's 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, ResourceId spawner, boolean initial) implements Site { + record Marker(BlockPosition position, ResourceId marker, ResourceId spawner, boolean initial) implements Site { public Marker { Objects.requireNonNull(position, "position"); Objects.requireNonNull(marker, "marker"); diff --git a/api/src/main/java/com/volmit/service/Loot.java b/api/src/main/java/com/volmit/service/Loot.java index 2809c1488..79c16728e 100644 --- a/api/src/main/java/com/volmit/service/Loot.java +++ b/api/src/main/java/com/volmit/service/Loot.java @@ -59,9 +59,9 @@ public interface Loot { * 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 { + record PlatformTable(ResourceId table, long seed) implements Source { public PlatformTable { - Objects.requireNonNull(key, "key"); + Objects.requireNonNull(table, "table"); } } } diff --git a/api/src/main/java/com/volmit/service/SaplingGrowth.java b/api/src/main/java/com/volmit/service/SaplingGrowth.java index 6a2205f5b..2fe0fa00d 100644 --- a/api/src/main/java/com/volmit/service/SaplingGrowth.java +++ b/api/src/main/java/com/volmit/service/SaplingGrowth.java @@ -33,9 +33,10 @@ public interface SaplingGrowth { * * @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} + * @param species the kind of tree that would grow, as the platform names it, such as {@code minecraft:tree} or + * {@code minecraft:jungle} (Bukkit's tree types, lower-cased) */ - record Sapling(BlockPosition at, BlockPosition center, String species) { + record Sapling(BlockPosition at, BlockPosition center, ResourceId species) { public Sapling { Objects.requireNonNull(at, "at"); Objects.requireNonNull(center, "center"); diff --git a/api/src/main/java/com/volmit/vanilla/JigsawOverrides.java b/api/src/main/java/com/volmit/vanilla/JigsawOverrides.java index 31a366cc1..4cf126114 100644 --- a/api/src/main/java/com/volmit/vanilla/JigsawOverrides.java +++ b/api/src/main/java/com/volmit/vanilla/JigsawOverrides.java @@ -5,6 +5,7 @@ import com.volmit.config.Ref; import com.volmit.config.Reference; import com.volmit.config.MaxNumber; import com.volmit.config.MinNumber; +import com.volmit.resource.ResourceId; import java.util.Objects; import java.util.Optional; import java.util.OptionalInt; @@ -16,8 +17,8 @@ import java.util.OptionalInt; */ @Desc("Optional overrides applied to a live vanilla, datapack, or modded jigsaw definition before Minecraft assembles it. Omitted values preserve the registered source definition.") public final class JigsawOverrides { - /** Removes the definition's start connector constraint when given as {@link #startJigsawName()}. */ - public static final String NO_START_JIGSAW = "NONE"; + /** What packs write as the start connector to remove the definition's constraint. */ + private static final String NO_START_JIGSAW = "NONE"; /** Whether the start piece follows one of the platform's heightmaps. */ @Desc("Controls whether a configured native jigsaw projects its start onto a Minecraft heightmap.") @@ -114,16 +115,23 @@ public final class JigsawOverrides { } /** These overrides, starting from the template pool {@code pool}, such as {@code minecraft:village/plains/town_centers}. */ - public JigsawOverrides withStartPool(String pool) { + public JigsawOverrides withStartPool(ResourceId pool) { JigsawOverrides overrides = new JigsawOverrides(this); - overrides.startPool = Objects.requireNonNull(pool, "pool"); + overrides.startPool = pool.toString(); return overrides; } - /** These overrides, starting from the connector {@code name}; {@link #NO_START_JIGSAW} removes the constraint. */ - public JigsawOverrides withStartJigsawName(String name) { + /** These overrides, starting from the connector {@code name}. */ + public JigsawOverrides withStartJigsawName(ResourceId name) { JigsawOverrides overrides = new JigsawOverrides(this); - overrides.startJigsawName = Objects.requireNonNull(name, "name"); + overrides.startJigsawName = name.toString(); + return overrides; + } + + /** These overrides, without the definition's start connector constraint. */ + public JigsawOverrides withoutStartJigsaw() { + JigsawOverrides overrides = new JigsawOverrides(this); + overrides.startJigsawName = NO_START_JIGSAW; return overrides; } @@ -167,14 +175,23 @@ public final class JigsawOverrides { return overrides; } - /** The template pool to start from; empty keeps the definition's. */ - public String startPool() { - return startPool == null ? "" : startPool; + /** The template pool to start from, such as {@code minecraft:village/plains/town_centers}; empty keeps the definition's. */ + public Optional startPool() { + return platformKey(startPool); } - /** The start connector; empty keeps the definition's, {@link #NO_START_JIGSAW} removes it. */ - public String startJigsawName() { - return startJigsawName == null ? "" : startJigsawName; + /** The start connector; empty keeps the definition's, unless {@link #removesStartJigsaw()}. */ + public Optional startJigsawName() { + return removesStartJigsaw() ? Optional.empty() : platformKey(startJigsawName); + } + + /** Whether the start connector constraint is removed, which packs write as {@code NONE}. */ + public boolean removesStartJigsaw() { + return startJigsawName != null && NO_START_JIGSAW.equalsIgnoreCase(startJigsawName.trim()); + } + + private static Optional platformKey(String key) { + return key == null || key.isBlank() ? Optional.empty() : Optional.of(ResourceId.ofPlatformKey(key)); } public OptionalInt maxDepth() { @@ -217,8 +234,8 @@ public final class JigsawOverrides { @Override public boolean equals(Object other) { - return other instanceof JigsawOverrides that && startPool().equals(that.startPool()) - && startJigsawName().equals(that.startJigsawName()) && Objects.equals(maxDepth, that.maxDepth) + return other instanceof JigsawOverrides that && written(startPool).equals(written(that.startPool)) + && written(startJigsawName).equals(written(that.startJigsawName)) && Objects.equals(maxDepth, that.maxDepth) && Objects.equals(maxDistanceHorizontal, that.maxDistanceHorizontal) && Objects.equals(maxDistanceVertical, that.maxDistanceVertical) && Objects.equals(useExpansionHack, that.useExpansionHack) @@ -230,12 +247,17 @@ public final class JigsawOverrides { @Override public int hashCode() { - return Objects.hash(startPool(), startJigsawName(), maxDepth, maxDistanceHorizontal, maxDistanceVertical, + return Objects.hash(written(startPool), written(startJigsawName), maxDepth, maxDistanceHorizontal, maxDistanceVertical, useExpansionHack, projectStartToHeightmap(), dimensionPaddingBottom, dimensionPaddingTop, liquidSettings()); } @Override public String toString() { - return "JigsawOverrides[pool '" + startPool() + "', depth " + maxDepth + ", " + projectStartToHeightmap() + "]"; + return "JigsawOverrides[pool '" + written(startPool) + "', depth " + maxDepth + ", " + projectStartToHeightmap() + "]"; + } + + /** A key as the pack wrote it, without surrounding blanks; empty when it wrote none. */ + private static String written(String key) { + return key == null ? "" : key.trim(); } } diff --git a/api/src/main/java/com/volmit/world/UpperDimension.java b/api/src/main/java/com/volmit/world/UpperDimension.java index 5174e139a..ec362e813 100644 --- a/api/src/main/java/com/volmit/world/UpperDimension.java +++ b/api/src/main/java/com/volmit/world/UpperDimension.java @@ -3,6 +3,7 @@ package com.volmit.world; import com.volmit.block.BlockState; import com.volmit.config.FeatureSettings; import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; import java.util.Optional; /** The dimension stacked above the one being generated, whose ground hangs from the top of this one's volume. It may be @@ -14,8 +15,8 @@ public interface UpperDimension { /** Whether the dimension above is this very dimension, stacked on itself. */ boolean isThisDimension(); - /** The key the pack knows the dimension by, such as {@code overworld}: what its noise seeds derive from. */ - String key(); + /** The id its pack gives the dimension's key, such as {@code overworld:overworld}: what its noise seeds derive from. */ + ResourceId id(); /** The settings of the upper dimension: its dimension, and the region and surface biome it has at the column. */ FeatureSettings settings(); diff --git a/api/src/test/java/com/volmit/ItemAndEntityValuesTest.java b/api/src/test/java/com/volmit/ItemAndEntityValuesTest.java index 0f7266de4..03712b3af 100644 --- a/api/src/test/java/com/volmit/ItemAndEntityValuesTest.java +++ b/api/src/test/java/com/volmit/ItemAndEntityValuesTest.java @@ -4,6 +4,8 @@ import com.volmit.entity.EntitySpec; import com.volmit.geometry.BlockPosition; import com.volmit.item.ItemDrop; import com.volmit.item.ItemEnchantment; +import com.volmit.resource.ContentKey; +import com.volmit.resource.ResourceId; import com.volmit.service.AmbientEffects; import com.volmit.service.BlockDrops; import com.volmit.service.EntitySpawns; @@ -12,55 +14,71 @@ import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; -import java.util.Map; import java.util.Optional; import java.util.OptionalDouble; -import java.util.OptionalInt; 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 { + private static final ContentKey STICK = new ContentKey.Registered(ResourceId.parse("minecraft:stick")); + private static final ResourceId SHARPNESS = ResourceId.parse("minecraft:sharpness"); + @Test void anItemDropRefusesNothingToDropAndKeepsItsListsApart() { - assertThrows(IllegalArgumentException.class, () -> ItemDrop.of("stick", 0)); + assertThrows(IllegalArgumentException.class, () -> ItemDrop.of(STICK, 0)); - List enchantments = new ArrayList<>(List.of(new ItemEnchantment("sharpness", 3))); - ItemDrop drop = new ItemDrop("diamond_sword", 1, Optional.empty(), List.of(), enchantments, List.of(), false, List.of(), - OptionalInt.empty(), OptionalDouble.of(0.25), Optional.empty(), Optional.empty(), Map.of(), Optional.empty()); + List enchantments = new ArrayList<>(List.of(new ItemEnchantment(SHARPNESS, 3))); + ItemDrop drop = new ItemDrop(STICK, 1, ItemDrop.Look.PLAIN, enchantments, List.of(), + new ItemDrop.Wear(false, OptionalDouble.of(0.25)), ItemDrop.PlatformExtras.NONE, Optional.empty()); enchantments.clear(); assertEquals(1, drop.enchantments().size()); assertThrows(UnsupportedOperationException.class, () -> drop.enchantments().clear()); - assertThrows(IllegalArgumentException.class, () -> new ItemEnchantment("sharpness", 0)); + assertThrows(IllegalArgumentException.class, () -> new ItemEnchantment(SHARPNESS, 0)); } @Test void absentValuesAreEmptyNeverNull() { - ItemDrop stick = ItemDrop.of("stick", 1); + ItemDrop stick = ItemDrop.of(STICK, 1); - assertTrue(stick.displayName().isEmpty()); - assertTrue(stick.damage().isEmpty()); + assertTrue(stick.look().displayName().isEmpty()); + assertTrue(stick.wear().damage().isEmpty()); assertTrue(stick.source().isEmpty()); - assertThrows(NullPointerException.class, () -> new ItemDrop("stick", 1, null, List.of(), List.of(), List.of(), false, - List.of(), OptionalInt.empty(), OptionalDouble.empty(), Optional.empty(), Optional.empty(), Map.of(), Optional.empty())); + assertThrows(NullPointerException.class, () -> new ItemDrop(STICK, 1, null, List.of(), List.of(), ItemDrop.Wear.NEW, + ItemDrop.PlatformExtras.NONE, Optional.empty())); assertThrows(NullPointerException.class, () -> new AmbientEffects.Effect(null, Optional.empty(), List.of(), Optional.empty())); assertThrows(NullPointerException.class, () -> new EntitySpawns.MarkerRule(null, false, false)); } @Test - void anEntityKnowsWhetherItIsAnotherPluginsMob() { - EntitySpec zombie = entity(Optional.of("minecraft:zombie"), Optional.empty()); - EntitySpec special = entity(Optional.empty(), Optional.of("mythic:dragon")); + void aProvidedKeyKeepsTheProvidersNameAsWrittenAndRefusesABlankOne() { + ContentKey mob = new ContentKey.Provided("mmoitems_SWORD", "EXCALIBUR:Gold"); - assertFalse(zombie.isSpecial()); - assertTrue(special.isSpecial()); + assertEquals("mmoitems_SWORD:EXCALIBUR:Gold", mob.toString()); + assertThrows(IllegalArgumentException.class, () -> new ContentKey.Provided("mythicmobs", " ")); + } + + @Test + void aPlatformKeyAsPacksWriteItBecomesAMinecraftIdUnlessItNamesANamespace() { + assertEquals(ResourceId.parse("minecraft:diamond_sword"), ResourceId.ofPlatformKey(" DIAMOND_SWORD ")); + assertEquals(ResourceId.parse("minecraft:fire_protection"), ResourceId.ofPlatformKey("Fire Protection")); + assertEquals(ResourceId.parse("mymod:vorpal"), ResourceId.ofPlatformKey("mymod:vorpal")); + assertThrows(IllegalArgumentException.class, () -> ResourceId.ofPlatformKey("a:b:c")); + } + + @Test + void anEntityHandsAHostTheExtensionItReadsAndNothingForAnotherType() { + EntitySpec zombie = entity(List.of("iris extras")); + + assertEquals(Optional.of("iris extras"), zombie.extension(String.class)); + assertEquals(Optional.empty(), zombie.extension(Integer.class)); } @Test void anAttemptSaysWhetherLightMatters() { BlockPosition at = new BlockPosition(1, 2, 3); - EntitySpec zombie = entity(Optional.of("minecraft:zombie"), Optional.empty()); + EntitySpec zombie = entity(List.of()); 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()); @@ -79,7 +97,7 @@ class ItemAndEntityValuesTest { List commands = new ArrayList<>(List.of( new AmbientEffects.Command(new EntitySpec.Command(List.of("say hi"), 0, false, 100), 1, 0, -1))); AmbientEffects.Effect effect = new AmbientEffects.Effect(Optional.empty(), Optional.empty(), commands, - Optional.of(new AmbientEffects.Potion("luck", 0, 100))); + Optional.of(new AmbientEffects.Potion(ResourceId.parse("minecraft:luck"), 0, 100))); commands.clear(); assertEquals(1, effect.commands().size()); @@ -88,9 +106,9 @@ class ItemAndEntityValuesTest { assertThrows(NullPointerException.class, () -> new AmbientEffects.Command(null, 0, 0, 0)); } - private static EntitySpec entity(Optional type, Optional specialType) { - return new EntitySpec(type, specialType, Optional.empty(), Optional.empty(), new EntitySpec.Flags(false, true, true, false, - true, false, false, false, false, false, false), EntitySpec.Equipment.NONE, List.of(), List.of(), List.of(), 0L, - Optional.empty(), Optional.empty(), false, Optional.empty(), Optional.empty(), false, List.of()); + private static EntitySpec entity(List extensions) { + return new EntitySpec(new ContentKey.Registered(ResourceId.parse("minecraft:zombie")), EntitySpec.Appearance.PLAIN, + EntitySpec.Behaviour.NATURAL, EntitySpec.Equipment.NONE, List.of(), EntitySpec.Company.NONE, + EntitySpec.Drops.PLATFORM, EntitySpec.Arrival.QUIET, extensions); } } diff --git a/host/src/main/java/com/volmit/host/OptionsMetadata.java b/host/src/main/java/com/volmit/host/OptionsMetadata.java index eeddb16fe..74bd0e73d 100644 --- a/host/src/main/java/com/volmit/host/OptionsMetadata.java +++ b/host/src/main/java/com/volmit/host/OptionsMetadata.java @@ -7,7 +7,6 @@ import com.volmit.config.MinNumber; import com.volmit.config.Ref; import com.volmit.config.Reference; import com.volmit.config.Required; -import com.volmit.config.ResourceRef; import com.volmit.config.Snippet; import java.lang.reflect.Field; import java.lang.reflect.Modifier; @@ -25,7 +24,8 @@ public record OptionsMetadata(String description, String snippet, List