Type platform keys and fold pack references into @Ref(kind)

Batch 6, findings 41 and 42.

- Platform keys travel as ResourceId: enchantments, attributes, sounds,
  particles, potions, loot tables, sapling species, marker tags, upper
  dimension ids and jigsaw start pools. ResourceId.ofPlatformKey normalises
  a key a pack wrote.
- Item and entity types are a ContentKey (Registered id, or Provided
  provider and name) instead of strings and a special-type flag.
- ItemDrop groups into Look, Wear and PlatformExtras; colours are an RGB
  int and DyeColor, attribute operations an enum.
- EntitySpec groups into Appearance, Behaviour, Company, Drops and Arrival,
  and carries host extensions instead of Iris-only fields.
- @Ref(kind = Type.class) replaces @ResourceRef and the PACK_* references;
  expressions and image maps become the host kinds EXPRESSIONS and
  IMAGE_MAPS.
This commit is contained in:
piexel committed 2026-10-24 06:06:44 +02:00
1 parent 05f621d82d
commit 6b24e6f150
31 files changed
+620 -295

No files matched your search

+6 -4
View File
@@ -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/<name>"` or `"snippet/<folder>/<name>"` string of a `@Snippet` type from
`snippet/<folder>/<name>.json`. Complete `NOISE_STYLE`, `PACK_EXPRESSION` and `PACK_IMAGE_MAP` references;
`snippet/<folder>/<name>.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
+32 -14
View File
@@ -743,7 +743,7 @@ core engine is modules as well. The host's own JSON fields are not in it; no key
| `List<E>`, `E[]` | `ListKind(E, false)` |
| `Set<E>` | `ListKind(E, true)` |
| `Map<String, V>` | `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<ResourceId>` 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
+31 -20
View File
@@ -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<String> 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> 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
+13 -4
View File
@@ -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;
}
@@ -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
}
@@ -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();
}
@@ -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<String> type, Optional<String> specialType, Optional<String> reason, Optional<String> customName,
Flags flags, Equipment equipment, List<EntitySpec> passengers, List<ItemAttribute> attributes,
List<ResourceId> lootTables, long lootShuffleSeed, Optional<EntitySpec> leashHolder,
Optional<SpawnEffect> spawnEffect, boolean riseOutOfGround, Optional<String> pandaMainGene,
Optional<String> pandaHiddenGene, boolean applySettingsToSpecial, List<Command> commands) {
public record EntitySpec(ContentKey type, Appearance appearance, Behaviour behaviour, Equipment equipment,
List<ItemAttribute> attributes, Company company, Drops drops, Arrival arrival, List<Object> 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 <T> Optional<T> extension(Class<T> 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<String> 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<String> type, Optional<String> 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<String> sound, int soundDistance, double minPitch, double maxPitch, double volume,
Optional<String> particle, int particleOffset, int particleCount, double altX, double altY,
double altZ, boolean randomAltX, boolean randomAltY, boolean randomAltZ, double extra) {
public record Company(List<EntitySpec> passengers, Optional<EntitySpec> 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<ResourceId> 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<SpawnEffect> effect, List<Command> 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> sound, Optional<Burst> 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) {
}
}
@@ -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
}
@@ -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
}
}
+70 -31
View File
@@ -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<String> displayName, List<String> lore, List<ItemEnchantment> enchantments,
List<ItemAttribute> attributes, boolean unbreakable, List<String> flags, OptionalInt customModel,
OptionalDouble damage, Optional<String> leatherColor, Optional<String> dyeColor, Map<String, Object> customNbt,
Optional<Source> source) {
public record ItemDrop(ContentKey item, int amount, Look look, List<ItemEnchantment> enchantments,
List<ItemAttribute> attributes, Wear wear, PlatformExtras extras, Optional<Source> 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<String> displayName, List<String> lore, OptionalInt customModel, OptionalInt leatherColor,
Optional<DyeColor> 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<String> flags, Map<String, Object> customNbt) {
public static final PlatformExtras NONE = new PlatformExtras(List.of(), Map.of());
public PlatformExtras {
flags = List.copyOf(flags);
customNbt = Collections.unmodifiableMap(new LinkedHashMap<>(customNbt));
}
}
/**
@@ -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);
@@ -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);
}
@@ -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<String> expression() {
/** The pack expression that replaces the base style, by the id the pack gives its key; see {@link PackResources#EXPRESSIONS}. */
public Optional<ResourceId> expression() {
return Optional.ofNullable(expression);
}
/** The key of the pack image map that replaces the base style when there is no expression. */
public Optional<String> imageMap() {
/** The pack image map that replaces the base style when there is no expression; see {@link PackResources#IMAGE_MAPS}. */
public Optional<ResourceId> imageMap() {
return Optional.ofNullable(imageMap);
}
@@ -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");
}
}
@@ -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");
}
}
@@ -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;
}
}
}
@@ -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<GeneratedObject> 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<PackExpression> 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<PackImageMap> 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)}.
*/
@@ -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<ResourceId> {
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<Re
return new ResourceId(namespace, NOT_PATH.matcher(key.toLowerCase(Locale.ROOT)).replaceAll(PATH_REPLACEMENT));
}
/**
* The id of a platform key as packs write it, such as {@code minecraft:diamond_sword} for {@code DIAMOND_SWORD} or
* {@code Diamond Sword}: trimmed, lower-cased, spaces as {@code _}, in the {@code minecraft} namespace when it names
* none. Throws IllegalArgumentException when the result is still no id, such as for {@code a:b:c}.
*/
public static ResourceId ofPlatformKey(String key) {
Objects.requireNonNull(key, "key");
String normalized = key.trim().toLowerCase(Locale.ROOT).replace(' ', '_');
return parse(normalized.indexOf(':') < 0 ? PLATFORM_NAMESPACE + ":" + normalized : normalized);
}
@Override
public String toString() { return namespace + ":" + path; }
@@ -2,6 +2,7 @@ package com.volmit.service;
import com.volmit.entity.EntitySpec;
import com.volmit.geometry.BlockPosition;
import com.volmit.resource.ResourceId;
import com.volmit.world.PackWorld;
import java.util.List;
import java.util.Objects;
@@ -44,34 +45,46 @@ public interface AmbientEffects {
/**
* A sound played to the player.
*
* @param key the platform's sound key
* @param key the sound, such as {@code minecraft:ambient.cave}
* @param offsetX blocks from the player where the sound seems to come from, as the other offsets
* @param volume the sound's volume
* @param pitch the sound's pitch
*/
record Sound(String key, int offsetX, int offsetY, int offsetZ, float volume, float pitch) {
record Sound(ResourceId key, int offsetX, int offsetY, int offsetZ, float volume, float pitch) {
public Sound {
Objects.requireNonNull(key, "key");
}
}
/**
* Particles shown to the player. They appear {@code forward} blocks ahead of the player, {@code sideways} blocks to
* the right (negative for the left) and on the surface at that spot, one block up, moved by {@code jitterX} and
* {@code jitterZ} and by {@code lift} blocks up.
* Particles shown to the player.
*
* @param key the platform's particle key
* @param count how many particles; none makes {@code altX}, {@code altY} and {@code altZ} their motion
* @param altX the particles' offset or motion, as the other two
* @param extra an extra value some particles take; 0 for none
* @param key the particle, such as {@code minecraft:ash}
* @param spot where they appear
* @param count how many particles; none makes {@code spread} their motion
* @param spread how far the particles spread along each axis, or their motion when {@code count} is 0
* @param extra an extra value some particles take; 0 for none
*/
record Particles(String key, double forward, double sideways, double jitterX, double jitterZ, int lift, int count,
double altX, double altY, double altZ, double extra) {
record Particles(ResourceId key, Spot spot, int count, Spread spread, double extra) {
public Particles {
Objects.requireNonNull(key, "key");
Objects.requireNonNull(spot, "spot");
Objects.requireNonNull(spread, "spread");
}
}
/**
* Where particles appear: {@code forward} blocks ahead of the player, {@code sideways} blocks to the right (negative
* for the left) and on the surface at that spot, one block up, moved by {@code jitterX} and {@code jitterZ} and by
* {@code lift} blocks up.
*/
record Spot(double forward, double sideways, double jitterX, double jitterZ, int lift) {
}
/** A distance along each axis. */
record Spread(double x, double y, double z) {
}
/**
* A command to run where the effect plays.
*
@@ -88,11 +101,11 @@ public interface AmbientEffects {
/**
* A potion effect for the player. A player who has the same potion effect with a stronger amplifier keeps it.
*
* @param key the platform's potion effect key
* @param key the potion effect, such as {@code minecraft:night_vision}
* @param strength the amplifier
* @param ticks how long it lasts, in server ticks
*/
record Potion(String key, int strength, int ticks) {
record Potion(ResourceId key, int strength, int ticks) {
public Potion {
Objects.requireNonNull(key, "key");
}
@@ -25,8 +25,12 @@ public interface EntitySpawns {
/** The pack's entity {@code entity} as this module would spawn it, for tools that spawn one on request; empty for an unknown one. */
Optional<EntitySpec> entity(PackWorld world, ResourceId entity);
/** What a marker in the world means for spawning; empty for a marker this module does not know. */
Optional<MarkerRule> 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<MarkerRule> 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");
@@ -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");
}
}
}
@@ -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");
@@ -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<ResourceId> 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<ResourceId> 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<ResourceId> 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();
}
}
@@ -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();
@@ -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<ItemEnchantment> 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<ItemEnchantment> 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<AmbientEffects.Command> 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<String> type, Optional<String> 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<Object> 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);
}
}
@@ -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<Option> o
}
/** One field of a settings type. {@code minimum}, {@code maximum}, {@code minItems}, {@code reference} and
* {@code resource} are null when not declared; {@code resource} is the class of {@link ResourceRef}.
* {@code resource} are null when not declared; {@code reference} is the registry and {@code resource} the
* kind's type a {@link Ref} gives, of which at most one is set.
*/
public record Option(Field field, String description, boolean required,
Double minimum, Double maximum, Integer minItems, Reference reference, Class<?> resource) {
@@ -59,7 +59,6 @@ public record OptionsMetadata(String description, String snippet, List<Option> o
var max = field.getAnnotation(MaxNumber.class);
var minItems = field.getAnnotation(MinItems.class);
var ref = field.getAnnotation(Ref.class);
var resourceRef = field.getAnnotation(ResourceRef.class);
if ((min != null || max != null) && !isNumeric(field.getType())) {
throw new IllegalArgumentException("Numeric bounds on nonnumeric option: " + field.getName());
}
@@ -72,10 +71,15 @@ public record OptionsMetadata(String description, String snippet, List<Option> o
throw new IllegalArgumentException("Invalid @MinItems on option: " + field.getName()
+ "; it fits lists, sets and arrays, and its value is not negative");
}
if (ref != null && ref.value().length + (ref.kind() == void.class ? 0 : 1) != 1) {
throw new IllegalArgumentException("Invalid @Ref on option: " + field.getName()
+ "; give exactly one of a Reference or a kind");
}
options.add(new Option(field, desc == null ? "" : desc.value(), field.isAnnotationPresent(Required.class),
min == null ? null : min.value(), max == null ? null : max.value(),
minItems == null ? null : minItems.value(),
ref == null ? null : ref.value(), resourceRef == null ? null : resourceRef.value()));
ref == null || ref.value().length == 0 ? null : ref.value()[0],
ref == null || ref.kind() == void.class ? null : ref.kind()));
}
}
var desc = type.getAnnotation(Desc.class);
@@ -20,8 +20,8 @@ import java.util.regex.Pattern;
import java.util.stream.Stream;
/** Describes a loaded pack's catalogued settings and resource kinds for studio. Fails the load, naming the class,
* field and module, on what the host could not render: an unsupported field type, a misplaced {@code @Ref} or
* {@code @ResourceRef}, a class without a usable no-argument constructor, a snippet name used twice, a pack
* field and module, on what the host could not render: an unsupported field type, a misplaced {@code @Ref} or one
* naming a kind nobody has, a class without a usable no-argument constructor, a snippet name used twice, a pack
* class's snippet name outside its module's path, or a pack module's resource kind read into a host type.
*/
@SuppressWarnings("removal") // held types and host kinds are transitional, until the cut-over
@@ -32,7 +32,7 @@ final class TypeDrafts {
private final HostTypes hostTypes;
private final Function<Class<?>, Optional<ResourceId>> resourceKinds;
/** @param resourceKinds the id of the resource kind read into a class, which {@code @ResourceRef} options name */
/** @param resourceKinds the id of the module resource kind read into a class, which {@code @Ref(kind = ...)} options name */
TypeDrafts(HostTypes hostTypes, Function<Class<?>, Optional<ResourceId>> resourceKinds) {
this.hostTypes = hostTypes;
this.resourceKinds = resourceKinds;
@@ -18,20 +18,23 @@ import com.volmit.host.schema.ValueKind.ObjectKind;
import com.volmit.host.schema.ValueKind.ReferenceKind;
import com.volmit.host.schema.ValueKind.ResourceReferenceKind;
import com.volmit.host.schema.ValueKind.TextKind;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import com.volmit.resource.ResourceKind;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/** Maps a settings field's declared type, {@code @Ref} and {@code @ResourceRef} to the JSON it takes. Host types
/** Maps a settings field's declared type and {@code @Ref} to the JSON it takes. Host types
* become host kinds where the settings may use them; other classes that are none of the built-in kinds become
* object kinds through the given function. Throws {@link SettingsTypeProblem} for a type or reference that does
* not fit.
@@ -45,8 +48,9 @@ final class ValueKinds {
Byte.class, Short.class, Integer.class, Long.class);
private static final Set<Class<?>> DECIMALS = Set.of(float.class, double.class, Float.class, Double.class);
private static final String DECLARE_COLLECTION = "declare it as List<...>, Set<...> or Map<String, ...>";
private static final Set<Reference> PACK_REFERENCES = EnumSet.of(Reference.PACK_BIOME, Reference.PACK_REGION, Reference.PACK_OBJECT,
Reference.PACK_EXPRESSION, Reference.PACK_IMAGE_MAP, Reference.PACK_STRUCTURE);
private static final Map<Class<?>, ResourceId> HOST_KINDS = Stream.of(PackResources.BIOMES, PackResources.REGIONS,
PackResources.OBJECTS, PackResources.EXPRESSIONS, PackResources.IMAGE_MAPS)
.collect(Collectors.toUnmodifiableMap(ResourceKind::type, ResourceKind::id));
private final Function<Class<?>, ObjectKind> objects;
private final HostTypes hostTypes;
@@ -68,13 +72,19 @@ final class ValueKinds {
return kind(option.type(), new Naming(option.reference(), option.resource()));
}
/** What a text option names: the field's {@code @Ref} and the class of its {@code @ResourceRef}, each null when absent. */
/** What a text option names: the registry or the kind's type of the field's {@code @Ref}, each null when absent. */
private record Naming(Reference reference, Class<?> resource) {
static final Naming NONE = new Naming(null, null);
boolean isEmpty() {
return reference == null && resource == null;
}
/** The annotation as written, for messages. */
@Override
public String toString() {
return reference != null ? "@Ref(" + reference + ")" : "@Ref(kind = " + resource.getName() + ")";
}
}
/** Lists, sets and arrays pass {@code naming} on to their elements. */
@@ -127,37 +137,29 @@ final class ValueKinds {
}
private ValueKind text(TextFormat format, Naming naming) {
if (naming.resource() != null) return resourceReference(naming);
if (naming.resource() != null) return resourceReference(naming.resource());
var reference = naming.reference();
if (reference == null) return new TextKind(format);
if (PACK_REFERENCES.contains(reference)) return new ReferenceKind(reference, TextFormat.PLAIN);
return new ReferenceKind(reference, format);
}
/** Packs name a kind's resources by key without a namespace, as they name their biomes, so the JSON holds a key
* whether the field is a String or a ResourceId (which the host reads as the pack's id of that key).
*/
private ValueKind resourceReference(Naming naming) {
var resource = naming.resource();
if (naming.reference() != null) {
throw new SettingsTypeProblem("has both @Ref(" + naming.reference() + ") and @ResourceRef(" + resource.getName()
+ "); an option names one kind of thing, so keep one");
}
private ValueKind resourceReference(Class<?> resource) {
var hostKind = HOST_KINDS.get(resource);
if (hostKind != null) return new ResourceReferenceKind(hostKind);
return resourceKinds.apply(resource).map(ResourceReferenceKind::new).orElseThrow(() -> new SettingsTypeProblem(
"has @ResourceRef(" + resource.getName() + "), but no module of the pack registers a resource kind read into"
+ " that class; name the class of a kind registered with FeatureRegistry.registerResourceKind"));
"has @Ref(kind = " + resource.getName() + "), but neither the host nor a module of the pack has a resource kind"
+ " read into that class; name the type of a PackResources kind or of a kind registered with"
+ " FeatureRegistry.registerResourceKind"));
}
private static ValueKind blockState(Naming naming) {
var reference = naming.reference();
if (naming.resource() == null && (reference == null || reference == Reference.BLOCK)) {
if (naming.isEmpty() || naming.reference() == Reference.BLOCK) {
return new ReferenceKind(Reference.BLOCK, TextFormat.BLOCK_STATE);
}
if (naming.resource() != null) {
throw new SettingsTypeProblem("has @ResourceRef(" + naming.resource().getName() + ") on BlockState, which always"
+ " names a block; remove the @ResourceRef or use String");
}
throw new SettingsTypeProblem("has @Ref(" + reference + ") on BlockState, which always names a block;"
throw new SettingsTypeProblem("has " + naming + " on BlockState, which always names a block;"
+ " remove the @Ref or use String or ResourceId");
}
@@ -180,12 +182,8 @@ final class ValueKinds {
private static void requireNoNaming(Type type, Naming naming) {
if (naming.isEmpty()) return;
if (naming.reference() != null) {
throw new SettingsTypeProblem("has @Ref(" + naming.reference() + ") on " + type.getTypeName()
+ ", but @Ref fits only String and ResourceId and lists, sets and arrays of them");
}
throw new SettingsTypeProblem("has @ResourceRef(" + naming.resource().getName() + ") on " + type.getTypeName()
+ ", but @ResourceRef fits only String and ResourceId and lists, sets and arrays of them");
throw new SettingsTypeProblem("has " + naming + " on " + type.getTypeName()
+ ", but @Ref fits only String and ResourceId and lists, sets and arrays of them");
}
private static boolean isCollection(Class<?> type) {
@@ -39,8 +39,12 @@ class VanillaStructureValuesTest {
"liquidSettings"), names(JigsawOverrides.class));
assertEquals(OptionalInt.empty(), JigsawOverrides.none().maxDepth());
assertEquals(JigsawOverrides.Heightmap.SOURCE, JigsawOverrides.none().projectStartToHeightmap());
var overrides = JigsawOverrides.none().withStartPool("minecraft:village/plains/town_centers").withMaxDepth(4)
var pool = com.volmit.resource.ResourceId.parse("minecraft:village/plains/town_centers");
var overrides = JigsawOverrides.none().withStartPool(pool).withMaxDepth(4)
.withMaxDistance(80, 120).withHeightmap(JigsawOverrides.Heightmap.NONE);
assertEquals(Optional.of(pool), overrides.startPool());
assertTrue(JigsawOverrides.none().withoutStartJigsaw().removesStartJigsaw());
assertNotEquals(JigsawOverrides.none(), JigsawOverrides.none().withoutStartJigsaw());
assertEquals(OptionalInt.of(4), overrides.maxDepth());
assertEquals(OptionalInt.of(120), overrides.maxDistanceVertical());
assertEquals(Optional.empty(), overrides.useExpansionHack());
@@ -29,6 +29,7 @@ import com.volmit.host.schema.ValueKind.ObjectKind;
import com.volmit.host.schema.ValueKind.ReferenceKind;
import com.volmit.host.schema.ValueKind.ResourceReferenceKind;
import com.volmit.host.schema.ValueKind.TextKind;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import com.volmit.resource.ResourceKind;
import com.volmit.support.TestModuleJar;
@@ -89,7 +90,7 @@ class PackSchemaTest {
private ResourceId palette = ResourceId.parse("example:flora/default");
@Ref(Reference.BLOCK)
private String ground = "minecraft:grass_block";
@Ref(Reference.PACK_BIOME) @MinItems(1)
@Ref(kind = com.volmit.world.PackBiome.class) @MinItems(1)
private List<String> biomes = List.of("plains", "forest");
@Ref(Reference.ITEM)
private ResourceId[] drops = {};
@@ -261,7 +262,7 @@ class PackSchemaTest {
var settings = floraSchema().type("pack.flora.FloraSettings");
assertEquals(new ReferenceKind(Reference.BLOCK, TextFormat.PLAIN), option(settings, "ground").kind());
assertEquals(new ListKind(new ReferenceKind(Reference.PACK_BIOME, TextFormat.PLAIN), false), option(settings, "biomes").kind());
assertEquals(new ListKind(new ResourceReferenceKind(PackResources.BIOMES.id()), false), option(settings, "biomes").kind());
assertEquals(Optional.of(List.of("plains", "forest")), option(settings, "biomes").defaultValue());
assertEquals(OptionalInt.of(1), option(settings, "biomes").minItems(), "@MinItems is described");
assertEquals(OptionalInt.empty(), option(settings, "drops").minItems());
@@ -544,8 +545,8 @@ class PackSchemaTest {
var style = schema.type("com.volmit.noise.NoiseStyle");
assertEquals(Optional.of("style"), style.snippet(), "API classes keep the snippet folders packs already use");
assertEquals(new ReferenceKind(Reference.NOISE_STYLE, TextFormat.PLAIN), option(style, "style").kind());
assertEquals(new ReferenceKind(Reference.PACK_EXPRESSION, TextFormat.PLAIN), option(style, "expression").kind());
assertEquals(new ReferenceKind(Reference.PACK_IMAGE_MAP, TextFormat.PLAIN), option(style, "imageMap").kind());
assertEquals(new ResourceReferenceKind(PackResources.EXPRESSIONS.id()), option(style, "expression").kind());
assertEquals(new ResourceReferenceKind(PackResources.IMAGE_MAPS.id()), option(style, "imageMap").kind());
assertEquals(Optional.of("FLAT"), option(style, "style").defaultValue());
assertEquals(List.of("palette", "range", "style", "style-range"), schema.snippets().stream().map(type -> type.snippet().orElseThrow()).toList());
}
@@ -684,16 +685,16 @@ class PackSchemaTest {
@Feature(id = "example:flora", name = "Flora", key = "flora", targets = Level.BIOME)
public final class FloraSettings implements IrisFeature {
@Ref(Reference.PACK_BIOME) private ResourceId home;
@Ref(Reference.PACK_OBJECT) private List<ResourceId> objects = List.of();
@Ref(kind = com.volmit.world.PackBiome.class) private ResourceId home;
@Ref(kind = com.volmit.object.GeneratedObject.class) private List<ResourceId> objects = List.of();
}
""")
.writeInto(pack, "flora.jar");
var settings = schemaOf(pack, NO_BUILT_INS).type("pack.flora.FloraSettings");
assertEquals(new ReferenceKind(Reference.PACK_BIOME, TextFormat.PLAIN), option(settings, "home").kind());
assertEquals(new ListKind(new ReferenceKind(Reference.PACK_OBJECT, TextFormat.PLAIN), false), option(settings, "objects").kind());
assertEquals(new ResourceReferenceKind(PackResources.BIOMES.id()), option(settings, "home").kind());
assertEquals(new ListKind(new ResourceReferenceKind(PackResources.OBJECTS.id()), false), option(settings, "objects").kind());
}
@Test
@@ -732,7 +733,7 @@ class PackSchemaTest {
public final class Keep {
@Desc("Towers on the walls") @MinNumber(1)
private int towers = 4;
@ResourceRef(Keep.class)
@Ref(kind = Keep.class)
private String next = "";
}
""")
@@ -746,7 +747,7 @@ class PackSchemaTest {
@Feature(id = "example:castle", name = "Castle", key = "castle", targets = Level.BIOME)
public final class CastleSettings implements IrisFeature {
@ResourceRef(Keep.class)
@Ref(kind = Keep.class)
private List<String> keeps = List.of("main");
}
""");
@@ -818,15 +819,16 @@ class PackSchemaTest {
@Test
void resourceReferencesNameARegisteredKindOnPlainText() {
assertLoadFails("Field pack.flora.FloraSettings.keep of " + FLORA_SOURCE + " has @ResourceRef(java.lang.Integer), but no"
+ " module of the pack registers a resource kind read into that class; name the class of a kind registered with"
+ " FeatureRegistry.registerResourceKind", "@ResourceRef(Integer.class) private String keep;");
assertLoadFails("Field pack.flora.FloraSettings.count of " + FLORA_SOURCE + " has @ResourceRef(java.lang.Integer) on int,"
+ " but @ResourceRef fits only String and ResourceId and lists, sets and arrays of them",
"@ResourceRef(Integer.class) private int count;");
assertLoadFails("Field pack.flora.FloraSettings.keep of " + FLORA_SOURCE + " has both @Ref(BLOCK) and"
+ " @ResourceRef(java.lang.Integer); an option names one kind of thing, so keep one",
"@Ref(Reference.BLOCK) @ResourceRef(Integer.class) private String keep;");
assertLoadFails("Field pack.flora.FloraSettings.keep of " + FLORA_SOURCE + " has @Ref(kind = java.lang.Integer), but"
+ " neither the host nor a module of the pack has a resource kind read into that class; name the type of a"
+ " PackResources kind or of a kind registered with FeatureRegistry.registerResourceKind",
"@Ref(kind = Integer.class) private String keep;");
assertLoadFails("Field pack.flora.FloraSettings.count of " + FLORA_SOURCE + " has @Ref(kind = java.lang.Integer) on int,"
+ " but @Ref fits only String and ResourceId and lists, sets and arrays of them",
"@Ref(kind = Integer.class) private int count;");
assertLoadFails("Invalid @Ref on option: keep; give exactly one of a Reference or a kind",
"@Ref(value = Reference.BLOCK, kind = Integer.class) private String keep;");
assertLoadFails("Invalid @Ref on option: keep; give exactly one of a Reference or a kind", "@Ref private String keep;");
}
/** A built-in module {@code id} that registers {@code kind}. */